Damien | 92c0656 | 2013-10-22 22:32:27 +0100 | [diff] [blame] | 1 | #include "misc.h" |
| 2 | #include "repl.h" |
| 3 | |
| 4 | bool str_startswith_word(const char *str, const char *head) { |
| 5 | int i; |
| 6 | for (i = 0; str[i] && head[i]; i++) { |
| 7 | if (str[i] != head[i]) { |
| 8 | return false; |
| 9 | } |
| 10 | } |
Damien George | 8cc96a3 | 2013-12-30 18:23:50 +0000 | [diff] [blame] | 11 | return head[i] == '\0' && (str[i] == '\0' || !unichar_isalpha(str[i])); |
Damien | 92c0656 | 2013-10-22 22:32:27 +0100 | [diff] [blame] | 12 | } |
| 13 | |
Damien | d99b052 | 2013-12-21 18:17:45 +0000 | [diff] [blame] | 14 | bool mp_repl_is_compound_stmt(const char *line) { |
Damien | 92c0656 | 2013-10-22 22:32:27 +0100 | [diff] [blame] | 15 | // compound if line starts with a certain keyword |
| 16 | if ( |
| 17 | str_startswith_word(line, "if") |
| 18 | || str_startswith_word(line, "while") |
| 19 | || str_startswith_word(line, "for") |
| 20 | || str_startswith_word(line, "true") |
| 21 | || str_startswith_word(line, "with") |
| 22 | || str_startswith_word(line, "def") |
| 23 | || str_startswith_word(line, "class") |
| 24 | || str_startswith_word(line, "@") |
| 25 | ) { |
| 26 | return true; |
| 27 | } |
| 28 | |
| 29 | // also "compound" if unmatched open bracket |
| 30 | int n_paren = 0; |
| 31 | int n_brack = 0; |
| 32 | int n_brace = 0; |
| 33 | for (const char *l = line; *l; l++) { |
| 34 | switch (*l) { |
| 35 | case '(': n_paren += 1; break; |
| 36 | case ')': n_paren -= 1; break; |
| 37 | case '[': n_brack += 1; break; |
| 38 | case ']': n_brack -= 1; break; |
| 39 | case '{': n_brace += 1; break; |
| 40 | case '}': n_brace -= 1; break; |
| 41 | } |
| 42 | } |
| 43 | return n_paren > 0 || n_brack > 0 || n_brace > 0; |
| 44 | } |