blob: bca1be584edd290eb8d06f3c99e695203cd72f82 [file] [log] [blame]
Damien92c06562013-10-22 22:32:27 +01001#include "misc.h"
Damien George136f6752014-01-07 14:54:15 +00002#include "mpconfig.h"
Damien92c06562013-10-22 22:32:27 +01003#include "repl.h"
4
Damien George136f6752014-01-07 14:54:15 +00005#if MICROPY_ENABLE_REPL_HELPERS
6
Damien92c06562013-10-22 22:32:27 +01007bool str_startswith_word(const char *str, const char *head) {
8 int i;
9 for (i = 0; str[i] && head[i]; i++) {
10 if (str[i] != head[i]) {
11 return false;
12 }
13 }
Damien George8cc96a32013-12-30 18:23:50 +000014 return head[i] == '\0' && (str[i] == '\0' || !unichar_isalpha(str[i]));
Damien92c06562013-10-22 22:32:27 +010015}
16
Damiend99b0522013-12-21 18:17:45 +000017bool mp_repl_is_compound_stmt(const char *line) {
Damien92c06562013-10-22 22:32:27 +010018 // compound if line starts with a certain keyword
19 if (
20 str_startswith_word(line, "if")
21 || str_startswith_word(line, "while")
22 || str_startswith_word(line, "for")
Paul Sokolovskye06edce2014-01-10 16:13:06 +020023 || str_startswith_word(line, "try")
Damien92c06562013-10-22 22:32:27 +010024 || str_startswith_word(line, "with")
25 || str_startswith_word(line, "def")
26 || str_startswith_word(line, "class")
27 || str_startswith_word(line, "@")
28 ) {
29 return true;
30 }
31
Damien Georgea28507a2014-04-07 13:01:30 +010032 // also "compound" if unmatched open bracket or triple quote
Damien92c06562013-10-22 22:32:27 +010033 int n_paren = 0;
34 int n_brack = 0;
35 int n_brace = 0;
Damien Georgea28507a2014-04-07 13:01:30 +010036 int in_triple_quote = 0;
Damien92c06562013-10-22 22:32:27 +010037 for (const char *l = line; *l; l++) {
38 switch (*l) {
39 case '(': n_paren += 1; break;
40 case ')': n_paren -= 1; break;
41 case '[': n_brack += 1; break;
42 case ']': n_brack -= 1; break;
43 case '{': n_brace += 1; break;
44 case '}': n_brace -= 1; break;
Damien Georgea28507a2014-04-07 13:01:30 +010045 case '"':
46 if (l[1] == '"' && l[2] == '"') {
47 l += 2;
48 in_triple_quote = 1 - in_triple_quote;
49 }
50 break;
Damien92c06562013-10-22 22:32:27 +010051 }
52 }
Damien Georgea28507a2014-04-07 13:01:30 +010053 return n_paren > 0 || n_brack > 0 || n_brace > 0 || in_triple_quote != 0;
Damien92c06562013-10-22 22:32:27 +010054}
Damien George136f6752014-01-07 14:54:15 +000055
56#endif // MICROPY_ENABLE_REPL_HELPERS