PageRenderTime 73ms CodeModel.GetById 11ms RepoModel.GetById 2ms app.codeStats 2ms

/py/compile.c

https://github.com/jtbattle/micropython
C | 3665 lines | 2885 code | 347 blank | 433 comment | 1051 complexity | 2ff9bcdf9404c0e273c8d9fb58f0a97c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * This file is part of the Micro Python project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 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 <stdbool.h>
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <assert.h>
  31. #include <math.h>
  32. #include "misc.h"
  33. #include "mpconfig.h"
  34. #include "qstr.h"
  35. #include "lexer.h"
  36. #include "parse.h"
  37. #include "runtime0.h"
  38. #include "obj.h"
  39. #include "emitglue.h"
  40. #include "scope.h"
  41. #include "emit.h"
  42. #include "compile.h"
  43. #include "runtime.h"
  44. #include "builtin.h"
  45. #include "smallint.h"
  46. // TODO need to mangle __attr names
  47. #define MICROPY_EMIT_NATIVE (MICROPY_EMIT_X64 || MICROPY_EMIT_THUMB)
  48. typedef enum {
  49. PN_none = 0,
  50. #define DEF_RULE(rule, comp, kind, ...) PN_##rule,
  51. #include "grammar.h"
  52. #undef DEF_RULE
  53. PN_maximum_number_of,
  54. PN_string, // special node for non-interned string
  55. } pn_kind_t;
  56. #define EMIT(fun) (comp->emit_method_table->fun(comp->emit))
  57. #define EMIT_ARG(fun, ...) (comp->emit_method_table->fun(comp->emit, __VA_ARGS__))
  58. #define EMIT_INLINE_ASM(fun) (comp->emit_inline_asm_method_table->fun(comp->emit_inline_asm))
  59. #define EMIT_INLINE_ASM_ARG(fun, ...) (comp->emit_inline_asm_method_table->fun(comp->emit_inline_asm, __VA_ARGS__))
  60. typedef struct _compiler_t {
  61. qstr source_file;
  62. uint8_t is_repl;
  63. uint8_t pass; // holds enum type pass_kind_t
  64. uint8_t had_error; // try to keep compiler clean from nlr
  65. uint8_t func_arg_is_super; // used to compile special case of super() function call
  66. uint next_label;
  67. uint16_t break_label; // highest bit set indicates we are breaking out of a for loop
  68. uint16_t continue_label;
  69. int break_continue_except_level;
  70. uint16_t cur_except_level; // increased for SETUP_EXCEPT, SETUP_FINALLY; decreased for POP_BLOCK, POP_EXCEPT
  71. uint8_t have_star;
  72. uint16_t num_dict_params;
  73. uint16_t num_default_params;
  74. scope_t *scope_head;
  75. scope_t *scope_cur;
  76. emit_t *emit; // current emitter
  77. const emit_method_table_t *emit_method_table; // current emit method table
  78. emit_inline_asm_t *emit_inline_asm; // current emitter for inline asm
  79. const emit_inline_asm_method_table_t *emit_inline_asm_method_table; // current emit method table for inline asm
  80. } compiler_t;
  81. STATIC void compile_syntax_error(compiler_t *comp, mp_parse_node_t pn, const char *msg) {
  82. // TODO store the error message to a variable in compiler_t instead of printing it
  83. if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  84. printf(" File \"%s\", line " UINT_FMT "\n", qstr_str(comp->source_file), (machine_uint_t)((mp_parse_node_struct_t*)pn)->source_line);
  85. } else {
  86. printf(" File \"%s\"\n", qstr_str(comp->source_file));
  87. }
  88. printf("SyntaxError: %s\n", msg);
  89. comp->had_error = true;
  90. }
  91. STATIC const mp_map_elem_t mp_constants_table[] = {
  92. // Extra constants as defined by a port
  93. MICROPY_PORT_CONSTANTS
  94. };
  95. STATIC const mp_map_t mp_constants_map = {
  96. .all_keys_are_qstrs = 1,
  97. .table_is_fixed_array = 1,
  98. .used = ARRAY_SIZE(mp_constants_table),
  99. .alloc = ARRAY_SIZE(mp_constants_table),
  100. .table = (mp_map_elem_t*)mp_constants_table,
  101. };
  102. // this function is essentially a simple preprocessor
  103. STATIC mp_parse_node_t fold_constants(compiler_t *comp, mp_parse_node_t pn, mp_map_t *consts) {
  104. if (0) {
  105. // dummy
  106. #if MICROPY_COMP_CONST
  107. } else if (MP_PARSE_NODE_IS_ID(pn)) {
  108. // lookup identifier in table of dynamic constants
  109. qstr qst = MP_PARSE_NODE_LEAF_ARG(pn);
  110. mp_map_elem_t *elem = mp_map_lookup(consts, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
  111. if (elem != NULL) {
  112. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, MP_OBJ_SMALL_INT_VALUE(elem->value));
  113. }
  114. #endif
  115. } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  116. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  117. // fold some parse nodes before folding their arguments
  118. switch (MP_PARSE_NODE_STRUCT_KIND(pns)) {
  119. #if MICROPY_COMP_CONST
  120. case PN_expr_stmt:
  121. if (!MP_PARSE_NODE_IS_NULL(pns->nodes[1])) {
  122. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
  123. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_expr_stmt_assign) {
  124. if (MP_PARSE_NODE_IS_ID(pns->nodes[0])
  125. && MP_PARSE_NODE_IS_STRUCT_KIND(pns1->nodes[0], PN_power)
  126. && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t*)pns1->nodes[0])->nodes[0])
  127. && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t*)pns1->nodes[0])->nodes[0]) == MP_QSTR_const
  128. && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t*)pns1->nodes[0])->nodes[1], PN_trailer_paren)
  129. && MP_PARSE_NODE_IS_NULL(((mp_parse_node_struct_t*)pns1->nodes[0])->nodes[2])
  130. ) {
  131. // code to assign dynamic constants: id = const(value)
  132. // get the id
  133. qstr id_qstr = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  134. // get the value
  135. mp_parse_node_t pn_value = ((mp_parse_node_struct_t*)((mp_parse_node_struct_t*)pns1->nodes[0])->nodes[1])->nodes[0];
  136. pn_value = fold_constants(comp, pn_value, consts);
  137. if (!MP_PARSE_NODE_IS_SMALL_INT(pn_value)) {
  138. compile_syntax_error(comp, (mp_parse_node_t)pns, "constant must be an integer");
  139. break;
  140. }
  141. machine_int_t value = MP_PARSE_NODE_LEAF_SMALL_INT(pn_value);
  142. // store the value in the table of dynamic constants
  143. mp_map_elem_t *elem = mp_map_lookup(consts, MP_OBJ_NEW_QSTR(id_qstr), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
  144. if (elem->value != MP_OBJ_NULL) {
  145. compile_syntax_error(comp, (mp_parse_node_t)pns, "constant redefined");
  146. break;
  147. }
  148. elem->value = MP_OBJ_NEW_SMALL_INT(value);
  149. // replace const(value) with value
  150. pns1->nodes[0] = pn_value;
  151. // finished folding this assignment
  152. return pn;
  153. }
  154. }
  155. }
  156. break;
  157. #endif
  158. case PN_string:
  159. return pn;
  160. }
  161. // fold arguments
  162. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  163. for (int i = 0; i < n; i++) {
  164. pns->nodes[i] = fold_constants(comp, pns->nodes[i], consts);
  165. }
  166. // try to fold this parse node
  167. switch (MP_PARSE_NODE_STRUCT_KIND(pns)) {
  168. case PN_atom_paren:
  169. if (n == 1 && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0])) {
  170. // (int)
  171. pn = pns->nodes[0];
  172. }
  173. break;
  174. case PN_expr:
  175. if (n == 2 && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0]) && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[1])) {
  176. // int | int
  177. machine_int_t arg0 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
  178. machine_int_t arg1 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[1]);
  179. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0 | arg1);
  180. }
  181. break;
  182. case PN_and_expr:
  183. if (n == 2 && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0]) && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[1])) {
  184. // int & int
  185. machine_int_t arg0 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
  186. machine_int_t arg1 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[1]);
  187. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0 & arg1);
  188. }
  189. break;
  190. case PN_shift_expr:
  191. if (n == 3 && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0]) && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[2])) {
  192. machine_int_t arg0 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
  193. machine_int_t arg1 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[2]);
  194. if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_DBL_LESS)) {
  195. // int << int
  196. if (!(arg1 >= BITS_PER_WORD || arg0 > (MP_SMALL_INT_MAX >> arg1) || arg0 < (MP_SMALL_INT_MIN >> arg1))) {
  197. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0 << arg1);
  198. }
  199. } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_DBL_MORE)) {
  200. // int >> int
  201. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0 >> arg1);
  202. } else {
  203. // shouldn't happen
  204. assert(0);
  205. }
  206. }
  207. break;
  208. case PN_arith_expr:
  209. // overflow checking here relies on SMALL_INT being strictly smaller than machine_int_t
  210. if (n == 3 && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0]) && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[2])) {
  211. machine_int_t arg0 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
  212. machine_int_t arg1 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[2]);
  213. if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_PLUS)) {
  214. // int + int
  215. arg0 += arg1;
  216. } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_MINUS)) {
  217. // int - int
  218. arg0 -= arg1;
  219. } else {
  220. // shouldn't happen
  221. assert(0);
  222. }
  223. if (MP_SMALL_INT_FITS(arg0)) {
  224. //printf("%ld + %ld\n", arg0, arg1);
  225. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0);
  226. }
  227. }
  228. break;
  229. case PN_term:
  230. if (n == 3 && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0]) && MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[2])) {
  231. machine_int_t arg0 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
  232. machine_int_t arg1 = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[2]);
  233. if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_STAR)) {
  234. // int * int
  235. if (!mp_small_int_mul_overflow(arg0, arg1)) {
  236. arg0 *= arg1;
  237. if (MP_SMALL_INT_FITS(arg0)) {
  238. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0);
  239. }
  240. }
  241. } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_SLASH)) {
  242. // int / int
  243. // pass
  244. } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_PERCENT)) {
  245. // int%int
  246. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, mp_small_int_modulo(arg0, arg1));
  247. } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_DBL_SLASH)) {
  248. if (arg1 != 0) {
  249. // int // int
  250. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, mp_small_int_floor_divide(arg0, arg1));
  251. }
  252. } else {
  253. // shouldn't happen
  254. assert(0);
  255. }
  256. }
  257. break;
  258. case PN_factor_2:
  259. if (MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[1])) {
  260. machine_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[1]);
  261. if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[0], MP_TOKEN_OP_PLUS)) {
  262. // +int
  263. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg);
  264. } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[0], MP_TOKEN_OP_MINUS)) {
  265. // -int
  266. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, -arg);
  267. } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[0], MP_TOKEN_OP_TILDE)) {
  268. // ~int
  269. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, ~arg);
  270. } else {
  271. // shouldn't happen
  272. assert(0);
  273. }
  274. }
  275. break;
  276. case PN_power:
  277. if (0) {
  278. #if MICROPY_EMIT_CPYTHON
  279. } else if (MP_PARSE_NODE_IS_SMALL_INT(pns->nodes[0]) && MP_PARSE_NODE_IS_NULL(pns->nodes[1]) && !MP_PARSE_NODE_IS_NULL(pns->nodes[2])) {
  280. // int ** x
  281. // can overflow; enabled only to compare with CPython
  282. mp_parse_node_struct_t* pns2 = (mp_parse_node_struct_t*)pns->nodes[2];
  283. if (MP_PARSE_NODE_IS_SMALL_INT(pns2->nodes[0])) {
  284. int power = MP_PARSE_NODE_LEAF_SMALL_INT(pns2->nodes[0]);
  285. if (power >= 0) {
  286. int ans = 1;
  287. int base = MP_PARSE_NODE_LEAF_SMALL_INT(pns->nodes[0]);
  288. for (; power > 0; power--) {
  289. ans *= base;
  290. }
  291. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, ans);
  292. }
  293. }
  294. #endif
  295. } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0]) && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_trailer_period) && MP_PARSE_NODE_IS_NULL(pns->nodes[2])) {
  296. // id.id
  297. // look it up in constant table, see if it can be replaced with an integer
  298. mp_parse_node_struct_t* pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
  299. assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
  300. qstr q_base = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]);
  301. qstr q_attr = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]);
  302. mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP);
  303. if (elem != NULL) {
  304. mp_obj_t dest[2];
  305. mp_load_method_maybe(elem->value, q_attr, dest);
  306. if (MP_OBJ_IS_SMALL_INT(dest[0]) && dest[1] == NULL) {
  307. machine_int_t val = MP_OBJ_SMALL_INT_VALUE(dest[0]);
  308. if (MP_SMALL_INT_FITS(val)) {
  309. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, val);
  310. }
  311. }
  312. }
  313. }
  314. break;
  315. }
  316. }
  317. return pn;
  318. }
  319. STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_arglist, bool is_method_call, int n_positional_extra);
  320. void compile_comprehension(compiler_t *comp, mp_parse_node_struct_t *pns, scope_kind_t kind);
  321. STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn);
  322. STATIC uint comp_next_label(compiler_t *comp) {
  323. return comp->next_label++;
  324. }
  325. STATIC void compile_increase_except_level(compiler_t *comp) {
  326. comp->cur_except_level += 1;
  327. if (comp->cur_except_level > comp->scope_cur->exc_stack_size) {
  328. comp->scope_cur->exc_stack_size = comp->cur_except_level;
  329. }
  330. }
  331. STATIC void compile_decrease_except_level(compiler_t *comp) {
  332. assert(comp->cur_except_level > 0);
  333. comp->cur_except_level -= 1;
  334. }
  335. STATIC scope_t *scope_new_and_link(compiler_t *comp, scope_kind_t kind, mp_parse_node_t pn, uint emit_options) {
  336. scope_t *scope = scope_new(kind, pn, comp->source_file, emit_options);
  337. scope->parent = comp->scope_cur;
  338. scope->next = NULL;
  339. if (comp->scope_head == NULL) {
  340. comp->scope_head = scope;
  341. } else {
  342. scope_t *s = comp->scope_head;
  343. while (s->next != NULL) {
  344. s = s->next;
  345. }
  346. s->next = scope;
  347. }
  348. return scope;
  349. }
  350. STATIC void apply_to_single_or_list(compiler_t *comp, mp_parse_node_t pn, int pn_list_kind, void (*f)(compiler_t*, mp_parse_node_t)) {
  351. if (MP_PARSE_NODE_IS_STRUCT(pn) && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn) == pn_list_kind) {
  352. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  353. int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  354. for (int i = 0; i < num_nodes; i++) {
  355. f(comp, pns->nodes[i]);
  356. }
  357. } else if (!MP_PARSE_NODE_IS_NULL(pn)) {
  358. f(comp, pn);
  359. }
  360. }
  361. STATIC int list_get(mp_parse_node_t *pn, int pn_kind, mp_parse_node_t **nodes) {
  362. if (MP_PARSE_NODE_IS_NULL(*pn)) {
  363. *nodes = NULL;
  364. return 0;
  365. } else if (MP_PARSE_NODE_IS_LEAF(*pn)) {
  366. *nodes = pn;
  367. return 1;
  368. } else {
  369. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)(*pn);
  370. if (MP_PARSE_NODE_STRUCT_KIND(pns) != pn_kind) {
  371. *nodes = pn;
  372. return 1;
  373. } else {
  374. *nodes = pns->nodes;
  375. return MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  376. }
  377. }
  378. }
  379. void compile_do_nothing(compiler_t *comp, mp_parse_node_struct_t *pns) {
  380. }
  381. void compile_generic_all_nodes(compiler_t *comp, mp_parse_node_struct_t *pns) {
  382. int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  383. for (int i = 0; i < num_nodes; i++) {
  384. compile_node(comp, pns->nodes[i]);
  385. }
  386. }
  387. #if MICROPY_EMIT_CPYTHON
  388. STATIC bool cpython_c_tuple_is_const(mp_parse_node_t pn) {
  389. if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_string)) {
  390. return true;
  391. }
  392. if (!MP_PARSE_NODE_IS_LEAF(pn)) {
  393. return false;
  394. }
  395. if (MP_PARSE_NODE_IS_ID(pn)) {
  396. return false;
  397. }
  398. return true;
  399. }
  400. STATIC void cpython_c_print_quoted_str(vstr_t *vstr, const char *str, uint len, bool bytes) {
  401. bool has_single_quote = false;
  402. bool has_double_quote = false;
  403. for (int i = 0; i < len; i++) {
  404. if (str[i] == '\'') {
  405. has_single_quote = true;
  406. } else if (str[i] == '"') {
  407. has_double_quote = true;
  408. }
  409. }
  410. if (bytes) {
  411. vstr_printf(vstr, "b");
  412. }
  413. bool quote_single = false;
  414. if (has_single_quote && !has_double_quote) {
  415. vstr_printf(vstr, "\"");
  416. } else {
  417. quote_single = true;
  418. vstr_printf(vstr, "'");
  419. }
  420. for (int i = 0; i < len; i++) {
  421. if (str[i] == '\n') {
  422. vstr_printf(vstr, "\\n");
  423. } else if (str[i] == '\\') {
  424. vstr_printf(vstr, "\\\\");
  425. } else if (str[i] == '\'' && quote_single) {
  426. vstr_printf(vstr, "\\'");
  427. } else {
  428. vstr_printf(vstr, "%c", str[i]);
  429. }
  430. }
  431. if (has_single_quote && !has_double_quote) {
  432. vstr_printf(vstr, "\"");
  433. } else {
  434. vstr_printf(vstr, "'");
  435. }
  436. }
  437. STATIC void cpython_c_tuple_emit_const(compiler_t *comp, mp_parse_node_t pn, vstr_t *vstr) {
  438. if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_string)) {
  439. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  440. cpython_c_print_quoted_str(vstr, (const char*)pns->nodes[0], (machine_uint_t)pns->nodes[1], false);
  441. return;
  442. }
  443. assert(MP_PARSE_NODE_IS_LEAF(pn));
  444. if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  445. vstr_printf(vstr, INT_FMT, MP_PARSE_NODE_LEAF_SMALL_INT(pn));
  446. return;
  447. }
  448. int arg = MP_PARSE_NODE_LEAF_ARG(pn);
  449. switch (MP_PARSE_NODE_LEAF_KIND(pn)) {
  450. case MP_PARSE_NODE_ID: assert(0);
  451. case MP_PARSE_NODE_INTEGER: vstr_printf(vstr, "%s", qstr_str(arg)); break;
  452. case MP_PARSE_NODE_DECIMAL: vstr_printf(vstr, "%s", qstr_str(arg)); break;
  453. case MP_PARSE_NODE_STRING:
  454. case MP_PARSE_NODE_BYTES: {
  455. uint len;
  456. const byte *str = qstr_data(arg, &len);
  457. cpython_c_print_quoted_str(vstr, (const char*)str, len, MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_BYTES);
  458. break;
  459. }
  460. case MP_PARSE_NODE_TOKEN:
  461. switch (arg) {
  462. case MP_TOKEN_KW_FALSE: vstr_printf(vstr, "False"); break;
  463. case MP_TOKEN_KW_NONE: vstr_printf(vstr, "None"); break;
  464. case MP_TOKEN_KW_TRUE: vstr_printf(vstr, "True"); break;
  465. default: assert(0); // shouldn't happen
  466. }
  467. break;
  468. default: assert(0);
  469. }
  470. }
  471. STATIC void cpython_c_tuple(compiler_t *comp, mp_parse_node_t pn, mp_parse_node_struct_t *pns_list) {
  472. int n = 0;
  473. if (pns_list != NULL) {
  474. n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns_list);
  475. }
  476. int total = n;
  477. bool is_const = true;
  478. if (!MP_PARSE_NODE_IS_NULL(pn)) {
  479. total += 1;
  480. if (!cpython_c_tuple_is_const(pn)) {
  481. is_const = false;
  482. }
  483. }
  484. for (int i = 0; i < n; i++) {
  485. if (!cpython_c_tuple_is_const(pns_list->nodes[i])) {
  486. is_const = false;
  487. break;
  488. }
  489. }
  490. if (total > 0 && is_const) {
  491. bool need_comma = false;
  492. vstr_t *vstr = vstr_new();
  493. vstr_printf(vstr, "(");
  494. if (!MP_PARSE_NODE_IS_NULL(pn)) {
  495. cpython_c_tuple_emit_const(comp, pn, vstr);
  496. need_comma = true;
  497. }
  498. for (int i = 0; i < n; i++) {
  499. if (need_comma) {
  500. vstr_printf(vstr, ", ");
  501. }
  502. cpython_c_tuple_emit_const(comp, pns_list->nodes[i], vstr);
  503. need_comma = true;
  504. }
  505. if (total == 1) {
  506. vstr_printf(vstr, ",)");
  507. } else {
  508. vstr_printf(vstr, ")");
  509. }
  510. EMIT_ARG(load_const_verbatim_str, vstr_str(vstr));
  511. vstr_free(vstr);
  512. } else {
  513. if (!MP_PARSE_NODE_IS_NULL(pn)) {
  514. compile_node(comp, pn);
  515. }
  516. for (int i = 0; i < n; i++) {
  517. compile_node(comp, pns_list->nodes[i]);
  518. }
  519. EMIT_ARG(build_tuple, total);
  520. }
  521. }
  522. #endif
  523. // funnelling all tuple creations through this function is purely so we can optionally agree with CPython
  524. STATIC void c_tuple(compiler_t *comp, mp_parse_node_t pn, mp_parse_node_struct_t *pns_list) {
  525. #if MICROPY_EMIT_CPYTHON
  526. cpython_c_tuple(comp, pn, pns_list);
  527. #else
  528. int total = 0;
  529. if (!MP_PARSE_NODE_IS_NULL(pn)) {
  530. compile_node(comp, pn);
  531. total += 1;
  532. }
  533. if (pns_list != NULL) {
  534. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns_list);
  535. for (int i = 0; i < n; i++) {
  536. compile_node(comp, pns_list->nodes[i]);
  537. }
  538. total += n;
  539. }
  540. EMIT_ARG(build_tuple, total);
  541. #endif
  542. }
  543. void compile_generic_tuple(compiler_t *comp, mp_parse_node_struct_t *pns) {
  544. // a simple tuple expression
  545. c_tuple(comp, MP_PARSE_NODE_NULL, pns);
  546. }
  547. STATIC bool node_is_const_false(mp_parse_node_t pn) {
  548. return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_FALSE);
  549. // untested: || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0);
  550. }
  551. STATIC bool node_is_const_true(mp_parse_node_t pn) {
  552. return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_TRUE) || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 1);
  553. }
  554. #if MICROPY_EMIT_CPYTHON
  555. // the is_nested variable is purely to match with CPython, which doesn't fully optimise not's
  556. STATIC void cpython_c_if_cond(compiler_t *comp, mp_parse_node_t pn, bool jump_if, int label, bool is_nested) {
  557. if (node_is_const_false(pn)) {
  558. if (jump_if == false) {
  559. EMIT_ARG(jump, label);
  560. }
  561. return;
  562. } else if (node_is_const_true(pn)) {
  563. if (jump_if == true) {
  564. EMIT_ARG(jump, label);
  565. }
  566. return;
  567. } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  568. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  569. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  570. if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_or_test) {
  571. if (jump_if == false) {
  572. uint label2 = comp_next_label(comp);
  573. for (int i = 0; i < n - 1; i++) {
  574. cpython_c_if_cond(comp, pns->nodes[i], true, label2, true);
  575. }
  576. cpython_c_if_cond(comp, pns->nodes[n - 1], false, label, true);
  577. EMIT_ARG(label_assign, label2);
  578. } else {
  579. for (int i = 0; i < n; i++) {
  580. cpython_c_if_cond(comp, pns->nodes[i], true, label, true);
  581. }
  582. }
  583. return;
  584. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_and_test) {
  585. if (jump_if == false) {
  586. for (int i = 0; i < n; i++) {
  587. cpython_c_if_cond(comp, pns->nodes[i], false, label, true);
  588. }
  589. } else {
  590. uint label2 = comp_next_label(comp);
  591. for (int i = 0; i < n - 1; i++) {
  592. cpython_c_if_cond(comp, pns->nodes[i], false, label2, true);
  593. }
  594. cpython_c_if_cond(comp, pns->nodes[n - 1], true, label, true);
  595. EMIT_ARG(label_assign, label2);
  596. }
  597. return;
  598. } else if (!is_nested && MP_PARSE_NODE_STRUCT_KIND(pns) == PN_not_test_2) {
  599. cpython_c_if_cond(comp, pns->nodes[0], !jump_if, label, true);
  600. return;
  601. }
  602. }
  603. // nothing special, fall back to default compiling for node and jump
  604. compile_node(comp, pn);
  605. if (jump_if == false) {
  606. EMIT_ARG(pop_jump_if_false, label);
  607. } else {
  608. EMIT_ARG(pop_jump_if_true, label);
  609. }
  610. }
  611. #endif
  612. STATIC void c_if_cond(compiler_t *comp, mp_parse_node_t pn, bool jump_if, int label) {
  613. #if MICROPY_EMIT_CPYTHON
  614. cpython_c_if_cond(comp, pn, jump_if, label, false);
  615. #else
  616. if (node_is_const_false(pn)) {
  617. if (jump_if == false) {
  618. EMIT_ARG(jump, label);
  619. }
  620. return;
  621. } else if (node_is_const_true(pn)) {
  622. if (jump_if == true) {
  623. EMIT_ARG(jump, label);
  624. }
  625. return;
  626. } else if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  627. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  628. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  629. if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_or_test) {
  630. if (jump_if == false) {
  631. uint label2 = comp_next_label(comp);
  632. for (int i = 0; i < n - 1; i++) {
  633. c_if_cond(comp, pns->nodes[i], true, label2);
  634. }
  635. c_if_cond(comp, pns->nodes[n - 1], false, label);
  636. EMIT_ARG(label_assign, label2);
  637. } else {
  638. for (int i = 0; i < n; i++) {
  639. c_if_cond(comp, pns->nodes[i], true, label);
  640. }
  641. }
  642. return;
  643. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_and_test) {
  644. if (jump_if == false) {
  645. for (int i = 0; i < n; i++) {
  646. c_if_cond(comp, pns->nodes[i], false, label);
  647. }
  648. } else {
  649. uint label2 = comp_next_label(comp);
  650. for (int i = 0; i < n - 1; i++) {
  651. c_if_cond(comp, pns->nodes[i], false, label2);
  652. }
  653. c_if_cond(comp, pns->nodes[n - 1], true, label);
  654. EMIT_ARG(label_assign, label2);
  655. }
  656. return;
  657. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_not_test_2) {
  658. c_if_cond(comp, pns->nodes[0], !jump_if, label);
  659. return;
  660. }
  661. }
  662. // nothing special, fall back to default compiling for node and jump
  663. compile_node(comp, pn);
  664. if (jump_if == false) {
  665. EMIT_ARG(pop_jump_if_false, label);
  666. } else {
  667. EMIT_ARG(pop_jump_if_true, label);
  668. }
  669. #endif
  670. }
  671. typedef enum { ASSIGN_STORE, ASSIGN_AUG_LOAD, ASSIGN_AUG_STORE } assign_kind_t;
  672. void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t kind);
  673. void c_assign_power(compiler_t *comp, mp_parse_node_struct_t *pns, assign_kind_t assign_kind) {
  674. if (assign_kind != ASSIGN_AUG_STORE) {
  675. compile_node(comp, pns->nodes[0]);
  676. }
  677. if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
  678. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1];
  679. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_power_trailers) {
  680. int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1);
  681. if (assign_kind != ASSIGN_AUG_STORE) {
  682. for (int i = 0; i < n - 1; i++) {
  683. compile_node(comp, pns1->nodes[i]);
  684. }
  685. }
  686. assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1]));
  687. pns1 = (mp_parse_node_struct_t*)pns1->nodes[n - 1];
  688. }
  689. if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_paren) {
  690. goto cannot_assign;
  691. } else if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) {
  692. if (assign_kind == ASSIGN_AUG_STORE) {
  693. EMIT(rot_three);
  694. EMIT(store_subscr);
  695. } else {
  696. compile_node(comp, pns1->nodes[0]);
  697. if (assign_kind == ASSIGN_AUG_LOAD) {
  698. EMIT(dup_top_two);
  699. EMIT(load_subscr);
  700. } else {
  701. EMIT(store_subscr);
  702. }
  703. }
  704. } else if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_period) {
  705. assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
  706. if (assign_kind == ASSIGN_AUG_LOAD) {
  707. EMIT(dup_top);
  708. EMIT_ARG(load_attr, MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]));
  709. } else {
  710. if (assign_kind == ASSIGN_AUG_STORE) {
  711. EMIT(rot_two);
  712. }
  713. EMIT_ARG(store_attr, MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]));
  714. }
  715. } else {
  716. goto cannot_assign;
  717. }
  718. } else {
  719. goto cannot_assign;
  720. }
  721. if (!MP_PARSE_NODE_IS_NULL(pns->nodes[2])) {
  722. goto cannot_assign;
  723. }
  724. return;
  725. cannot_assign:
  726. compile_syntax_error(comp, (mp_parse_node_t)pns, "can't assign to expression");
  727. }
  728. // we need to allow for a caller passing in 1 initial node (node_head) followed by an array of nodes (nodes_tail)
  729. void c_assign_tuple(compiler_t *comp, mp_parse_node_t node_head, uint num_tail, mp_parse_node_t *nodes_tail) {
  730. uint num_head = (node_head == MP_PARSE_NODE_NULL) ? 0 : 1;
  731. // look for star expression
  732. int have_star_index = -1;
  733. if (num_head != 0 && MP_PARSE_NODE_IS_STRUCT_KIND(node_head, PN_star_expr)) {
  734. EMIT_ARG(unpack_ex, 0, num_tail);
  735. have_star_index = 0;
  736. }
  737. for (int i = 0; i < num_tail; i++) {
  738. if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes_tail[i], PN_star_expr)) {
  739. if (have_star_index < 0) {
  740. EMIT_ARG(unpack_ex, num_head + i, num_tail - i - 1);
  741. have_star_index = num_head + i;
  742. } else {
  743. compile_syntax_error(comp, nodes_tail[i], "multiple *x in assignment");
  744. return;
  745. }
  746. }
  747. }
  748. if (have_star_index < 0) {
  749. EMIT_ARG(unpack_sequence, num_head + num_tail);
  750. }
  751. if (num_head != 0) {
  752. if (0 == have_star_index) {
  753. c_assign(comp, ((mp_parse_node_struct_t*)node_head)->nodes[0], ASSIGN_STORE);
  754. } else {
  755. c_assign(comp, node_head, ASSIGN_STORE);
  756. }
  757. }
  758. for (int i = 0; i < num_tail; i++) {
  759. if (num_head + i == have_star_index) {
  760. c_assign(comp, ((mp_parse_node_struct_t*)nodes_tail[i])->nodes[0], ASSIGN_STORE);
  761. } else {
  762. c_assign(comp, nodes_tail[i], ASSIGN_STORE);
  763. }
  764. }
  765. }
  766. // assigns top of stack to pn
  767. void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_kind) {
  768. tail_recursion:
  769. if (MP_PARSE_NODE_IS_NULL(pn)) {
  770. assert(0);
  771. } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
  772. if (MP_PARSE_NODE_IS_ID(pn)) {
  773. int arg = MP_PARSE_NODE_LEAF_ARG(pn);
  774. switch (assign_kind) {
  775. case ASSIGN_STORE:
  776. case ASSIGN_AUG_STORE:
  777. EMIT_ARG(store_id, arg);
  778. break;
  779. case ASSIGN_AUG_LOAD:
  780. EMIT_ARG(load_id, arg);
  781. break;
  782. }
  783. } else {
  784. compile_syntax_error(comp, pn, "can't assign to literal");
  785. return;
  786. }
  787. } else {
  788. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  789. switch (MP_PARSE_NODE_STRUCT_KIND(pns)) {
  790. case PN_power:
  791. // lhs is an index or attribute
  792. c_assign_power(comp, pns, assign_kind);
  793. break;
  794. case PN_testlist_star_expr:
  795. case PN_exprlist:
  796. // lhs is a tuple
  797. if (assign_kind != ASSIGN_STORE) {
  798. goto bad_aug;
  799. }
  800. c_assign_tuple(comp, MP_PARSE_NODE_NULL, MP_PARSE_NODE_STRUCT_NUM_NODES(pns), pns->nodes);
  801. break;
  802. case PN_atom_paren:
  803. // lhs is something in parenthesis
  804. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  805. // empty tuple
  806. goto cannot_assign;
  807. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) {
  808. pns = (mp_parse_node_struct_t*)pns->nodes[0];
  809. goto testlist_comp;
  810. } else {
  811. // parenthesis around 1 item, is just that item
  812. pn = pns->nodes[0];
  813. goto tail_recursion;
  814. }
  815. break;
  816. case PN_atom_bracket:
  817. // lhs is something in brackets
  818. if (assign_kind != ASSIGN_STORE) {
  819. goto bad_aug;
  820. }
  821. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  822. // empty list, assignment allowed
  823. c_assign_tuple(comp, MP_PARSE_NODE_NULL, 0, NULL);
  824. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) {
  825. pns = (mp_parse_node_struct_t*)pns->nodes[0];
  826. goto testlist_comp;
  827. } else {
  828. // brackets around 1 item
  829. c_assign_tuple(comp, pns->nodes[0], 0, NULL);
  830. }
  831. break;
  832. default:
  833. goto cannot_assign;
  834. }
  835. return;
  836. testlist_comp:
  837. // lhs is a sequence
  838. if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
  839. mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1];
  840. if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) {
  841. // sequence of one item, with trailing comma
  842. assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0]));
  843. c_assign_tuple(comp, pns->nodes[0], 0, NULL);
  844. } else if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3c) {
  845. // sequence of many items
  846. uint n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns2);
  847. c_assign_tuple(comp, pns->nodes[0], n, pns2->nodes);
  848. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_comp_for) {
  849. // TODO can we ever get here? can it be compiled?
  850. goto cannot_assign;
  851. } else {
  852. // sequence with 2 items
  853. goto sequence_with_2_items;
  854. }
  855. } else {
  856. // sequence with 2 items
  857. sequence_with_2_items:
  858. c_assign_tuple(comp, MP_PARSE_NODE_NULL, 2, pns->nodes);
  859. }
  860. return;
  861. }
  862. return;
  863. cannot_assign:
  864. compile_syntax_error(comp, pn, "can't assign to expression");
  865. return;
  866. bad_aug:
  867. compile_syntax_error(comp, pn, "illegal expression for augmented assignment");
  868. }
  869. // stuff for lambda and comprehensions and generators
  870. // if we are not in CPython compatibility mode then:
  871. // if n_pos_defaults > 0 then there is a tuple on the stack with the positional defaults
  872. // if n_kw_defaults > 0 then there is a dictionary on the stack with the keyword defaults
  873. // if both exist, the tuple is above the dictionary (ie the first pop gets the tuple)
  874. void close_over_variables_etc(compiler_t *comp, scope_t *this_scope, int n_pos_defaults, int n_kw_defaults) {
  875. assert(n_pos_defaults >= 0);
  876. assert(n_kw_defaults >= 0);
  877. // make closed over variables, if any
  878. // ensure they are closed over in the order defined in the outer scope (mainly to agree with CPython)
  879. int nfree = 0;
  880. if (comp->scope_cur->kind != SCOPE_MODULE) {
  881. for (int i = 0; i < comp->scope_cur->id_info_len; i++) {
  882. id_info_t *id = &comp->scope_cur->id_info[i];
  883. if (id->kind == ID_INFO_KIND_CELL || id->kind == ID_INFO_KIND_FREE) {
  884. for (int j = 0; j < this_scope->id_info_len; j++) {
  885. id_info_t *id2 = &this_scope->id_info[j];
  886. if (id2->kind == ID_INFO_KIND_FREE && id->qstr == id2->qstr) {
  887. #if MICROPY_EMIT_CPYTHON
  888. EMIT_ARG(load_closure, id->qstr, id->local_num);
  889. #else
  890. // in Micro Python we load closures using LOAD_FAST
  891. EMIT_ARG(load_fast, id->qstr, id->flags, id->local_num);
  892. #endif
  893. nfree += 1;
  894. }
  895. }
  896. }
  897. }
  898. }
  899. // make the function/closure
  900. if (nfree == 0) {
  901. EMIT_ARG(make_function, this_scope, n_pos_defaults, n_kw_defaults);
  902. } else {
  903. EMIT_ARG(make_closure, this_scope, nfree, n_pos_defaults, n_kw_defaults);
  904. }
  905. }
  906. void compile_funcdef_param(compiler_t *comp, mp_parse_node_t pn) {
  907. if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_typedargslist_star)) {
  908. comp->have_star = true;
  909. /* don't need to distinguish bare from named star
  910. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  911. if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) {
  912. // bare star
  913. } else {
  914. // named star
  915. }
  916. */
  917. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_typedargslist_dbl_star)) {
  918. // named double star
  919. // TODO do we need to do anything with this?
  920. } else {
  921. mp_parse_node_t pn_id;
  922. mp_parse_node_t pn_colon;
  923. mp_parse_node_t pn_equal;
  924. if (MP_PARSE_NODE_IS_ID(pn)) {
  925. // this parameter is just an id
  926. pn_id = pn;
  927. pn_colon = MP_PARSE_NODE_NULL;
  928. pn_equal = MP_PARSE_NODE_NULL;
  929. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_typedargslist_name)) {
  930. // this parameter has a colon and/or equal specifier
  931. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  932. pn_id = pns->nodes[0];
  933. pn_colon = pns->nodes[1];
  934. pn_equal = pns->nodes[2];
  935. } else {
  936. // XXX what to do here?
  937. assert(0);
  938. return;
  939. }
  940. if (MP_PARSE_NODE_IS_NULL(pn_equal)) {
  941. // this parameter does not have a default value
  942. // check for non-default parameters given after default parameters (allowed by parser, but not syntactically valid)
  943. if (!comp->have_star && comp->num_default_params != 0) {
  944. compile_syntax_error(comp, pn, "non-default argument follows default argument");
  945. return;
  946. }
  947. } else {
  948. // this parameter has a default value
  949. // in CPython, None (and True, False?) as default parameters are loaded with LOAD_NAME; don't understandy why
  950. if (comp->have_star) {
  951. comp->num_dict_params += 1;
  952. #if MICROPY_EMIT_CPYTHON
  953. EMIT_ARG(load_const_str, MP_PARSE_NODE_LEAF_ARG(pn_id), false);
  954. compile_node(comp, pn_equal);
  955. #else
  956. // in Micro Python we put the default dict parameters into a dictionary using the bytecode
  957. if (comp->num_dict_params == 1) {
  958. // in Micro Python we put the default positional parameters into a tuple using the bytecode
  959. // we need to do this here before we start building the map for the default keywords
  960. if (comp->num_default_params > 0) {
  961. EMIT_ARG(build_tuple, comp->num_default_params);
  962. } else {
  963. EMIT(load_null); // sentinel indicating empty default positional args
  964. }
  965. // first default dict param, so make the map
  966. EMIT_ARG(build_map, 0);
  967. }
  968. // compile value then key, then store it to the dict
  969. compile_node(comp, pn_equal);
  970. EMIT_ARG(load_const_str, MP_PARSE_NODE_LEAF_ARG(pn_id), false);
  971. EMIT(store_map);
  972. #endif
  973. } else {
  974. comp->num_default_params += 1;
  975. compile_node(comp, pn_equal);
  976. }
  977. }
  978. // TODO pn_colon not implemented
  979. (void)pn_colon;
  980. }
  981. }
  982. // leaves function object on stack
  983. // returns function name
  984. qstr compile_funcdef_helper(compiler_t *comp, mp_parse_node_struct_t *pns, uint emit_options) {
  985. if (comp->pass == MP_PASS_SCOPE) {
  986. // create a new scope for this function
  987. scope_t *s = scope_new_and_link(comp, SCOPE_FUNCTION, (mp_parse_node_t)pns, emit_options);
  988. // store the function scope so the compiling function can use it at each pass
  989. pns->nodes[4] = (mp_parse_node_t)s;
  990. }
  991. // save variables (probably don't need to do this, since we can't have nested definitions..?)
  992. uint old_have_star = comp->have_star;
  993. uint old_num_dict_params = comp->num_dict_params;
  994. uint old_num_default_params = comp->num_default_params;
  995. // compile default parameters
  996. comp->have_star = false;
  997. comp->num_dict_params = 0;
  998. comp->num_default_params = 0;
  999. apply_to_single_or_list(comp, pns->nodes[1], PN_typedargslist, compile_funcdef_param);
  1000. if (comp->had_error) {
  1001. return MP_QSTR_NULL;
  1002. }
  1003. #if !MICROPY_EMIT_CPYTHON
  1004. // in Micro Python we put the default positional parameters into a tuple using the bytecode
  1005. // the default keywords args may have already made the tuple; if not, do it now
  1006. if (comp->num_default_params > 0 && comp->num_dict_params == 0) {
  1007. EMIT_ARG(build_tuple, comp->num_default_params);
  1008. EMIT(load_null); // sentinel indicating empty default keyword args
  1009. }
  1010. #endif
  1011. // get the scope for this function
  1012. scope_t *fscope = (scope_t*)pns->nodes[4];
  1013. // make the function
  1014. close_over_variables_etc(comp, fscope, comp->num_default_params, comp->num_dict_params);
  1015. // restore variables
  1016. comp->have_star = old_have_star;
  1017. comp->num_dict_params = old_num_dict_params;
  1018. comp->num_default_params = old_num_default_params;
  1019. // return its name (the 'f' in "def f(...):")
  1020. return fscope->simple_name;
  1021. }
  1022. // leaves class object on stack
  1023. // returns class name
  1024. qstr compile_classdef_helper(compiler_t *comp, mp_parse_node_struct_t *pns, uint emit_options) {
  1025. if (comp->pass == MP_PASS_SCOPE) {
  1026. // create a new scope for this class
  1027. scope_t *s = scope_new_and_link(comp, SCOPE_CLASS, (mp_parse_node_t)pns, emit_options);
  1028. // store the class scope so the compiling function can use it at each pass
  1029. pns->nodes[3] = (mp_parse_node_t)s;
  1030. }
  1031. EMIT(load_build_class);
  1032. // scope for this class
  1033. scope_t *cscope = (scope_t*)pns->nodes[3];
  1034. // compile the class
  1035. close_over_variables_etc(comp, cscope, 0, 0);
  1036. // get its name
  1037. EMIT_ARG(load_const_str, cscope->simple_name, false);
  1038. // nodes[1] has parent classes, if any
  1039. // empty parenthesis (eg class C():) gets here as an empty PN_classdef_2 and needs special handling
  1040. mp_parse_node_t parents = pns->nodes[1];
  1041. if (MP_PARSE_NODE_IS_STRUCT_KIND(parents, PN_classdef_2)) {
  1042. parents = MP_PARSE_NODE_NULL;
  1043. }
  1044. comp->func_arg_is_super = false;
  1045. compile_trailer_paren_helper(comp, parents, false, 2);
  1046. // return its name (the 'C' in class C(...):")
  1047. return cscope->simple_name;
  1048. }
  1049. // returns true if it was a built-in decorator (even if the built-in had an error)
  1050. STATIC bool compile_built_in_decorator(compiler_t *comp, int name_len, mp_parse_node_t *name_nodes, uint *emit_options) {
  1051. if (MP_PARSE_NODE_LEAF_ARG(name_nodes[0]) != MP_QSTR_micropython) {
  1052. return false;
  1053. }
  1054. if (name_len != 2) {
  1055. compile_syntax_error(comp, name_nodes[0], "invalid micropython decorator");
  1056. return true;
  1057. }
  1058. qstr attr = MP_PARSE_NODE_LEAF_ARG(name_nodes[1]);
  1059. if (attr == MP_QSTR_bytecode) {
  1060. *emit_options = MP_EMIT_OPT_BYTECODE;
  1061. #if MICROPY_EMIT_NATIVE
  1062. } else if (attr == MP_QSTR_native) {
  1063. *emit_options = MP_EMIT_OPT_NATIVE_PYTHON;
  1064. } else if (attr == MP_QSTR_viper) {
  1065. *emit_options = MP_EMIT_OPT_VIPER;
  1066. #endif
  1067. #if MICROPY_EMIT_INLINE_THUMB
  1068. } else if (attr == MP_QSTR_asm_thumb) {
  1069. *emit_options = MP_EMIT_OPT_ASM_THUMB;
  1070. #endif
  1071. } else {
  1072. compile_syntax_error(comp, name_nodes[1], "invalid micropython decorator");
  1073. }
  1074. return true;
  1075. }
  1076. void compile_decorated(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1077. // get the list of decorators
  1078. mp_parse_node_t *nodes;
  1079. int n = list_get(&pns->nodes[0], PN_decorators, &nodes);
  1080. // inherit emit options for this function/class definition
  1081. uint emit_options = comp->scope_cur->emit_options;
  1082. // compile each decorator
  1083. int num_built_in_decorators = 0;
  1084. for (int i = 0; i < n; i++) {
  1085. assert(MP_PARSE_NODE_IS_STRUCT_KIND(nodes[i], PN_decorator)); // should be
  1086. mp_parse_node_struct_t *pns_decorator = (mp_parse_node_struct_t*)nodes[i];
  1087. // nodes[0] contains the decorator function, which is a dotted name
  1088. mp_parse_node_t *name_nodes;
  1089. int name_len = list_get(&pns_decorator->nodes[0], PN_dotted_name, &name_nodes);
  1090. // check for built-in decorators
  1091. if (compile_built_in_decorator(comp, name_len, name_nodes, &emit_options)) {
  1092. // this was a built-in
  1093. num_built_in_decorators += 1;
  1094. } else {
  1095. // not a built-in, compile normally
  1096. // compile the decorator function
  1097. compile_node(comp, name_nodes[0]);
  1098. for (int i = 1; i < name_len; i++) {
  1099. assert(MP_PARSE_NODE_IS_ID(name_nodes[i])); // should be
  1100. EMIT_ARG(load_attr, MP_PARSE_NODE_LEAF_ARG(name_nodes[i]));
  1101. }
  1102. // nodes[1] contains arguments to the decorator function, if any
  1103. if (!MP_PARSE_NODE_IS_NULL(pns_decorator->nodes[1])) {
  1104. // call the decorator function with the arguments in nodes[1]
  1105. comp->func_arg_is_super = false;
  1106. compile_node(comp, pns_decorator->nodes[1]);
  1107. }
  1108. }
  1109. }
  1110. // compile the body (funcdef or classdef) and get its name
  1111. mp_parse_node_struct_t *pns_body = (mp_parse_node_struct_t*)pns->nodes[1];
  1112. qstr body_name = 0;
  1113. if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_funcdef) {
  1114. body_name = compile_funcdef_helper(comp, pns_body, emit_options);
  1115. } else if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_classdef) {
  1116. body_name = compile_classdef_helper(comp, pns_body, emit_options);
  1117. } else {
  1118. // shouldn't happen
  1119. assert(0);
  1120. }
  1121. // call each decorator
  1122. for (int i = 0; i < n - num_built_in_decorators; i++) {
  1123. EMIT_ARG(call_function, 1, 0, 0);
  1124. }
  1125. // store func/class object into name
  1126. EMIT_ARG(store_id, body_name);
  1127. }
  1128. void compile_funcdef(compiler_t *comp, mp_parse_node_struct_t *pns) {
  1129. qstr fname = compile_funcdef_helper(comp, pns, comp->scope_cur->emit_options);
  1130. // store function object into function name
  1131. EMIT_ARG(store_id, fname);
  1132. }
  1133. void c_del_stmt(compiler_t *comp, mp_parse_node_t pn) {
  1134. if (MP_PARSE_NODE_IS_ID(pn)) {
  1135. EMIT_ARG(delete_id, MP_PARSE_NODE_LEAF_ARG(pn));
  1136. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_power)) {
  1137. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  1138. compile_node(comp, pns->nodes[0]); // base of the power node
  1139. if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) {
  1140. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes

Large files files are truncated, but you can click here to view the full file