parse.c 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013-2017 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 <unistd.h> // for ssize_t
  30. #include <assert.h>
  31. #include <string.h>
  32. #include "py/lexer.h"
  33. #include "py/parse.h"
  34. #include "py/parsenum.h"
  35. #include "py/runtime.h"
  36. #include "py/objint.h"
  37. #include "py/objstr.h"
  38. #include "py/builtin.h"
  39. #if MICROPY_ENABLE_COMPILER
  40. #define RULE_ACT_ARG_MASK (0x0f)
  41. #define RULE_ACT_KIND_MASK (0x30)
  42. #define RULE_ACT_ALLOW_IDENT (0x40)
  43. #define RULE_ACT_ADD_BLANK (0x80)
  44. #define RULE_ACT_OR (0x10)
  45. #define RULE_ACT_AND (0x20)
  46. #define RULE_ACT_LIST (0x30)
  47. #define RULE_ARG_KIND_MASK (0xf000)
  48. #define RULE_ARG_ARG_MASK (0x0fff)
  49. #define RULE_ARG_TOK (0x1000)
  50. #define RULE_ARG_RULE (0x2000)
  51. #define RULE_ARG_OPT_RULE (0x3000)
  52. // *FORMAT-OFF*
  53. enum {
  54. // define rules with a compile function
  55. #define DEF_RULE(rule, comp, kind, ...) RULE_##rule,
  56. #define DEF_RULE_NC(rule, kind, ...)
  57. #include "py/grammar.h"
  58. #undef DEF_RULE
  59. #undef DEF_RULE_NC
  60. RULE_const_object, // special node for a constant, generic Python object
  61. // define rules without a compile function
  62. #define DEF_RULE(rule, comp, kind, ...)
  63. #define DEF_RULE_NC(rule, kind, ...) RULE_##rule,
  64. #include "py/grammar.h"
  65. #undef DEF_RULE
  66. #undef DEF_RULE_NC
  67. };
  68. // Define an array of actions corresponding to each rule
  69. static const uint8_t rule_act_table[] = {
  70. #define or(n) (RULE_ACT_OR | n)
  71. #define and(n) (RULE_ACT_AND | n)
  72. #define and_ident(n) (RULE_ACT_AND | n | RULE_ACT_ALLOW_IDENT)
  73. #define and_blank(n) (RULE_ACT_AND | n | RULE_ACT_ADD_BLANK)
  74. #define one_or_more (RULE_ACT_LIST | 2)
  75. #define list (RULE_ACT_LIST | 1)
  76. #define list_with_end (RULE_ACT_LIST | 3)
  77. #define DEF_RULE(rule, comp, kind, ...) kind,
  78. #define DEF_RULE_NC(rule, kind, ...)
  79. #include "py/grammar.h"
  80. #undef DEF_RULE
  81. #undef DEF_RULE_NC
  82. 0, // RULE_const_object
  83. #define DEF_RULE(rule, comp, kind, ...)
  84. #define DEF_RULE_NC(rule, kind, ...) kind,
  85. #include "py/grammar.h"
  86. #undef DEF_RULE
  87. #undef DEF_RULE_NC
  88. #undef or
  89. #undef and
  90. #undef and_ident
  91. #undef and_blank
  92. #undef one_or_more
  93. #undef list
  94. #undef list_with_end
  95. };
  96. // Define the argument data for each rule, as a combined array
  97. static const uint16_t rule_arg_combined_table[] = {
  98. #define tok(t) (RULE_ARG_TOK | MP_TOKEN_##t)
  99. #define rule(r) (RULE_ARG_RULE | RULE_##r)
  100. #define opt_rule(r) (RULE_ARG_OPT_RULE | RULE_##r)
  101. #define DEF_RULE(rule, comp, kind, ...) __VA_ARGS__,
  102. #define DEF_RULE_NC(rule, kind, ...)
  103. #include "py/grammar.h"
  104. #undef DEF_RULE
  105. #undef DEF_RULE_NC
  106. #define DEF_RULE(rule, comp, kind, ...)
  107. #define DEF_RULE_NC(rule, kind, ...) __VA_ARGS__,
  108. #include "py/grammar.h"
  109. #undef DEF_RULE
  110. #undef DEF_RULE_NC
  111. #undef tok
  112. #undef rule
  113. #undef opt_rule
  114. };
  115. // Macro to create a list of N identifiers where N is the number of variable arguments to the macro
  116. #define RULE_EXPAND(x) x
  117. #define RULE_PADDING(rule, ...) RULE_PADDING2(rule, __VA_ARGS__, RULE_PADDING_IDS(rule))
  118. #define RULE_PADDING2(rule, ...) RULE_EXPAND(RULE_PADDING3(rule, __VA_ARGS__))
  119. #define RULE_PADDING3(rule, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, ...) __VA_ARGS__
  120. #define RULE_PADDING_IDS(r) PAD13_##r, PAD12_##r, PAD11_##r, PAD10_##r, PAD9_##r, PAD8_##r, PAD7_##r, PAD6_##r, PAD5_##r, PAD4_##r, PAD3_##r, PAD2_##r, PAD1_##r,
  121. // Use an enum to create constants specifying how much room a rule takes in rule_arg_combined_table
  122. enum {
  123. #define DEF_RULE(rule, comp, kind, ...) RULE_PADDING(rule, __VA_ARGS__)
  124. #define DEF_RULE_NC(rule, kind, ...)
  125. #include "py/grammar.h"
  126. #undef DEF_RULE
  127. #undef DEF_RULE_NC
  128. #define DEF_RULE(rule, comp, kind, ...)
  129. #define DEF_RULE_NC(rule, kind, ...) RULE_PADDING(rule, __VA_ARGS__)
  130. #include "py/grammar.h"
  131. #undef DEF_RULE
  132. #undef DEF_RULE_NC
  133. };
  134. // Macro to compute the start of a rule in rule_arg_combined_table
  135. #define RULE_ARG_OFFSET(rule, ...) RULE_ARG_OFFSET2(rule, __VA_ARGS__, RULE_ARG_OFFSET_IDS(rule))
  136. #define RULE_ARG_OFFSET2(rule, ...) RULE_EXPAND(RULE_ARG_OFFSET3(rule, __VA_ARGS__))
  137. #define RULE_ARG_OFFSET3(rule, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, ...) _14
  138. #define RULE_ARG_OFFSET_IDS(r) PAD13_##r, PAD12_##r, PAD11_##r, PAD10_##r, PAD9_##r, PAD8_##r, PAD7_##r, PAD6_##r, PAD5_##r, PAD4_##r, PAD3_##r, PAD2_##r, PAD1_##r, PAD0_##r,
  139. // Use the above enum values to create a table of offsets for each rule's arg
  140. // data, which indexes rule_arg_combined_table. The offsets require 9 bits of
  141. // storage but only the lower 8 bits are stored here. The 9th bit is computed
  142. // in get_rule_arg using the FIRST_RULE_WITH_OFFSET_ABOVE_255 constant.
  143. static const uint8_t rule_arg_offset_table[] = {
  144. #define DEF_RULE(rule, comp, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) & 0xff,
  145. #define DEF_RULE_NC(rule, kind, ...)
  146. #include "py/grammar.h"
  147. #undef DEF_RULE
  148. #undef DEF_RULE_NC
  149. 0, // RULE_const_object
  150. #define DEF_RULE(rule, comp, kind, ...)
  151. #define DEF_RULE_NC(rule, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) & 0xff,
  152. #include "py/grammar.h"
  153. #undef DEF_RULE
  154. #undef DEF_RULE_NC
  155. };
  156. // Define a constant that's used to determine the 9th bit of the values in rule_arg_offset_table
  157. static const size_t FIRST_RULE_WITH_OFFSET_ABOVE_255 =
  158. #define DEF_RULE(rule, comp, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) >= 0x100 ? RULE_##rule :
  159. #define DEF_RULE_NC(rule, kind, ...)
  160. #include "py/grammar.h"
  161. #undef DEF_RULE
  162. #undef DEF_RULE_NC
  163. #define DEF_RULE(rule, comp, kind, ...)
  164. #define DEF_RULE_NC(rule, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) >= 0x100 ? RULE_##rule :
  165. #include "py/grammar.h"
  166. #undef DEF_RULE
  167. #undef DEF_RULE_NC
  168. 0;
  169. #if MICROPY_DEBUG_PARSE_RULE_NAME
  170. // Define an array of rule names corresponding to each rule
  171. static const char *const rule_name_table[] = {
  172. #define DEF_RULE(rule, comp, kind, ...) #rule,
  173. #define DEF_RULE_NC(rule, kind, ...)
  174. #include "py/grammar.h"
  175. #undef DEF_RULE
  176. #undef DEF_RULE_NC
  177. "", // RULE_const_object
  178. #define DEF_RULE(rule, comp, kind, ...)
  179. #define DEF_RULE_NC(rule, kind, ...) #rule,
  180. #include "py/grammar.h"
  181. #undef DEF_RULE
  182. #undef DEF_RULE_NC
  183. };
  184. #endif
  185. // *FORMAT-ON*
  186. typedef struct _rule_stack_t {
  187. size_t src_line : (8 * sizeof(size_t) - 8); // maximum bits storing source line number
  188. size_t rule_id : 8; // this must be large enough to fit largest rule number
  189. size_t arg_i; // this dictates the maximum nodes in a "list" of things
  190. } rule_stack_t;
  191. typedef struct _mp_parse_chunk_t {
  192. size_t alloc;
  193. union {
  194. size_t used;
  195. struct _mp_parse_chunk_t *next;
  196. } union_;
  197. byte data[];
  198. } mp_parse_chunk_t;
  199. typedef struct _parser_t {
  200. size_t rule_stack_alloc;
  201. size_t rule_stack_top;
  202. rule_stack_t *rule_stack;
  203. size_t result_stack_alloc;
  204. size_t result_stack_top;
  205. mp_parse_node_t *result_stack;
  206. mp_lexer_t *lexer;
  207. mp_parse_tree_t tree;
  208. mp_parse_chunk_t *cur_chunk;
  209. #if MICROPY_COMP_CONST
  210. mp_map_t consts;
  211. #endif
  212. } parser_t;
  213. static void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args);
  214. static const uint16_t *get_rule_arg(uint8_t r_id) {
  215. size_t off = rule_arg_offset_table[r_id];
  216. if (r_id >= FIRST_RULE_WITH_OFFSET_ABOVE_255) {
  217. off |= 0x100;
  218. }
  219. return &rule_arg_combined_table[off];
  220. }
  221. static void *parser_alloc(parser_t *parser, size_t num_bytes) {
  222. // use a custom memory allocator to store parse nodes sequentially in large chunks
  223. mp_parse_chunk_t *chunk = parser->cur_chunk;
  224. if (chunk != NULL && chunk->union_.used + num_bytes > chunk->alloc) {
  225. // not enough room at end of previously allocated chunk so try to grow
  226. mp_parse_chunk_t *new_data = (mp_parse_chunk_t *)m_renew_maybe(byte, chunk,
  227. sizeof(mp_parse_chunk_t) + chunk->alloc,
  228. sizeof(mp_parse_chunk_t) + chunk->alloc + num_bytes, false);
  229. if (new_data == NULL) {
  230. // could not grow existing memory; shrink it to fit previous
  231. (void)m_renew_maybe(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc,
  232. sizeof(mp_parse_chunk_t) + chunk->union_.used, false);
  233. chunk->alloc = chunk->union_.used;
  234. chunk->union_.next = parser->tree.chunk;
  235. parser->tree.chunk = chunk;
  236. chunk = NULL;
  237. } else {
  238. // could grow existing memory
  239. chunk->alloc += num_bytes;
  240. }
  241. }
  242. if (chunk == NULL) {
  243. // no previous chunk, allocate a new chunk
  244. size_t alloc = MICROPY_ALLOC_PARSE_CHUNK_INIT;
  245. if (alloc < num_bytes) {
  246. alloc = num_bytes;
  247. }
  248. chunk = (mp_parse_chunk_t *)m_new(byte, sizeof(mp_parse_chunk_t) + alloc);
  249. chunk->alloc = alloc;
  250. chunk->union_.used = 0;
  251. parser->cur_chunk = chunk;
  252. }
  253. byte *ret = chunk->data + chunk->union_.used;
  254. chunk->union_.used += num_bytes;
  255. return ret;
  256. }
  257. #if MICROPY_COMP_CONST_TUPLE
  258. static void parser_free_parse_node_struct(parser_t *parser, mp_parse_node_struct_t *pns) {
  259. mp_parse_chunk_t *chunk = parser->cur_chunk;
  260. if (chunk->data <= (byte *)pns && (byte *)pns < chunk->data + chunk->union_.used) {
  261. size_t num_bytes = sizeof(mp_parse_node_struct_t) + sizeof(mp_parse_node_t) * MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  262. chunk->union_.used -= num_bytes;
  263. }
  264. }
  265. #endif
  266. static void push_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t arg_i) {
  267. if (parser->rule_stack_top >= parser->rule_stack_alloc) {
  268. rule_stack_t *rs = m_renew(rule_stack_t, parser->rule_stack, parser->rule_stack_alloc, parser->rule_stack_alloc + MICROPY_ALLOC_PARSE_RULE_INC);
  269. parser->rule_stack = rs;
  270. parser->rule_stack_alloc += MICROPY_ALLOC_PARSE_RULE_INC;
  271. }
  272. rule_stack_t *rs = &parser->rule_stack[parser->rule_stack_top++];
  273. rs->src_line = src_line;
  274. rs->rule_id = rule_id;
  275. rs->arg_i = arg_i;
  276. }
  277. static void push_rule_from_arg(parser_t *parser, size_t arg) {
  278. assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE || (arg & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE);
  279. size_t rule_id = arg & RULE_ARG_ARG_MASK;
  280. push_rule(parser, parser->lexer->tok_line, rule_id, 0);
  281. }
  282. static uint8_t pop_rule(parser_t *parser, size_t *arg_i, size_t *src_line) {
  283. parser->rule_stack_top -= 1;
  284. uint8_t rule_id = parser->rule_stack[parser->rule_stack_top].rule_id;
  285. *arg_i = parser->rule_stack[parser->rule_stack_top].arg_i;
  286. *src_line = parser->rule_stack[parser->rule_stack_top].src_line;
  287. return rule_id;
  288. }
  289. #if MICROPY_COMP_CONST_TUPLE
  290. static uint8_t peek_rule(parser_t *parser, size_t n) {
  291. assert(parser->rule_stack_top > n);
  292. return parser->rule_stack[parser->rule_stack_top - 1 - n].rule_id;
  293. }
  294. #endif
  295. bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) {
  296. if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  297. *o = MP_OBJ_NEW_SMALL_INT(MP_PARSE_NODE_LEAF_SMALL_INT(pn));
  298. return true;
  299. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_const_object)) {
  300. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  301. *o = mp_parse_node_extract_const_object(pns);
  302. return mp_obj_is_int(*o);
  303. } else {
  304. return false;
  305. }
  306. }
  307. #if MICROPY_COMP_CONST_TUPLE || MICROPY_COMP_CONST
  308. static bool mp_parse_node_is_const(mp_parse_node_t pn) {
  309. if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  310. // Small integer.
  311. return true;
  312. } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
  313. // Possible str, or constant literal.
  314. uintptr_t kind = MP_PARSE_NODE_LEAF_KIND(pn);
  315. if (kind == MP_PARSE_NODE_STRING) {
  316. return true;
  317. } else if (kind == MP_PARSE_NODE_TOKEN) {
  318. uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
  319. return arg == MP_TOKEN_KW_NONE
  320. || arg == MP_TOKEN_KW_FALSE
  321. || arg == MP_TOKEN_KW_TRUE
  322. || arg == MP_TOKEN_ELLIPSIS;
  323. }
  324. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_const_object)) {
  325. // Constant object.
  326. return true;
  327. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_atom_paren)) {
  328. // Possible empty tuple.
  329. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  330. return MP_PARSE_NODE_IS_NULL(pns->nodes[0]);
  331. }
  332. return false;
  333. }
  334. static mp_obj_t mp_parse_node_convert_to_obj(mp_parse_node_t pn) {
  335. assert(mp_parse_node_is_const(pn));
  336. if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  337. mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn);
  338. #if MICROPY_DYNAMIC_COMPILER
  339. mp_uint_t sign_mask = -((mp_uint_t)1 << (mp_dynamic_compiler.small_int_bits - 1));
  340. if (!((arg & sign_mask) == 0 || (arg & sign_mask) == sign_mask)) {
  341. // Integer doesn't fit in a small-int, so create a multi-precision int object.
  342. return mp_obj_new_int_from_ll(arg);
  343. }
  344. #endif
  345. return MP_OBJ_NEW_SMALL_INT(arg);
  346. } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
  347. uintptr_t kind = MP_PARSE_NODE_LEAF_KIND(pn);
  348. uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
  349. if (kind == MP_PARSE_NODE_STRING) {
  350. return MP_OBJ_NEW_QSTR(arg);
  351. } else {
  352. assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN);
  353. switch (arg) {
  354. case MP_TOKEN_KW_NONE:
  355. return mp_const_none;
  356. case MP_TOKEN_KW_FALSE:
  357. return mp_const_false;
  358. case MP_TOKEN_KW_TRUE:
  359. return mp_const_true;
  360. default:
  361. assert(arg == MP_TOKEN_ELLIPSIS);
  362. return MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj);
  363. }
  364. }
  365. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_const_object)) {
  366. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  367. return mp_parse_node_extract_const_object(pns);
  368. } else {
  369. assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_atom_paren));
  370. assert(MP_PARSE_NODE_IS_NULL(((mp_parse_node_struct_t *)pn)->nodes[0]));
  371. return mp_const_empty_tuple;
  372. }
  373. }
  374. #endif
  375. static bool parse_node_is_const_bool(mp_parse_node_t pn, bool value) {
  376. // Returns true if 'pn' is a constant whose boolean value is equivalent to 'value'
  377. #if MICROPY_COMP_CONST_TUPLE || MICROPY_COMP_CONST
  378. return mp_parse_node_is_const(pn) && mp_obj_is_true(mp_parse_node_convert_to_obj(pn)) == value;
  379. #else
  380. return MP_PARSE_NODE_IS_TOKEN_KIND(pn, value ? MP_TOKEN_KW_TRUE : MP_TOKEN_KW_FALSE)
  381. || (MP_PARSE_NODE_IS_SMALL_INT(pn) && !!MP_PARSE_NODE_LEAF_SMALL_INT(pn) == value);
  382. #endif
  383. }
  384. bool mp_parse_node_is_const_false(mp_parse_node_t pn) {
  385. return parse_node_is_const_bool(pn, false);
  386. }
  387. bool mp_parse_node_is_const_true(mp_parse_node_t pn) {
  388. return parse_node_is_const_bool(pn, true);
  389. }
  390. size_t mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_node_t **nodes) {
  391. if (MP_PARSE_NODE_IS_NULL(*pn)) {
  392. *nodes = NULL;
  393. return 0;
  394. } else if (MP_PARSE_NODE_IS_LEAF(*pn)) {
  395. *nodes = pn;
  396. return 1;
  397. } else {
  398. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)(*pn);
  399. if (MP_PARSE_NODE_STRUCT_KIND(pns) != pn_kind) {
  400. *nodes = pn;
  401. return 1;
  402. } else {
  403. *nodes = pns->nodes;
  404. return MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  405. }
  406. }
  407. }
  408. #if MICROPY_DEBUG_PRINTERS
  409. void mp_parse_node_print(const mp_print_t *print, mp_parse_node_t pn, size_t indent) {
  410. if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  411. mp_printf(print, "[% 4d] ", (int)((mp_parse_node_struct_t *)pn)->source_line);
  412. } else {
  413. mp_printf(print, " ");
  414. }
  415. for (size_t i = 0; i < indent; i++) {
  416. mp_printf(print, " ");
  417. }
  418. if (MP_PARSE_NODE_IS_NULL(pn)) {
  419. mp_printf(print, "NULL\n");
  420. } else if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  421. mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn);
  422. mp_printf(print, "int(" INT_FMT ")\n", arg);
  423. } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
  424. uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
  425. switch (MP_PARSE_NODE_LEAF_KIND(pn)) {
  426. case MP_PARSE_NODE_ID:
  427. mp_printf(print, "id(%s)\n", qstr_str(arg));
  428. break;
  429. case MP_PARSE_NODE_STRING:
  430. mp_printf(print, "str(%s)\n", qstr_str(arg));
  431. break;
  432. default:
  433. assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN);
  434. mp_printf(print, "tok(%u)\n", (uint)arg);
  435. break;
  436. }
  437. } else {
  438. // node must be a mp_parse_node_struct_t
  439. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  440. if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_const_object) {
  441. mp_obj_t obj = mp_parse_node_extract_const_object(pns);
  442. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  443. mp_printf(print, "literal const(%016llx)=", obj);
  444. #else
  445. mp_printf(print, "literal const(%p)=", obj);
  446. #endif
  447. mp_obj_print_helper(print, obj, PRINT_REPR);
  448. mp_printf(print, "\n");
  449. } else {
  450. size_t n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  451. #if MICROPY_DEBUG_PARSE_RULE_NAME
  452. mp_printf(print, "%s(%u) (n=%u)\n", rule_name_table[MP_PARSE_NODE_STRUCT_KIND(pns)], (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
  453. #else
  454. mp_printf(print, "rule(%u) (n=%u)\n", (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
  455. #endif
  456. for (size_t i = 0; i < n; i++) {
  457. mp_parse_node_print(print, pns->nodes[i], indent + 2);
  458. }
  459. }
  460. }
  461. }
  462. #endif // MICROPY_DEBUG_PRINTERS
  463. /*
  464. static void result_stack_show(const mp_print_t *print, parser_t *parser) {
  465. mp_printf(print, "result stack, most recent first\n");
  466. for (ssize_t i = parser->result_stack_top - 1; i >= 0; i--) {
  467. mp_parse_node_print(print, parser->result_stack[i], 0);
  468. }
  469. }
  470. */
  471. static mp_parse_node_t pop_result(parser_t *parser) {
  472. assert(parser->result_stack_top > 0);
  473. return parser->result_stack[--parser->result_stack_top];
  474. }
  475. static mp_parse_node_t peek_result(parser_t *parser, size_t pos) {
  476. assert(parser->result_stack_top > pos);
  477. return parser->result_stack[parser->result_stack_top - 1 - pos];
  478. }
  479. static void push_result_node(parser_t *parser, mp_parse_node_t pn) {
  480. if (parser->result_stack_top >= parser->result_stack_alloc) {
  481. mp_parse_node_t *stack = m_renew(mp_parse_node_t, parser->result_stack, parser->result_stack_alloc, parser->result_stack_alloc + MICROPY_ALLOC_PARSE_RESULT_INC);
  482. parser->result_stack = stack;
  483. parser->result_stack_alloc += MICROPY_ALLOC_PARSE_RESULT_INC;
  484. }
  485. parser->result_stack[parser->result_stack_top++] = pn;
  486. }
  487. static mp_parse_node_t make_node_const_object(parser_t *parser, size_t src_line, mp_obj_t obj) {
  488. mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_obj_t));
  489. pn->source_line = src_line;
  490. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  491. // nodes are 32-bit pointers, but need to store 64-bit object
  492. pn->kind_num_nodes = RULE_const_object | (2 << 8);
  493. pn->nodes[0] = (uint64_t)obj;
  494. pn->nodes[1] = (uint64_t)obj >> 32;
  495. #else
  496. pn->kind_num_nodes = RULE_const_object | (1 << 8);
  497. pn->nodes[0] = (uintptr_t)obj;
  498. #endif
  499. return (mp_parse_node_t)pn;
  500. }
  501. // Create a parse node representing a constant object, possibly optimising the case of
  502. // an integer, by putting the (small) integer value directly in the parse node itself.
  503. static mp_parse_node_t make_node_const_object_optimised(parser_t *parser, size_t src_line, mp_obj_t obj) {
  504. if (mp_obj_is_small_int(obj)) {
  505. mp_int_t val = MP_OBJ_SMALL_INT_VALUE(obj);
  506. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  507. // A parse node is only 32-bits and the small-int value must fit in 31-bits
  508. if (((val ^ (val << 1)) & 0xffffffff80000000) != 0) {
  509. return make_node_const_object(parser, src_line, obj);
  510. }
  511. #endif
  512. #if MICROPY_DYNAMIC_COMPILER
  513. // Check that the integer value fits in target runtime's small-int
  514. mp_uint_t sign_mask = -((mp_uint_t)1 << (mp_dynamic_compiler.small_int_bits - 1));
  515. if (!((val & sign_mask) == 0 || (val & sign_mask) == sign_mask)) {
  516. return make_node_const_object(parser, src_line, obj);
  517. }
  518. #endif
  519. return mp_parse_node_new_small_int(val);
  520. } else {
  521. return make_node_const_object(parser, src_line, obj);
  522. }
  523. }
  524. static void push_result_token(parser_t *parser, uint8_t rule_id) {
  525. mp_parse_node_t pn;
  526. mp_lexer_t *lex = parser->lexer;
  527. if (lex->tok_kind == MP_TOKEN_NAME) {
  528. qstr id = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
  529. #if MICROPY_COMP_CONST
  530. // if name is a standalone identifier, look it up in the table of dynamic constants
  531. mp_map_elem_t *elem;
  532. if (rule_id == RULE_atom
  533. && (elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP)) != NULL) {
  534. pn = make_node_const_object_optimised(parser, lex->tok_line, elem->value);
  535. } else {
  536. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
  537. }
  538. #else
  539. (void)rule_id;
  540. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
  541. #endif
  542. } else if (lex->tok_kind == MP_TOKEN_INTEGER) {
  543. mp_obj_t o = mp_parse_num_integer(lex->vstr.buf, lex->vstr.len, 0, lex);
  544. pn = make_node_const_object_optimised(parser, lex->tok_line, o);
  545. } else if (lex->tok_kind == MP_TOKEN_FLOAT_OR_IMAG) {
  546. mp_obj_t o = mp_parse_num_float(lex->vstr.buf, lex->vstr.len, true, lex);
  547. pn = make_node_const_object(parser, lex->tok_line, o);
  548. } else if (lex->tok_kind == MP_TOKEN_STRING) {
  549. // Don't automatically intern all strings. Doc strings (which are usually large)
  550. // will be discarded by the compiler, and so we shouldn't intern them.
  551. qstr qst = MP_QSTRnull;
  552. if (lex->vstr.len <= MICROPY_ALLOC_PARSE_INTERN_STRING_LEN) {
  553. // intern short strings
  554. qst = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
  555. } else {
  556. // check if this string is already interned
  557. qst = qstr_find_strn(lex->vstr.buf, lex->vstr.len);
  558. }
  559. if (qst != MP_QSTRnull) {
  560. // qstr exists, make a leaf node
  561. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_STRING, qst);
  562. } else {
  563. // not interned, make a node holding a pointer to the string object
  564. mp_obj_t o = mp_obj_new_str_copy(&mp_type_str, (const byte *)lex->vstr.buf, lex->vstr.len);
  565. pn = make_node_const_object(parser, lex->tok_line, o);
  566. }
  567. } else if (lex->tok_kind == MP_TOKEN_BYTES) {
  568. // make a node holding a pointer to the bytes object
  569. mp_obj_t o = mp_obj_new_bytes((const byte *)lex->vstr.buf, lex->vstr.len);
  570. pn = make_node_const_object(parser, lex->tok_line, o);
  571. } else {
  572. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, lex->tok_kind);
  573. }
  574. push_result_node(parser, pn);
  575. }
  576. #if MICROPY_COMP_CONST_FOLDING
  577. #if MICROPY_COMP_MODULE_CONST
  578. static const mp_rom_map_elem_t mp_constants_table[] = {
  579. #if MICROPY_PY_ERRNO
  580. { MP_ROM_QSTR(MP_QSTR_errno), MP_ROM_PTR(&mp_module_errno) },
  581. #endif
  582. #if MICROPY_PY_UCTYPES
  583. { MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) },
  584. #endif
  585. // Extra constants as defined by a port
  586. MICROPY_PORT_CONSTANTS
  587. };
  588. static MP_DEFINE_CONST_MAP(mp_constants_map, mp_constants_table);
  589. #endif
  590. #if MICROPY_COMP_CONST_FOLDING_COMPILER_WORKAROUND
  591. // Some versions of the xtensa-esp32-elf-gcc compiler generate wrong code if this
  592. // function is static, so provide a hook for them to work around this problem.
  593. MP_NOINLINE
  594. #endif
  595. static bool fold_logical_constants(parser_t *parser, uint8_t rule_id, size_t *num_args) {
  596. if (rule_id == RULE_or_test
  597. || rule_id == RULE_and_test) {
  598. // folding for binary logical ops: or and
  599. size_t copy_to = *num_args;
  600. for (size_t i = copy_to; i > 0;) {
  601. mp_parse_node_t pn = peek_result(parser, --i);
  602. parser->result_stack[parser->result_stack_top - copy_to] = pn;
  603. if (i == 0) {
  604. // always need to keep the last value
  605. break;
  606. }
  607. if (rule_id == RULE_or_test) {
  608. if (mp_parse_node_is_const_true(pn)) {
  609. //
  610. break;
  611. } else if (!mp_parse_node_is_const_false(pn)) {
  612. copy_to -= 1;
  613. }
  614. } else {
  615. // RULE_and_test
  616. if (mp_parse_node_is_const_false(pn)) {
  617. break;
  618. } else if (!mp_parse_node_is_const_true(pn)) {
  619. copy_to -= 1;
  620. }
  621. }
  622. }
  623. copy_to -= 1; // copy_to now contains number of args to pop
  624. // pop and discard all the short-circuited expressions
  625. for (size_t i = 0; i < copy_to; ++i) {
  626. pop_result(parser);
  627. }
  628. *num_args -= copy_to;
  629. // we did a complete folding if there's only 1 arg left
  630. return *num_args == 1;
  631. } else if (rule_id == RULE_not_test_2) {
  632. // folding for unary logical op: not
  633. mp_parse_node_t pn = peek_result(parser, 0);
  634. if (mp_parse_node_is_const_false(pn)) {
  635. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_TRUE);
  636. } else if (mp_parse_node_is_const_true(pn)) {
  637. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_FALSE);
  638. } else {
  639. return false;
  640. }
  641. pop_result(parser);
  642. push_result_node(parser, pn);
  643. return true;
  644. }
  645. return false;
  646. }
  647. static bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) {
  648. // this code does folding of arbitrary integer expressions, eg 1 + 2 * 3 + 4
  649. // it does not do partial folding, eg 1 + 2 + x -> 3 + x
  650. mp_obj_t arg0;
  651. if (rule_id == RULE_expr
  652. || rule_id == RULE_xor_expr
  653. || rule_id == RULE_and_expr
  654. || rule_id == RULE_power) {
  655. // folding for binary ops: | ^ & **
  656. mp_parse_node_t pn = peek_result(parser, num_args - 1);
  657. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  658. return false;
  659. }
  660. mp_binary_op_t op;
  661. if (rule_id == RULE_expr) {
  662. op = MP_BINARY_OP_OR;
  663. } else if (rule_id == RULE_xor_expr) {
  664. op = MP_BINARY_OP_XOR;
  665. } else if (rule_id == RULE_and_expr) {
  666. op = MP_BINARY_OP_AND;
  667. } else {
  668. op = MP_BINARY_OP_POWER;
  669. }
  670. for (ssize_t i = num_args - 2; i >= 0; --i) {
  671. pn = peek_result(parser, i);
  672. mp_obj_t arg1;
  673. if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
  674. return false;
  675. }
  676. if (op == MP_BINARY_OP_POWER && mp_obj_int_sign(arg1) < 0) {
  677. // ** can't have negative rhs
  678. return false;
  679. }
  680. arg0 = mp_binary_op(op, arg0, arg1);
  681. }
  682. } else if (rule_id == RULE_shift_expr
  683. || rule_id == RULE_arith_expr
  684. || rule_id == RULE_term) {
  685. // folding for binary ops: << >> + - * @ / % //
  686. mp_parse_node_t pn = peek_result(parser, num_args - 1);
  687. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  688. return false;
  689. }
  690. for (ssize_t i = num_args - 2; i >= 1; i -= 2) {
  691. pn = peek_result(parser, i - 1);
  692. mp_obj_t arg1;
  693. if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
  694. return false;
  695. }
  696. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, i));
  697. if (tok == MP_TOKEN_OP_AT || tok == MP_TOKEN_OP_SLASH) {
  698. // Can't fold @ or /
  699. return false;
  700. }
  701. mp_binary_op_t op = MP_BINARY_OP_LSHIFT + (tok - MP_TOKEN_OP_DBL_LESS);
  702. int rhs_sign = mp_obj_int_sign(arg1);
  703. if (op <= MP_BINARY_OP_RSHIFT) {
  704. // << and >> can't have negative rhs
  705. if (rhs_sign < 0) {
  706. return false;
  707. }
  708. } else if (op >= MP_BINARY_OP_FLOOR_DIVIDE) {
  709. // % and // can't have zero rhs
  710. if (rhs_sign == 0) {
  711. return false;
  712. }
  713. }
  714. arg0 = mp_binary_op(op, arg0, arg1);
  715. }
  716. } else if (rule_id == RULE_factor_2) {
  717. // folding for unary ops: + - ~
  718. mp_parse_node_t pn = peek_result(parser, 0);
  719. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  720. return false;
  721. }
  722. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, 1));
  723. mp_unary_op_t op;
  724. if (tok == MP_TOKEN_OP_TILDE) {
  725. op = MP_UNARY_OP_INVERT;
  726. } else {
  727. assert(tok == MP_TOKEN_OP_PLUS || tok == MP_TOKEN_OP_MINUS); // should be
  728. op = MP_UNARY_OP_POSITIVE + (tok - MP_TOKEN_OP_PLUS);
  729. }
  730. arg0 = mp_unary_op(op, arg0);
  731. #if MICROPY_COMP_CONST
  732. } else if (rule_id == RULE_expr_stmt) {
  733. mp_parse_node_t pn1 = peek_result(parser, 0);
  734. if (!MP_PARSE_NODE_IS_NULL(pn1)
  735. && !(MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_augassign)
  736. || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) {
  737. // this node is of the form <x> = <y>
  738. mp_parse_node_t pn0 = peek_result(parser, 1);
  739. if (MP_PARSE_NODE_IS_ID(pn0)
  740. && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_atom_expr_normal)
  741. && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t *)pn1)->nodes[0])
  742. && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t *)pn1)->nodes[0]) == MP_QSTR_const
  743. && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t *)pn1)->nodes[1], RULE_trailer_paren)
  744. ) {
  745. // code to assign dynamic constants: id = const(value)
  746. // get the id
  747. qstr id = MP_PARSE_NODE_LEAF_ARG(pn0);
  748. // get the value
  749. mp_parse_node_t pn_value = ((mp_parse_node_struct_t *)((mp_parse_node_struct_t *)pn1)->nodes[1])->nodes[0];
  750. if (!mp_parse_node_is_const(pn_value)) {
  751. mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  752. MP_ERROR_TEXT("not a constant"));
  753. mp_obj_exception_add_traceback(exc, parser->lexer->source_name,
  754. ((mp_parse_node_struct_t *)pn1)->source_line, MP_QSTRnull);
  755. nlr_raise(exc);
  756. }
  757. mp_obj_t value = mp_parse_node_convert_to_obj(pn_value);
  758. // store the value in the table of dynamic constants
  759. mp_map_elem_t *elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
  760. assert(elem->value == MP_OBJ_NULL);
  761. elem->value = value;
  762. // If the constant starts with an underscore then treat it as a private
  763. // variable and don't emit any code to store the value to the id.
  764. if (qstr_str(id)[0] == '_') {
  765. pop_result(parser); // pop const(value)
  766. pop_result(parser); // pop id
  767. push_result_rule(parser, 0, RULE_pass_stmt, 0); // replace with "pass"
  768. return true;
  769. }
  770. // replace const(value) with value
  771. pop_result(parser);
  772. push_result_node(parser, pn_value);
  773. // finished folding this assignment, but we still want it to be part of the tree
  774. return false;
  775. }
  776. }
  777. return false;
  778. #endif
  779. #if MICROPY_COMP_MODULE_CONST
  780. } else if (rule_id == RULE_atom_expr_normal) {
  781. mp_parse_node_t pn0 = peek_result(parser, 1);
  782. mp_parse_node_t pn1 = peek_result(parser, 0);
  783. if (!(MP_PARSE_NODE_IS_ID(pn0)
  784. && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) {
  785. return false;
  786. }
  787. // id1.id2
  788. // look it up in constant table, see if it can be replaced with an integer
  789. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pn1;
  790. assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
  791. qstr q_base = MP_PARSE_NODE_LEAF_ARG(pn0);
  792. qstr q_attr = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]);
  793. mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP);
  794. if (elem == NULL) {
  795. return false;
  796. }
  797. mp_obj_t dest[2];
  798. mp_load_method_maybe(elem->value, q_attr, dest);
  799. if (!(dest[0] != MP_OBJ_NULL && mp_obj_is_int(dest[0]) && dest[1] == MP_OBJ_NULL)) {
  800. return false;
  801. }
  802. arg0 = dest[0];
  803. #endif
  804. } else {
  805. return false;
  806. }
  807. // success folding this rule
  808. for (size_t i = num_args; i > 0; i--) {
  809. pop_result(parser);
  810. }
  811. push_result_node(parser, make_node_const_object_optimised(parser, 0, arg0));
  812. return true;
  813. }
  814. #endif // MICROPY_COMP_CONST_FOLDING
  815. #if MICROPY_COMP_CONST_TUPLE
  816. static bool build_tuple_from_stack(parser_t *parser, size_t src_line, size_t num_args) {
  817. for (size_t i = num_args; i > 0;) {
  818. mp_parse_node_t pn = peek_result(parser, --i);
  819. if (!mp_parse_node_is_const(pn)) {
  820. return false;
  821. }
  822. }
  823. mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_args, NULL));
  824. for (size_t i = num_args; i > 0;) {
  825. mp_parse_node_t pn = pop_result(parser);
  826. tuple->items[--i] = mp_parse_node_convert_to_obj(pn);
  827. if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  828. parser_free_parse_node_struct(parser, (mp_parse_node_struct_t *)pn);
  829. }
  830. }
  831. push_result_node(parser, make_node_const_object(parser, src_line, MP_OBJ_FROM_PTR(tuple)));
  832. return true;
  833. }
  834. static bool build_tuple(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args) {
  835. if (rule_id == RULE_testlist_comp) {
  836. if (peek_rule(parser, 0) == RULE_atom_paren) {
  837. // Tuple of the form "(a,)".
  838. return build_tuple_from_stack(parser, src_line, num_args);
  839. }
  840. }
  841. if (rule_id == RULE_testlist_comp_3c) {
  842. assert(peek_rule(parser, 0) == RULE_testlist_comp_3b);
  843. assert(peek_rule(parser, 1) == RULE_testlist_comp);
  844. if (peek_rule(parser, 2) == RULE_atom_paren) {
  845. // Tuple of the form "(a, b)".
  846. if (build_tuple_from_stack(parser, src_line, num_args)) {
  847. parser->rule_stack_top -= 2; // discard 2 rules
  848. return true;
  849. }
  850. }
  851. }
  852. if (rule_id == RULE_testlist_star_expr
  853. || rule_id == RULE_testlist
  854. || rule_id == RULE_subscriptlist) {
  855. // Tuple of the form:
  856. // - x = a, b
  857. // - return a, b
  858. // - for x in a, b: pass
  859. // - x[a, b]
  860. return build_tuple_from_stack(parser, src_line, num_args);
  861. }
  862. return false;
  863. }
  864. #endif
  865. static void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args) {
  866. // Simplify and optimise certain rules, to reduce memory usage and simplify the compiler.
  867. if (rule_id == RULE_atom_paren) {
  868. // Remove parenthesis around a single expression if possible.
  869. // This atom_paren rule always has a single argument, and after this
  870. // optimisation that argument is either NULL or testlist_comp.
  871. mp_parse_node_t pn = peek_result(parser, 0);
  872. if (MP_PARSE_NODE_IS_NULL(pn)) {
  873. // need to keep parenthesis for ()
  874. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_testlist_comp)) {
  875. // need to keep parenthesis for (a, b, ...)
  876. } else {
  877. // parenthesis around a single expression, so it's just the expression
  878. return;
  879. }
  880. } else if (rule_id == RULE_testlist_comp) {
  881. // The testlist_comp rule can be the sole argument to either atom_parent
  882. // or atom_bracket, for (...) and [...] respectively.
  883. assert(num_args == 2);
  884. mp_parse_node_t pn = peek_result(parser, 0);
  885. if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  886. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  887. if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_testlist_comp_3b) {
  888. // tuple of one item, with trailing comma
  889. pop_result(parser);
  890. --num_args;
  891. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_testlist_comp_3c) {
  892. // tuple of many items, convert testlist_comp_3c to testlist_comp
  893. pop_result(parser);
  894. assert(pn == peek_result(parser, 0));
  895. pns->kind_num_nodes = rule_id | MP_PARSE_NODE_STRUCT_NUM_NODES(pns) << 8;
  896. return;
  897. } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_comp_for) {
  898. // generator expression
  899. } else {
  900. // tuple with 2 items
  901. }
  902. } else {
  903. // tuple with 2 items
  904. }
  905. } else if (rule_id == RULE_testlist_comp_3c) {
  906. // steal first arg of outer testlist_comp rule
  907. ++num_args;
  908. }
  909. #if MICROPY_COMP_CONST_FOLDING
  910. if (fold_logical_constants(parser, rule_id, &num_args)) {
  911. // we folded this rule so return straight away
  912. return;
  913. }
  914. if (fold_constants(parser, rule_id, num_args)) {
  915. // we folded this rule so return straight away
  916. return;
  917. }
  918. #endif
  919. #if MICROPY_COMP_CONST_TUPLE
  920. if (build_tuple(parser, src_line, rule_id, num_args)) {
  921. // we built a tuple from this rule so return straight away
  922. return;
  923. }
  924. #endif
  925. mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_parse_node_t) * num_args);
  926. pn->source_line = src_line;
  927. pn->kind_num_nodes = (rule_id & 0xff) | (num_args << 8);
  928. for (size_t i = num_args; i > 0; i--) {
  929. pn->nodes[i - 1] = pop_result(parser);
  930. }
  931. if (rule_id == RULE_testlist_comp_3c) {
  932. // need to push something non-null to replace stolen first arg of testlist_comp
  933. push_result_node(parser, (mp_parse_node_t)pn);
  934. }
  935. push_result_node(parser, (mp_parse_node_t)pn);
  936. }
  937. mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) {
  938. // Set exception handler to free the lexer if an exception is raised.
  939. MP_DEFINE_NLR_JUMP_CALLBACK_FUNCTION_1(ctx, mp_lexer_free, lex);
  940. nlr_push_jump_callback(&ctx.callback, mp_call_function_1_from_nlr_jump_callback);
  941. // initialise parser and allocate memory for its stacks
  942. parser_t parser;
  943. parser.rule_stack_alloc = MICROPY_ALLOC_PARSE_RULE_INIT;
  944. parser.rule_stack_top = 0;
  945. parser.rule_stack = m_new(rule_stack_t, parser.rule_stack_alloc);
  946. parser.result_stack_alloc = MICROPY_ALLOC_PARSE_RESULT_INIT;
  947. parser.result_stack_top = 0;
  948. parser.result_stack = m_new(mp_parse_node_t, parser.result_stack_alloc);
  949. parser.lexer = lex;
  950. parser.tree.chunk = NULL;
  951. parser.cur_chunk = NULL;
  952. #if MICROPY_COMP_CONST
  953. mp_map_init(&parser.consts, 0);
  954. #endif
  955. // work out the top-level rule to use, and push it on the stack
  956. size_t top_level_rule;
  957. switch (input_kind) {
  958. case MP_PARSE_SINGLE_INPUT:
  959. top_level_rule = RULE_single_input;
  960. break;
  961. case MP_PARSE_EVAL_INPUT:
  962. top_level_rule = RULE_eval_input;
  963. break;
  964. default:
  965. top_level_rule = RULE_file_input;
  966. }
  967. push_rule(&parser, lex->tok_line, top_level_rule, 0);
  968. // parse!
  969. bool backtrack = false;
  970. for (;;) {
  971. next_rule:
  972. if (parser.rule_stack_top == 0) {
  973. break;
  974. }
  975. // Pop the next rule to process it
  976. size_t i; // state for the current rule
  977. size_t rule_src_line; // source line for the first token matched by the current rule
  978. uint8_t rule_id = pop_rule(&parser, &i, &rule_src_line);
  979. uint8_t rule_act = rule_act_table[rule_id];
  980. const uint16_t *rule_arg = get_rule_arg(rule_id);
  981. size_t n = rule_act & RULE_ACT_ARG_MASK;
  982. #if 0
  983. // debugging
  984. printf("depth=" UINT_FMT " ", parser.rule_stack_top);
  985. for (int j = 0; j < parser.rule_stack_top; ++j) {
  986. printf(" ");
  987. }
  988. printf("%s n=" UINT_FMT " i=" UINT_FMT " bt=%d\n", rule_name_table[rule_id], n, i, backtrack);
  989. #endif
  990. switch (rule_act & RULE_ACT_KIND_MASK) {
  991. case RULE_ACT_OR:
  992. if (i > 0 && !backtrack) {
  993. goto next_rule;
  994. } else {
  995. backtrack = false;
  996. }
  997. for (; i < n; ++i) {
  998. uint16_t kind = rule_arg[i] & RULE_ARG_KIND_MASK;
  999. if (kind == RULE_ARG_TOK) {
  1000. if (lex->tok_kind == (rule_arg[i] & RULE_ARG_ARG_MASK)) {
  1001. push_result_token(&parser, rule_id);
  1002. mp_lexer_to_next(lex);
  1003. goto next_rule;
  1004. }
  1005. } else {
  1006. assert(kind == RULE_ARG_RULE);
  1007. if (i + 1 < n) {
  1008. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this or-rule
  1009. }
  1010. push_rule_from_arg(&parser, rule_arg[i]); // push child of or-rule
  1011. goto next_rule;
  1012. }
  1013. }
  1014. backtrack = true;
  1015. break;
  1016. case RULE_ACT_AND: {
  1017. // failed, backtrack if we can, else syntax error
  1018. if (backtrack) {
  1019. assert(i > 0);
  1020. if ((rule_arg[i - 1] & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE) {
  1021. // an optional rule that failed, so continue with next arg
  1022. push_result_node(&parser, MP_PARSE_NODE_NULL);
  1023. backtrack = false;
  1024. } else {
  1025. // a mandatory rule that failed, so propagate backtrack
  1026. if (i > 1) {
  1027. // already eaten tokens so can't backtrack
  1028. goto syntax_error;
  1029. } else {
  1030. goto next_rule;
  1031. }
  1032. }
  1033. }
  1034. // progress through the rule
  1035. for (; i < n; ++i) {
  1036. if ((rule_arg[i] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  1037. // need to match a token
  1038. mp_token_kind_t tok_kind = rule_arg[i] & RULE_ARG_ARG_MASK;
  1039. if (lex->tok_kind == tok_kind) {
  1040. // matched token
  1041. if (tok_kind == MP_TOKEN_NAME) {
  1042. push_result_token(&parser, rule_id);
  1043. }
  1044. mp_lexer_to_next(lex);
  1045. } else {
  1046. // failed to match token
  1047. if (i > 0) {
  1048. // already eaten tokens so can't backtrack
  1049. goto syntax_error;
  1050. } else {
  1051. // this rule failed, so backtrack
  1052. backtrack = true;
  1053. goto next_rule;
  1054. }
  1055. }
  1056. } else {
  1057. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this and-rule
  1058. push_rule_from_arg(&parser, rule_arg[i]); // push child of and-rule
  1059. goto next_rule;
  1060. }
  1061. }
  1062. assert(i == n);
  1063. // matched the rule, so now build the corresponding parse_node
  1064. #if !MICROPY_ENABLE_DOC_STRING
  1065. // this code discards lonely statements, such as doc strings
  1066. if (input_kind != MP_PARSE_SINGLE_INPUT && rule_id == RULE_expr_stmt && peek_result(&parser, 0) == MP_PARSE_NODE_NULL) {
  1067. mp_parse_node_t p = peek_result(&parser, 1);
  1068. if ((MP_PARSE_NODE_IS_LEAF(p) && !MP_PARSE_NODE_IS_ID(p))
  1069. || MP_PARSE_NODE_IS_STRUCT_KIND(p, RULE_const_object)) {
  1070. pop_result(&parser); // MP_PARSE_NODE_NULL
  1071. pop_result(&parser); // const expression (leaf or RULE_const_object)
  1072. // Pushing the "pass" rule here will overwrite any RULE_const_object
  1073. // entry that was on the result stack, allowing the GC to reclaim
  1074. // the memory from the const object when needed.
  1075. push_result_rule(&parser, rule_src_line, RULE_pass_stmt, 0);
  1076. break;
  1077. }
  1078. }
  1079. #endif
  1080. // count number of arguments for the parse node
  1081. i = 0;
  1082. size_t num_not_nil = 0;
  1083. for (size_t x = n; x > 0;) {
  1084. --x;
  1085. if ((rule_arg[x] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  1086. mp_token_kind_t tok_kind = rule_arg[x] & RULE_ARG_ARG_MASK;
  1087. if (tok_kind == MP_TOKEN_NAME) {
  1088. // only tokens which were names are pushed to stack
  1089. i += 1;
  1090. num_not_nil += 1;
  1091. }
  1092. } else {
  1093. // rules are always pushed
  1094. if (peek_result(&parser, i) != MP_PARSE_NODE_NULL) {
  1095. num_not_nil += 1;
  1096. }
  1097. i += 1;
  1098. }
  1099. }
  1100. if (num_not_nil == 1 && (rule_act & RULE_ACT_ALLOW_IDENT)) {
  1101. // this rule has only 1 argument and should not be emitted
  1102. mp_parse_node_t pn = MP_PARSE_NODE_NULL;
  1103. for (size_t x = 0; x < i; ++x) {
  1104. mp_parse_node_t pn2 = pop_result(&parser);
  1105. if (pn2 != MP_PARSE_NODE_NULL) {
  1106. pn = pn2;
  1107. }
  1108. }
  1109. push_result_node(&parser, pn);
  1110. } else {
  1111. // this rule must be emitted
  1112. if (rule_act & RULE_ACT_ADD_BLANK) {
  1113. // and add an extra blank node at the end (used by the compiler to store data)
  1114. push_result_node(&parser, MP_PARSE_NODE_NULL);
  1115. i += 1;
  1116. }
  1117. push_result_rule(&parser, rule_src_line, rule_id, i);
  1118. }
  1119. break;
  1120. }
  1121. default: {
  1122. assert((rule_act & RULE_ACT_KIND_MASK) == RULE_ACT_LIST);
  1123. // n=2 is: item item*
  1124. // n=1 is: item (sep item)*
  1125. // n=3 is: item (sep item)* [sep]
  1126. bool had_trailing_sep;
  1127. if (backtrack) {
  1128. list_backtrack:
  1129. had_trailing_sep = false;
  1130. if (n == 2) {
  1131. if (i == 1) {
  1132. // fail on item, first time round; propagate backtrack
  1133. goto next_rule;
  1134. } else {
  1135. // fail on item, in later rounds; finish with this rule
  1136. backtrack = false;
  1137. }
  1138. } else {
  1139. if (i == 1) {
  1140. // fail on item, first time round; propagate backtrack
  1141. goto next_rule;
  1142. } else if ((i & 1) == 1) {
  1143. // fail on item, in later rounds; have eaten tokens so can't backtrack
  1144. if (n == 3) {
  1145. // list allows trailing separator; finish parsing list
  1146. had_trailing_sep = true;
  1147. backtrack = false;
  1148. } else {
  1149. // list doesn't allowing trailing separator; fail
  1150. goto syntax_error;
  1151. }
  1152. } else {
  1153. // fail on separator; finish parsing list
  1154. backtrack = false;
  1155. }
  1156. }
  1157. } else {
  1158. for (;;) {
  1159. size_t arg = rule_arg[i & 1 & n];
  1160. if ((arg & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  1161. if (lex->tok_kind == (arg & RULE_ARG_ARG_MASK)) {
  1162. if (i & 1 & n) {
  1163. // separators which are tokens are not pushed to result stack
  1164. } else {
  1165. push_result_token(&parser, rule_id);
  1166. }
  1167. mp_lexer_to_next(lex);
  1168. // got element of list, so continue parsing list
  1169. i += 1;
  1170. } else {
  1171. // couldn't get element of list
  1172. i += 1;
  1173. backtrack = true;
  1174. goto list_backtrack;
  1175. }
  1176. } else {
  1177. assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE);
  1178. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this list-rule
  1179. push_rule_from_arg(&parser, arg); // push child of list-rule
  1180. goto next_rule;
  1181. }
  1182. }
  1183. }
  1184. assert(i >= 1);
  1185. // compute number of elements in list, result in i
  1186. i -= 1;
  1187. if ((n & 1) && (rule_arg[1] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  1188. // don't count separators when they are tokens
  1189. i = (i + 1) / 2;
  1190. }
  1191. if (i == 1) {
  1192. // list matched single item
  1193. if (had_trailing_sep) {
  1194. // if there was a trailing separator, make a list of a single item
  1195. push_result_rule(&parser, rule_src_line, rule_id, i);
  1196. } else {
  1197. // just leave single item on stack (ie don't wrap in a list)
  1198. }
  1199. } else {
  1200. push_result_rule(&parser, rule_src_line, rule_id, i);
  1201. }
  1202. break;
  1203. }
  1204. }
  1205. }
  1206. #if MICROPY_COMP_CONST
  1207. mp_map_deinit(&parser.consts);
  1208. #endif
  1209. // truncate final chunk and link into chain of chunks
  1210. if (parser.cur_chunk != NULL) {
  1211. (void)m_renew_maybe(byte, parser.cur_chunk,
  1212. sizeof(mp_parse_chunk_t) + parser.cur_chunk->alloc,
  1213. sizeof(mp_parse_chunk_t) + parser.cur_chunk->union_.used,
  1214. false);
  1215. parser.cur_chunk->alloc = parser.cur_chunk->union_.used;
  1216. parser.cur_chunk->union_.next = parser.tree.chunk;
  1217. parser.tree.chunk = parser.cur_chunk;
  1218. }
  1219. if (
  1220. lex->tok_kind != MP_TOKEN_END // check we are at the end of the token stream
  1221. || parser.result_stack_top == 0 // check that we got a node (can fail on empty input)
  1222. ) {
  1223. syntax_error:;
  1224. mp_obj_t exc;
  1225. if (lex->tok_kind == MP_TOKEN_INDENT) {
  1226. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  1227. MP_ERROR_TEXT("unexpected indent"));
  1228. } else if (lex->tok_kind == MP_TOKEN_DEDENT_MISMATCH) {
  1229. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  1230. MP_ERROR_TEXT("unindent doesn't match any outer indent level"));
  1231. #if MICROPY_PY_FSTRINGS
  1232. } else if (lex->tok_kind == MP_TOKEN_MALFORMED_FSTRING) {
  1233. exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  1234. MP_ERROR_TEXT("malformed f-string"));
  1235. } else if (lex->tok_kind == MP_TOKEN_FSTRING_RAW) {
  1236. exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  1237. MP_ERROR_TEXT("raw f-strings are not supported"));
  1238. #endif
  1239. } else {
  1240. exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  1241. MP_ERROR_TEXT("invalid syntax"));
  1242. }
  1243. // add traceback to give info about file name and location
  1244. // we don't have a 'block' name, so just pass the NULL qstr to indicate this
  1245. mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTRnull);
  1246. nlr_raise(exc);
  1247. }
  1248. // get the root parse node that we created
  1249. assert(parser.result_stack_top == 1);
  1250. parser.tree.root = parser.result_stack[0];
  1251. // free the memory that we don't need anymore
  1252. m_del(rule_stack_t, parser.rule_stack, parser.rule_stack_alloc);
  1253. m_del(mp_parse_node_t, parser.result_stack, parser.result_stack_alloc);
  1254. // Deregister exception handler and free the lexer.
  1255. nlr_pop_jump_callback(true);
  1256. return parser.tree;
  1257. }
  1258. void mp_parse_tree_clear(mp_parse_tree_t *tree) {
  1259. mp_parse_chunk_t *chunk = tree->chunk;
  1260. while (chunk != NULL) {
  1261. mp_parse_chunk_t *next = chunk->union_.next;
  1262. m_del(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc);
  1263. chunk = next;
  1264. }
  1265. tree->chunk = NULL; // Avoid dangling pointer that may live on stack
  1266. }
  1267. #endif // MICROPY_ENABLE_COMPILER