repl.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013-2015 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <string.h>
  27. #include "py/obj.h"
  28. #include "py/objmodule.h"
  29. #include "py/runtime.h"
  30. #include "py/builtin.h"
  31. #include "py/repl.h"
  32. #if MICROPY_HELPER_REPL
  33. #if MICROPY_PY_SYS_PS1_PS2
  34. const char *mp_repl_get_psx(unsigned int entry) {
  35. if (mp_obj_is_str(MP_STATE_VM(sys_mutable)[entry])) {
  36. return mp_obj_str_get_str(MP_STATE_VM(sys_mutable)[entry]);
  37. } else {
  38. return "";
  39. }
  40. }
  41. #endif
  42. static bool str_startswith_word(const char *str, const char *head) {
  43. size_t i;
  44. for (i = 0; str[i] && head[i]; i++) {
  45. if (str[i] != head[i]) {
  46. return false;
  47. }
  48. }
  49. return head[i] == '\0' && (str[i] == '\0' || !unichar_isident(str[i]));
  50. }
  51. bool mp_repl_continue_with_input(const char *input) {
  52. // check for blank input
  53. if (input[0] == '\0') {
  54. return false;
  55. }
  56. // check if input starts with a certain keyword
  57. bool starts_with_compound_keyword =
  58. input[0] == '@'
  59. || str_startswith_word(input, "if")
  60. || str_startswith_word(input, "while")
  61. || str_startswith_word(input, "for")
  62. || str_startswith_word(input, "try")
  63. || str_startswith_word(input, "with")
  64. || str_startswith_word(input, "def")
  65. || str_startswith_word(input, "class")
  66. #if MICROPY_PY_ASYNC_AWAIT
  67. || str_startswith_word(input, "async")
  68. #endif
  69. ;
  70. // check for unmatched open bracket, quote or escape quote
  71. #define Q_NONE (0)
  72. #define Q_1_SINGLE (1)
  73. #define Q_1_DOUBLE (2)
  74. #define Q_3_SINGLE (3)
  75. #define Q_3_DOUBLE (4)
  76. int n_paren = 0;
  77. int n_brack = 0;
  78. int n_brace = 0;
  79. int in_quote = Q_NONE;
  80. const char *i;
  81. for (i = input; *i; i++) {
  82. if (*i == '\'') {
  83. if ((in_quote == Q_NONE || in_quote == Q_3_SINGLE) && i[1] == '\'' && i[2] == '\'') {
  84. i += 2;
  85. in_quote = Q_3_SINGLE - in_quote;
  86. } else if (in_quote == Q_NONE || in_quote == Q_1_SINGLE) {
  87. in_quote = Q_1_SINGLE - in_quote;
  88. }
  89. } else if (*i == '"') {
  90. if ((in_quote == Q_NONE || in_quote == Q_3_DOUBLE) && i[1] == '"' && i[2] == '"') {
  91. i += 2;
  92. in_quote = Q_3_DOUBLE - in_quote;
  93. } else if (in_quote == Q_NONE || in_quote == Q_1_DOUBLE) {
  94. in_quote = Q_1_DOUBLE - in_quote;
  95. }
  96. } else if (*i == '\\' && (i[1] == '\'' || i[1] == '"' || i[1] == '\\')) {
  97. if (in_quote != Q_NONE) {
  98. i++;
  99. }
  100. } else if (in_quote == Q_NONE) {
  101. switch (*i) {
  102. case '(':
  103. n_paren += 1;
  104. break;
  105. case ')':
  106. n_paren -= 1;
  107. break;
  108. case '[':
  109. n_brack += 1;
  110. break;
  111. case ']':
  112. n_brack -= 1;
  113. break;
  114. case '{':
  115. n_brace += 1;
  116. break;
  117. case '}':
  118. n_brace -= 1;
  119. break;
  120. default:
  121. break;
  122. }
  123. }
  124. }
  125. // continue if unmatched 3-quotes
  126. if (in_quote == Q_3_SINGLE || in_quote == Q_3_DOUBLE) {
  127. return true;
  128. }
  129. // continue if unmatched brackets, but only if not in a 1-quote
  130. if ((n_paren > 0 || n_brack > 0 || n_brace > 0) && in_quote == Q_NONE) {
  131. return true;
  132. }
  133. // continue if last character was backslash (for line continuation)
  134. if (i[-1] == '\\') {
  135. return true;
  136. }
  137. // continue if compound keyword and last line was not empty
  138. if (starts_with_compound_keyword && i[-1] != '\n') {
  139. return true;
  140. }
  141. // otherwise, don't continue
  142. return false;
  143. }
  144. static bool test_qstr(mp_obj_t obj, qstr name) {
  145. if (obj) {
  146. // try object member
  147. mp_obj_t dest[2];
  148. mp_load_method_protected(obj, name, dest, true);
  149. return dest[0] != MP_OBJ_NULL;
  150. } else {
  151. // try builtin module
  152. return mp_map_lookup((mp_map_t *)&mp_builtin_module_map, MP_OBJ_NEW_QSTR(name), MP_MAP_LOOKUP) ||
  153. mp_map_lookup((mp_map_t *)&mp_builtin_extensible_module_map, MP_OBJ_NEW_QSTR(name), MP_MAP_LOOKUP);
  154. }
  155. }
  156. static const char *find_completions(const char *s_start, size_t s_len,
  157. mp_obj_t obj, size_t *match_len, qstr *q_first, qstr *q_last) {
  158. const char *match_str = NULL;
  159. *match_len = 0;
  160. *q_first = *q_last = 0;
  161. size_t nqstr = QSTR_TOTAL();
  162. for (qstr q = MP_QSTR_ + 1; q < nqstr; ++q) {
  163. size_t d_len;
  164. const char *d_str = (const char *)qstr_data(q, &d_len);
  165. // special case; filter out words that begin with underscore
  166. // unless there's already a partial match
  167. if (s_len == 0 && d_str[0] == '_') {
  168. continue;
  169. }
  170. if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) {
  171. if (test_qstr(obj, q)) {
  172. if (match_str == NULL) {
  173. match_str = d_str;
  174. *match_len = d_len;
  175. } else {
  176. // search for longest common prefix of match_str and d_str
  177. // (assumes these strings are null-terminated)
  178. for (size_t j = s_len; j <= *match_len && j <= d_len; ++j) {
  179. if (match_str[j] != d_str[j]) {
  180. *match_len = j;
  181. break;
  182. }
  183. }
  184. }
  185. if (*q_first == 0) {
  186. *q_first = q;
  187. }
  188. *q_last = q;
  189. }
  190. }
  191. }
  192. return match_str;
  193. }
  194. static void print_completions(const mp_print_t *print,
  195. const char *s_start, size_t s_len,
  196. mp_obj_t obj, qstr q_first, qstr q_last) {
  197. #define WORD_SLOT_LEN (16)
  198. #define MAX_LINE_LEN (4 * WORD_SLOT_LEN)
  199. int line_len = MAX_LINE_LEN; // force a newline for first word
  200. for (qstr q = q_first; q <= q_last; ++q) {
  201. size_t d_len;
  202. const char *d_str = (const char *)qstr_data(q, &d_len);
  203. if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) {
  204. if (test_qstr(obj, q)) {
  205. int gap = (line_len + WORD_SLOT_LEN - 1) / WORD_SLOT_LEN * WORD_SLOT_LEN - line_len;
  206. if (gap < 2) {
  207. gap += WORD_SLOT_LEN;
  208. }
  209. if (line_len + gap + d_len <= MAX_LINE_LEN) {
  210. // TODO optimise printing of gap?
  211. for (int j = 0; j < gap; ++j) {
  212. mp_print_str(print, " ");
  213. }
  214. mp_print_str(print, d_str);
  215. line_len += gap + d_len;
  216. } else {
  217. mp_printf(print, "\n%s", d_str);
  218. line_len = d_len;
  219. }
  220. }
  221. }
  222. }
  223. mp_print_str(print, "\n");
  224. }
  225. size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print, const char **compl_str) {
  226. // scan backwards to find start of "a.b.c" chain
  227. const char *org_str = str;
  228. const char *top = str + len;
  229. for (const char *s = top; --s >= str;) {
  230. if (!(unichar_isalpha(*s) || unichar_isdigit(*s) || *s == '_' || *s == '.')) {
  231. ++s;
  232. str = s;
  233. break;
  234. }
  235. }
  236. // begin search in outer global dict which is accessed from __main__
  237. mp_obj_t obj = MP_OBJ_FROM_PTR(&mp_module___main__);
  238. mp_obj_t dest[2];
  239. const char *s_start;
  240. size_t s_len;
  241. for (;;) {
  242. // get next word in string to complete
  243. s_start = str;
  244. while (str < top && *str != '.') {
  245. ++str;
  246. }
  247. s_len = str - s_start;
  248. if (str == top) {
  249. // end of string, do completion on this partial name
  250. break;
  251. }
  252. // a complete word, lookup in current object
  253. qstr q = qstr_find_strn(s_start, s_len);
  254. if (q == MP_QSTRnull) {
  255. // lookup will fail
  256. return 0;
  257. }
  258. mp_load_method_protected(obj, q, dest, true);
  259. obj = dest[0]; // attribute, method, or MP_OBJ_NULL if nothing found
  260. if (obj == MP_OBJ_NULL) {
  261. // lookup failed
  262. return 0;
  263. }
  264. // skip '.' to move to next word
  265. ++str;
  266. }
  267. // after "import", suggest built-in modules
  268. static const char import_str[] = "import ";
  269. if (len >= 7 && !memcmp(org_str, import_str, 7)) {
  270. obj = MP_OBJ_NULL;
  271. }
  272. // look for matches
  273. size_t match_len;
  274. qstr q_first, q_last;
  275. const char *match_str =
  276. find_completions(s_start, s_len, obj, &match_len, &q_first, &q_last);
  277. // nothing found
  278. if (q_first == 0) {
  279. // If there're no better alternatives, and if it's first word
  280. // in the line, try to complete "import".
  281. if (s_start == org_str && s_len > 0 && s_len < sizeof(import_str) - 1) {
  282. if (memcmp(s_start, import_str, s_len) == 0) {
  283. *compl_str = import_str + s_len;
  284. return sizeof(import_str) - 1 - s_len;
  285. }
  286. }
  287. return 0;
  288. }
  289. // 1 match found, or multiple matches with a common prefix
  290. if (q_first == q_last || match_len > s_len) {
  291. *compl_str = match_str + s_len;
  292. return match_len - s_len;
  293. }
  294. // multiple matches found, print them out
  295. print_completions(print, s_start, s_len, obj, q_first, q_last);
  296. return (size_t)(-1); // indicate many matches
  297. }
  298. #endif // MICROPY_HELPER_REPL