parse.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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 const uint16_t *get_rule_arg(uint8_t r_id) {
  214. size_t off = rule_arg_offset_table[r_id];
  215. if (r_id >= FIRST_RULE_WITH_OFFSET_ABOVE_255) {
  216. off |= 0x100;
  217. }
  218. return &rule_arg_combined_table[off];
  219. }
  220. STATIC void *parser_alloc(parser_t *parser, size_t num_bytes) {
  221. // use a custom memory allocator to store parse nodes sequentially in large chunks
  222. mp_parse_chunk_t *chunk = parser->cur_chunk;
  223. if (chunk != NULL && chunk->union_.used + num_bytes > chunk->alloc) {
  224. // not enough room at end of previously allocated chunk so try to grow
  225. mp_parse_chunk_t *new_data = (mp_parse_chunk_t *)m_renew_maybe(byte, chunk,
  226. sizeof(mp_parse_chunk_t) + chunk->alloc,
  227. sizeof(mp_parse_chunk_t) + chunk->alloc + num_bytes, false);
  228. if (new_data == NULL) {
  229. // could not grow existing memory; shrink it to fit previous
  230. (void)m_renew_maybe(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc,
  231. sizeof(mp_parse_chunk_t) + chunk->union_.used, false);
  232. chunk->alloc = chunk->union_.used;
  233. chunk->union_.next = parser->tree.chunk;
  234. parser->tree.chunk = chunk;
  235. chunk = NULL;
  236. } else {
  237. // could grow existing memory
  238. chunk->alloc += num_bytes;
  239. }
  240. }
  241. if (chunk == NULL) {
  242. // no previous chunk, allocate a new chunk
  243. size_t alloc = MICROPY_ALLOC_PARSE_CHUNK_INIT;
  244. if (alloc < num_bytes) {
  245. alloc = num_bytes;
  246. }
  247. chunk = (mp_parse_chunk_t *)m_new(byte, sizeof(mp_parse_chunk_t) + alloc);
  248. chunk->alloc = alloc;
  249. chunk->union_.used = 0;
  250. parser->cur_chunk = chunk;
  251. }
  252. byte *ret = chunk->data + chunk->union_.used;
  253. chunk->union_.used += num_bytes;
  254. return ret;
  255. }
  256. STATIC void push_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t arg_i) {
  257. if (parser->rule_stack_top >= parser->rule_stack_alloc) {
  258. 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);
  259. parser->rule_stack = rs;
  260. parser->rule_stack_alloc += MICROPY_ALLOC_PARSE_RULE_INC;
  261. }
  262. rule_stack_t *rs = &parser->rule_stack[parser->rule_stack_top++];
  263. rs->src_line = src_line;
  264. rs->rule_id = rule_id;
  265. rs->arg_i = arg_i;
  266. }
  267. STATIC void push_rule_from_arg(parser_t *parser, size_t arg) {
  268. assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE || (arg & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE);
  269. size_t rule_id = arg & RULE_ARG_ARG_MASK;
  270. push_rule(parser, parser->lexer->tok_line, rule_id, 0);
  271. }
  272. STATIC uint8_t pop_rule(parser_t *parser, size_t *arg_i, size_t *src_line) {
  273. parser->rule_stack_top -= 1;
  274. uint8_t rule_id = parser->rule_stack[parser->rule_stack_top].rule_id;
  275. *arg_i = parser->rule_stack[parser->rule_stack_top].arg_i;
  276. *src_line = parser->rule_stack[parser->rule_stack_top].src_line;
  277. return rule_id;
  278. }
  279. bool mp_parse_node_is_const_false(mp_parse_node_t pn) {
  280. return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_FALSE)
  281. || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0);
  282. }
  283. bool mp_parse_node_is_const_true(mp_parse_node_t pn) {
  284. return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_TRUE)
  285. || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) != 0);
  286. }
  287. bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) {
  288. if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  289. *o = MP_OBJ_NEW_SMALL_INT(MP_PARSE_NODE_LEAF_SMALL_INT(pn));
  290. return true;
  291. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_const_object)) {
  292. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  293. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  294. // nodes are 32-bit pointers, but need to extract 64-bit object
  295. *o = (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32);
  296. #else
  297. *o = (mp_obj_t)pns->nodes[0];
  298. #endif
  299. return mp_obj_is_int(*o);
  300. } else {
  301. return false;
  302. }
  303. }
  304. size_t mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_node_t **nodes) {
  305. if (MP_PARSE_NODE_IS_NULL(*pn)) {
  306. *nodes = NULL;
  307. return 0;
  308. } else if (MP_PARSE_NODE_IS_LEAF(*pn)) {
  309. *nodes = pn;
  310. return 1;
  311. } else {
  312. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)(*pn);
  313. if (MP_PARSE_NODE_STRUCT_KIND(pns) != pn_kind) {
  314. *nodes = pn;
  315. return 1;
  316. } else {
  317. *nodes = pns->nodes;
  318. return MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  319. }
  320. }
  321. }
  322. #if MICROPY_DEBUG_PRINTERS
  323. void mp_parse_node_print(const mp_print_t *print, mp_parse_node_t pn, size_t indent) {
  324. if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  325. mp_printf(print, "[% 4d] ", (int)((mp_parse_node_struct_t *)pn)->source_line);
  326. } else {
  327. mp_printf(print, " ");
  328. }
  329. for (size_t i = 0; i < indent; i++) {
  330. mp_printf(print, " ");
  331. }
  332. if (MP_PARSE_NODE_IS_NULL(pn)) {
  333. mp_printf(print, "NULL\n");
  334. } else if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  335. mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn);
  336. mp_printf(print, "int(" INT_FMT ")\n", arg);
  337. } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
  338. uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
  339. switch (MP_PARSE_NODE_LEAF_KIND(pn)) {
  340. case MP_PARSE_NODE_ID:
  341. mp_printf(print, "id(%s)\n", qstr_str(arg));
  342. break;
  343. case MP_PARSE_NODE_STRING:
  344. mp_printf(print, "str(%s)\n", qstr_str(arg));
  345. break;
  346. case MP_PARSE_NODE_BYTES:
  347. mp_printf(print, "bytes(%s)\n", qstr_str(arg));
  348. break;
  349. default:
  350. assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN);
  351. mp_printf(print, "tok(%u)\n", (uint)arg);
  352. break;
  353. }
  354. } else {
  355. // node must be a mp_parse_node_struct_t
  356. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
  357. if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_const_object) {
  358. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  359. mp_printf(print, "literal const(%016llx)\n", (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32));
  360. #else
  361. mp_printf(print, "literal const(%p)\n", (mp_obj_t)pns->nodes[0]);
  362. #endif
  363. } else {
  364. size_t n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  365. #if MICROPY_DEBUG_PARSE_RULE_NAME
  366. 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);
  367. #else
  368. mp_printf(print, "rule(%u) (n=%u)\n", (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
  369. #endif
  370. for (size_t i = 0; i < n; i++) {
  371. mp_parse_node_print(print, pns->nodes[i], indent + 2);
  372. }
  373. }
  374. }
  375. }
  376. #endif // MICROPY_DEBUG_PRINTERS
  377. /*
  378. STATIC void result_stack_show(const mp_print_t *print, parser_t *parser) {
  379. mp_printf(print, "result stack, most recent first\n");
  380. for (ssize_t i = parser->result_stack_top - 1; i >= 0; i--) {
  381. mp_parse_node_print(print, parser->result_stack[i], 0);
  382. }
  383. }
  384. */
  385. STATIC mp_parse_node_t pop_result(parser_t *parser) {
  386. assert(parser->result_stack_top > 0);
  387. return parser->result_stack[--parser->result_stack_top];
  388. }
  389. STATIC mp_parse_node_t peek_result(parser_t *parser, size_t pos) {
  390. assert(parser->result_stack_top > pos);
  391. return parser->result_stack[parser->result_stack_top - 1 - pos];
  392. }
  393. STATIC void push_result_node(parser_t *parser, mp_parse_node_t pn) {
  394. if (parser->result_stack_top >= parser->result_stack_alloc) {
  395. 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);
  396. parser->result_stack = stack;
  397. parser->result_stack_alloc += MICROPY_ALLOC_PARSE_RESULT_INC;
  398. }
  399. parser->result_stack[parser->result_stack_top++] = pn;
  400. }
  401. STATIC mp_parse_node_t make_node_const_object(parser_t *parser, size_t src_line, mp_obj_t obj) {
  402. mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_obj_t));
  403. pn->source_line = src_line;
  404. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  405. // nodes are 32-bit pointers, but need to store 64-bit object
  406. pn->kind_num_nodes = RULE_const_object | (2 << 8);
  407. pn->nodes[0] = (uint64_t)obj;
  408. pn->nodes[1] = (uint64_t)obj >> 32;
  409. #else
  410. pn->kind_num_nodes = RULE_const_object | (1 << 8);
  411. pn->nodes[0] = (uintptr_t)obj;
  412. #endif
  413. return (mp_parse_node_t)pn;
  414. }
  415. STATIC mp_parse_node_t mp_parse_node_new_small_int_checked(parser_t *parser, mp_obj_t o_val) {
  416. (void)parser;
  417. mp_int_t val = MP_OBJ_SMALL_INT_VALUE(o_val);
  418. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  419. // A parse node is only 32-bits and the small-int value must fit in 31-bits
  420. if (((val ^ (val << 1)) & 0xffffffff80000000) != 0) {
  421. return make_node_const_object(parser, 0, o_val);
  422. }
  423. #endif
  424. return mp_parse_node_new_small_int(val);
  425. }
  426. STATIC void push_result_token(parser_t *parser, uint8_t rule_id) {
  427. mp_parse_node_t pn;
  428. mp_lexer_t *lex = parser->lexer;
  429. if (lex->tok_kind == MP_TOKEN_NAME) {
  430. qstr id = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
  431. #if MICROPY_COMP_CONST
  432. // if name is a standalone identifier, look it up in the table of dynamic constants
  433. mp_map_elem_t *elem;
  434. if (rule_id == RULE_atom
  435. && (elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP)) != NULL) {
  436. if (mp_obj_is_small_int(elem->value)) {
  437. pn = mp_parse_node_new_small_int_checked(parser, elem->value);
  438. } else {
  439. pn = make_node_const_object(parser, lex->tok_line, elem->value);
  440. }
  441. } else {
  442. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
  443. }
  444. #else
  445. (void)rule_id;
  446. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
  447. #endif
  448. } else if (lex->tok_kind == MP_TOKEN_INTEGER) {
  449. mp_obj_t o = mp_parse_num_integer(lex->vstr.buf, lex->vstr.len, 0, lex);
  450. if (mp_obj_is_small_int(o)) {
  451. pn = mp_parse_node_new_small_int_checked(parser, o);
  452. } else {
  453. pn = make_node_const_object(parser, lex->tok_line, o);
  454. }
  455. } else if (lex->tok_kind == MP_TOKEN_FLOAT_OR_IMAG) {
  456. mp_obj_t o = mp_parse_num_decimal(lex->vstr.buf, lex->vstr.len, true, false, lex);
  457. pn = make_node_const_object(parser, lex->tok_line, o);
  458. } else if (lex->tok_kind == MP_TOKEN_STRING || lex->tok_kind == MP_TOKEN_BYTES) {
  459. // Don't automatically intern all strings/bytes. doc strings (which are usually large)
  460. // will be discarded by the compiler, and so we shouldn't intern them.
  461. qstr qst = MP_QSTRnull;
  462. if (lex->vstr.len <= MICROPY_ALLOC_PARSE_INTERN_STRING_LEN) {
  463. // intern short strings
  464. qst = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
  465. } else {
  466. // check if this string is already interned
  467. qst = qstr_find_strn(lex->vstr.buf, lex->vstr.len);
  468. }
  469. if (qst != MP_QSTRnull) {
  470. // qstr exists, make a leaf node
  471. pn = mp_parse_node_new_leaf(lex->tok_kind == MP_TOKEN_STRING ? MP_PARSE_NODE_STRING : MP_PARSE_NODE_BYTES, qst);
  472. } else {
  473. // not interned, make a node holding a pointer to the string/bytes object
  474. mp_obj_t o = mp_obj_new_str_copy(
  475. lex->tok_kind == MP_TOKEN_STRING ? &mp_type_str : &mp_type_bytes,
  476. (const byte *)lex->vstr.buf, lex->vstr.len);
  477. pn = make_node_const_object(parser, lex->tok_line, o);
  478. }
  479. } else {
  480. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, lex->tok_kind);
  481. }
  482. push_result_node(parser, pn);
  483. }
  484. #if MICROPY_COMP_MODULE_CONST
  485. STATIC const mp_rom_map_elem_t mp_constants_table[] = {
  486. #if MICROPY_PY_UERRNO
  487. { MP_ROM_QSTR(MP_QSTR_errno), MP_ROM_PTR(&mp_module_uerrno) },
  488. #endif
  489. #if MICROPY_PY_UCTYPES
  490. { MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) },
  491. #endif
  492. // Extra constants as defined by a port
  493. MICROPY_PORT_CONSTANTS
  494. };
  495. STATIC MP_DEFINE_CONST_MAP(mp_constants_map, mp_constants_table);
  496. #endif
  497. STATIC void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args);
  498. #if MICROPY_COMP_CONST_FOLDING
  499. STATIC bool fold_logical_constants(parser_t *parser, uint8_t rule_id, size_t *num_args) {
  500. if (rule_id == RULE_or_test
  501. || rule_id == RULE_and_test) {
  502. // folding for binary logical ops: or and
  503. size_t copy_to = *num_args;
  504. for (size_t i = copy_to; i > 0;) {
  505. mp_parse_node_t pn = peek_result(parser, --i);
  506. parser->result_stack[parser->result_stack_top - copy_to] = pn;
  507. if (i == 0) {
  508. // always need to keep the last value
  509. break;
  510. }
  511. if (rule_id == RULE_or_test) {
  512. if (mp_parse_node_is_const_true(pn)) {
  513. //
  514. break;
  515. } else if (!mp_parse_node_is_const_false(pn)) {
  516. copy_to -= 1;
  517. }
  518. } else {
  519. // RULE_and_test
  520. if (mp_parse_node_is_const_false(pn)) {
  521. break;
  522. } else if (!mp_parse_node_is_const_true(pn)) {
  523. copy_to -= 1;
  524. }
  525. }
  526. }
  527. copy_to -= 1; // copy_to now contains number of args to pop
  528. // pop and discard all the short-circuited expressions
  529. for (size_t i = 0; i < copy_to; ++i) {
  530. pop_result(parser);
  531. }
  532. *num_args -= copy_to;
  533. // we did a complete folding if there's only 1 arg left
  534. return *num_args == 1;
  535. } else if (rule_id == RULE_not_test_2) {
  536. // folding for unary logical op: not
  537. mp_parse_node_t pn = peek_result(parser, 0);
  538. if (mp_parse_node_is_const_false(pn)) {
  539. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_TRUE);
  540. } else if (mp_parse_node_is_const_true(pn)) {
  541. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_FALSE);
  542. } else {
  543. return false;
  544. }
  545. pop_result(parser);
  546. push_result_node(parser, pn);
  547. return true;
  548. }
  549. return false;
  550. }
  551. STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) {
  552. // this code does folding of arbitrary integer expressions, eg 1 + 2 * 3 + 4
  553. // it does not do partial folding, eg 1 + 2 + x -> 3 + x
  554. mp_obj_t arg0;
  555. if (rule_id == RULE_expr
  556. || rule_id == RULE_xor_expr
  557. || rule_id == RULE_and_expr
  558. || rule_id == RULE_power) {
  559. // folding for binary ops: | ^ & **
  560. mp_parse_node_t pn = peek_result(parser, num_args - 1);
  561. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  562. return false;
  563. }
  564. mp_binary_op_t op;
  565. if (rule_id == RULE_expr) {
  566. op = MP_BINARY_OP_OR;
  567. } else if (rule_id == RULE_xor_expr) {
  568. op = MP_BINARY_OP_XOR;
  569. } else if (rule_id == RULE_and_expr) {
  570. op = MP_BINARY_OP_AND;
  571. } else {
  572. op = MP_BINARY_OP_POWER;
  573. }
  574. for (ssize_t i = num_args - 2; i >= 0; --i) {
  575. pn = peek_result(parser, i);
  576. mp_obj_t arg1;
  577. if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
  578. return false;
  579. }
  580. if (op == MP_BINARY_OP_POWER && mp_obj_int_sign(arg1) < 0) {
  581. // ** can't have negative rhs
  582. return false;
  583. }
  584. arg0 = mp_binary_op(op, arg0, arg1);
  585. }
  586. } else if (rule_id == RULE_shift_expr
  587. || rule_id == RULE_arith_expr
  588. || rule_id == RULE_term) {
  589. // folding for binary ops: << >> + - * @ / % //
  590. mp_parse_node_t pn = peek_result(parser, num_args - 1);
  591. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  592. return false;
  593. }
  594. for (ssize_t i = num_args - 2; i >= 1; i -= 2) {
  595. pn = peek_result(parser, i - 1);
  596. mp_obj_t arg1;
  597. if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
  598. return false;
  599. }
  600. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, i));
  601. if (tok == MP_TOKEN_OP_AT || tok == MP_TOKEN_OP_SLASH) {
  602. // Can't fold @ or /
  603. return false;
  604. }
  605. mp_binary_op_t op = MP_BINARY_OP_LSHIFT + (tok - MP_TOKEN_OP_DBL_LESS);
  606. int rhs_sign = mp_obj_int_sign(arg1);
  607. if (op <= MP_BINARY_OP_RSHIFT) {
  608. // << and >> can't have negative rhs
  609. if (rhs_sign < 0) {
  610. return false;
  611. }
  612. } else if (op >= MP_BINARY_OP_FLOOR_DIVIDE) {
  613. // % and // can't have zero rhs
  614. if (rhs_sign == 0) {
  615. return false;
  616. }
  617. }
  618. arg0 = mp_binary_op(op, arg0, arg1);
  619. }
  620. } else if (rule_id == RULE_factor_2) {
  621. // folding for unary ops: + - ~
  622. mp_parse_node_t pn = peek_result(parser, 0);
  623. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  624. return false;
  625. }
  626. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, 1));
  627. mp_unary_op_t op;
  628. if (tok == MP_TOKEN_OP_TILDE) {
  629. op = MP_UNARY_OP_INVERT;
  630. } else {
  631. assert(tok == MP_TOKEN_OP_PLUS || tok == MP_TOKEN_OP_MINUS); // should be
  632. op = MP_UNARY_OP_POSITIVE + (tok - MP_TOKEN_OP_PLUS);
  633. }
  634. arg0 = mp_unary_op(op, arg0);
  635. #if MICROPY_COMP_CONST
  636. } else if (rule_id == RULE_expr_stmt) {
  637. mp_parse_node_t pn1 = peek_result(parser, 0);
  638. if (!MP_PARSE_NODE_IS_NULL(pn1)
  639. && !(MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_augassign)
  640. || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) {
  641. // this node is of the form <x> = <y>
  642. mp_parse_node_t pn0 = peek_result(parser, 1);
  643. if (MP_PARSE_NODE_IS_ID(pn0)
  644. && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_atom_expr_normal)
  645. && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t *)pn1)->nodes[0])
  646. && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t *)pn1)->nodes[0]) == MP_QSTR_const
  647. && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t *)pn1)->nodes[1], RULE_trailer_paren)
  648. ) {
  649. // code to assign dynamic constants: id = const(value)
  650. // get the id
  651. qstr id = MP_PARSE_NODE_LEAF_ARG(pn0);
  652. // get the value
  653. mp_parse_node_t pn_value = ((mp_parse_node_struct_t *)((mp_parse_node_struct_t *)pn1)->nodes[1])->nodes[0];
  654. mp_obj_t value;
  655. if (!mp_parse_node_get_int_maybe(pn_value, &value)) {
  656. mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  657. MP_ERROR_TEXT("constant must be an integer"));
  658. mp_obj_exception_add_traceback(exc, parser->lexer->source_name,
  659. ((mp_parse_node_struct_t *)pn1)->source_line, MP_QSTRnull);
  660. nlr_raise(exc);
  661. }
  662. // store the value in the table of dynamic constants
  663. mp_map_elem_t *elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
  664. assert(elem->value == MP_OBJ_NULL);
  665. elem->value = value;
  666. // If the constant starts with an underscore then treat it as a private
  667. // variable and don't emit any code to store the value to the id.
  668. if (qstr_str(id)[0] == '_') {
  669. pop_result(parser); // pop const(value)
  670. pop_result(parser); // pop id
  671. push_result_rule(parser, 0, RULE_pass_stmt, 0); // replace with "pass"
  672. return true;
  673. }
  674. // replace const(value) with value
  675. pop_result(parser);
  676. push_result_node(parser, pn_value);
  677. // finished folding this assignment, but we still want it to be part of the tree
  678. return false;
  679. }
  680. }
  681. return false;
  682. #endif
  683. #if MICROPY_COMP_MODULE_CONST
  684. } else if (rule_id == RULE_atom_expr_normal) {
  685. mp_parse_node_t pn0 = peek_result(parser, 1);
  686. mp_parse_node_t pn1 = peek_result(parser, 0);
  687. if (!(MP_PARSE_NODE_IS_ID(pn0)
  688. && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) {
  689. return false;
  690. }
  691. // id1.id2
  692. // look it up in constant table, see if it can be replaced with an integer
  693. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pn1;
  694. assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
  695. qstr q_base = MP_PARSE_NODE_LEAF_ARG(pn0);
  696. qstr q_attr = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]);
  697. mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP);
  698. if (elem == NULL) {
  699. return false;
  700. }
  701. mp_obj_t dest[2];
  702. mp_load_method_maybe(elem->value, q_attr, dest);
  703. if (!(dest[0] != MP_OBJ_NULL && mp_obj_is_int(dest[0]) && dest[1] == MP_OBJ_NULL)) {
  704. return false;
  705. }
  706. arg0 = dest[0];
  707. #endif
  708. } else {
  709. return false;
  710. }
  711. // success folding this rule
  712. for (size_t i = num_args; i > 0; i--) {
  713. pop_result(parser);
  714. }
  715. if (mp_obj_is_small_int(arg0)) {
  716. push_result_node(parser, mp_parse_node_new_small_int_checked(parser, arg0));
  717. } else {
  718. // TODO reuse memory for parse node struct?
  719. push_result_node(parser, make_node_const_object(parser, 0, arg0));
  720. }
  721. return true;
  722. }
  723. #endif
  724. STATIC void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args) {
  725. // optimise away parenthesis around an expression if possible
  726. if (rule_id == RULE_atom_paren) {
  727. // there should be just 1 arg for this rule
  728. mp_parse_node_t pn = peek_result(parser, 0);
  729. if (MP_PARSE_NODE_IS_NULL(pn)) {
  730. // need to keep parenthesis for ()
  731. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_testlist_comp)) {
  732. // need to keep parenthesis for (a, b, ...)
  733. } else {
  734. // parenthesis around a single expression, so it's just the expression
  735. return;
  736. }
  737. }
  738. #if MICROPY_COMP_CONST_FOLDING
  739. if (fold_logical_constants(parser, rule_id, &num_args)) {
  740. // we folded this rule so return straight away
  741. return;
  742. }
  743. if (fold_constants(parser, rule_id, num_args)) {
  744. // we folded this rule so return straight away
  745. return;
  746. }
  747. #endif
  748. mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_parse_node_t) * num_args);
  749. pn->source_line = src_line;
  750. pn->kind_num_nodes = (rule_id & 0xff) | (num_args << 8);
  751. for (size_t i = num_args; i > 0; i--) {
  752. pn->nodes[i - 1] = pop_result(parser);
  753. }
  754. push_result_node(parser, (mp_parse_node_t)pn);
  755. }
  756. mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) {
  757. // initialise parser and allocate memory for its stacks
  758. parser_t parser;
  759. parser.rule_stack_alloc = MICROPY_ALLOC_PARSE_RULE_INIT;
  760. parser.rule_stack_top = 0;
  761. parser.rule_stack = m_new(rule_stack_t, parser.rule_stack_alloc);
  762. parser.result_stack_alloc = MICROPY_ALLOC_PARSE_RESULT_INIT;
  763. parser.result_stack_top = 0;
  764. parser.result_stack = m_new(mp_parse_node_t, parser.result_stack_alloc);
  765. parser.lexer = lex;
  766. parser.tree.chunk = NULL;
  767. parser.cur_chunk = NULL;
  768. #if MICROPY_COMP_CONST
  769. mp_map_init(&parser.consts, 0);
  770. #endif
  771. // work out the top-level rule to use, and push it on the stack
  772. size_t top_level_rule;
  773. switch (input_kind) {
  774. case MP_PARSE_SINGLE_INPUT:
  775. top_level_rule = RULE_single_input;
  776. break;
  777. case MP_PARSE_EVAL_INPUT:
  778. top_level_rule = RULE_eval_input;
  779. break;
  780. default:
  781. top_level_rule = RULE_file_input;
  782. }
  783. push_rule(&parser, lex->tok_line, top_level_rule, 0);
  784. // parse!
  785. bool backtrack = false;
  786. for (;;) {
  787. next_rule:
  788. if (parser.rule_stack_top == 0) {
  789. break;
  790. }
  791. // Pop the next rule to process it
  792. size_t i; // state for the current rule
  793. size_t rule_src_line; // source line for the first token matched by the current rule
  794. uint8_t rule_id = pop_rule(&parser, &i, &rule_src_line);
  795. uint8_t rule_act = rule_act_table[rule_id];
  796. const uint16_t *rule_arg = get_rule_arg(rule_id);
  797. size_t n = rule_act & RULE_ACT_ARG_MASK;
  798. #if 0
  799. // debugging
  800. printf("depth=" UINT_FMT " ", parser.rule_stack_top);
  801. for (int j = 0; j < parser.rule_stack_top; ++j) {
  802. printf(" ");
  803. }
  804. printf("%s n=" UINT_FMT " i=" UINT_FMT " bt=%d\n", rule_name_table[rule_id], n, i, backtrack);
  805. #endif
  806. switch (rule_act & RULE_ACT_KIND_MASK) {
  807. case RULE_ACT_OR:
  808. if (i > 0 && !backtrack) {
  809. goto next_rule;
  810. } else {
  811. backtrack = false;
  812. }
  813. for (; i < n; ++i) {
  814. uint16_t kind = rule_arg[i] & RULE_ARG_KIND_MASK;
  815. if (kind == RULE_ARG_TOK) {
  816. if (lex->tok_kind == (rule_arg[i] & RULE_ARG_ARG_MASK)) {
  817. push_result_token(&parser, rule_id);
  818. mp_lexer_to_next(lex);
  819. goto next_rule;
  820. }
  821. } else {
  822. assert(kind == RULE_ARG_RULE);
  823. if (i + 1 < n) {
  824. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this or-rule
  825. }
  826. push_rule_from_arg(&parser, rule_arg[i]); // push child of or-rule
  827. goto next_rule;
  828. }
  829. }
  830. backtrack = true;
  831. break;
  832. case RULE_ACT_AND: {
  833. // failed, backtrack if we can, else syntax error
  834. if (backtrack) {
  835. assert(i > 0);
  836. if ((rule_arg[i - 1] & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE) {
  837. // an optional rule that failed, so continue with next arg
  838. push_result_node(&parser, MP_PARSE_NODE_NULL);
  839. backtrack = false;
  840. } else {
  841. // a mandatory rule that failed, so propagate backtrack
  842. if (i > 1) {
  843. // already eaten tokens so can't backtrack
  844. goto syntax_error;
  845. } else {
  846. goto next_rule;
  847. }
  848. }
  849. }
  850. // progress through the rule
  851. for (; i < n; ++i) {
  852. if ((rule_arg[i] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  853. // need to match a token
  854. mp_token_kind_t tok_kind = rule_arg[i] & RULE_ARG_ARG_MASK;
  855. if (lex->tok_kind == tok_kind) {
  856. // matched token
  857. if (tok_kind == MP_TOKEN_NAME) {
  858. push_result_token(&parser, rule_id);
  859. }
  860. mp_lexer_to_next(lex);
  861. } else {
  862. // failed to match token
  863. if (i > 0) {
  864. // already eaten tokens so can't backtrack
  865. goto syntax_error;
  866. } else {
  867. // this rule failed, so backtrack
  868. backtrack = true;
  869. goto next_rule;
  870. }
  871. }
  872. } else {
  873. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this and-rule
  874. push_rule_from_arg(&parser, rule_arg[i]); // push child of and-rule
  875. goto next_rule;
  876. }
  877. }
  878. assert(i == n);
  879. // matched the rule, so now build the corresponding parse_node
  880. #if !MICROPY_ENABLE_DOC_STRING
  881. // this code discards lonely statements, such as doc strings
  882. if (input_kind != MP_PARSE_SINGLE_INPUT && rule_id == RULE_expr_stmt && peek_result(&parser, 0) == MP_PARSE_NODE_NULL) {
  883. mp_parse_node_t p = peek_result(&parser, 1);
  884. if ((MP_PARSE_NODE_IS_LEAF(p) && !MP_PARSE_NODE_IS_ID(p))
  885. || MP_PARSE_NODE_IS_STRUCT_KIND(p, RULE_const_object)) {
  886. pop_result(&parser); // MP_PARSE_NODE_NULL
  887. pop_result(&parser); // const expression (leaf or RULE_const_object)
  888. // Pushing the "pass" rule here will overwrite any RULE_const_object
  889. // entry that was on the result stack, allowing the GC to reclaim
  890. // the memory from the const object when needed.
  891. push_result_rule(&parser, rule_src_line, RULE_pass_stmt, 0);
  892. break;
  893. }
  894. }
  895. #endif
  896. // count number of arguments for the parse node
  897. i = 0;
  898. size_t num_not_nil = 0;
  899. for (size_t x = n; x > 0;) {
  900. --x;
  901. if ((rule_arg[x] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  902. mp_token_kind_t tok_kind = rule_arg[x] & RULE_ARG_ARG_MASK;
  903. if (tok_kind == MP_TOKEN_NAME) {
  904. // only tokens which were names are pushed to stack
  905. i += 1;
  906. num_not_nil += 1;
  907. }
  908. } else {
  909. // rules are always pushed
  910. if (peek_result(&parser, i) != MP_PARSE_NODE_NULL) {
  911. num_not_nil += 1;
  912. }
  913. i += 1;
  914. }
  915. }
  916. if (num_not_nil == 1 && (rule_act & RULE_ACT_ALLOW_IDENT)) {
  917. // this rule has only 1 argument and should not be emitted
  918. mp_parse_node_t pn = MP_PARSE_NODE_NULL;
  919. for (size_t x = 0; x < i; ++x) {
  920. mp_parse_node_t pn2 = pop_result(&parser);
  921. if (pn2 != MP_PARSE_NODE_NULL) {
  922. pn = pn2;
  923. }
  924. }
  925. push_result_node(&parser, pn);
  926. } else {
  927. // this rule must be emitted
  928. if (rule_act & RULE_ACT_ADD_BLANK) {
  929. // and add an extra blank node at the end (used by the compiler to store data)
  930. push_result_node(&parser, MP_PARSE_NODE_NULL);
  931. i += 1;
  932. }
  933. push_result_rule(&parser, rule_src_line, rule_id, i);
  934. }
  935. break;
  936. }
  937. default: {
  938. assert((rule_act & RULE_ACT_KIND_MASK) == RULE_ACT_LIST);
  939. // n=2 is: item item*
  940. // n=1 is: item (sep item)*
  941. // n=3 is: item (sep item)* [sep]
  942. bool had_trailing_sep;
  943. if (backtrack) {
  944. list_backtrack:
  945. had_trailing_sep = false;
  946. if (n == 2) {
  947. if (i == 1) {
  948. // fail on item, first time round; propagate backtrack
  949. goto next_rule;
  950. } else {
  951. // fail on item, in later rounds; finish with this rule
  952. backtrack = false;
  953. }
  954. } else {
  955. if (i == 1) {
  956. // fail on item, first time round; propagate backtrack
  957. goto next_rule;
  958. } else if ((i & 1) == 1) {
  959. // fail on item, in later rounds; have eaten tokens so can't backtrack
  960. if (n == 3) {
  961. // list allows trailing separator; finish parsing list
  962. had_trailing_sep = true;
  963. backtrack = false;
  964. } else {
  965. // list doesn't allowing trailing separator; fail
  966. goto syntax_error;
  967. }
  968. } else {
  969. // fail on separator; finish parsing list
  970. backtrack = false;
  971. }
  972. }
  973. } else {
  974. for (;;) {
  975. size_t arg = rule_arg[i & 1 & n];
  976. if ((arg & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  977. if (lex->tok_kind == (arg & RULE_ARG_ARG_MASK)) {
  978. if (i & 1 & n) {
  979. // separators which are tokens are not pushed to result stack
  980. } else {
  981. push_result_token(&parser, rule_id);
  982. }
  983. mp_lexer_to_next(lex);
  984. // got element of list, so continue parsing list
  985. i += 1;
  986. } else {
  987. // couldn't get element of list
  988. i += 1;
  989. backtrack = true;
  990. goto list_backtrack;
  991. }
  992. } else {
  993. assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE);
  994. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this list-rule
  995. push_rule_from_arg(&parser, arg); // push child of list-rule
  996. goto next_rule;
  997. }
  998. }
  999. }
  1000. assert(i >= 1);
  1001. // compute number of elements in list, result in i
  1002. i -= 1;
  1003. if ((n & 1) && (rule_arg[1] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  1004. // don't count separators when they are tokens
  1005. i = (i + 1) / 2;
  1006. }
  1007. if (i == 1) {
  1008. // list matched single item
  1009. if (had_trailing_sep) {
  1010. // if there was a trailing separator, make a list of a single item
  1011. push_result_rule(&parser, rule_src_line, rule_id, i);
  1012. } else {
  1013. // just leave single item on stack (ie don't wrap in a list)
  1014. }
  1015. } else {
  1016. push_result_rule(&parser, rule_src_line, rule_id, i);
  1017. }
  1018. break;
  1019. }
  1020. }
  1021. }
  1022. #if MICROPY_COMP_CONST
  1023. mp_map_deinit(&parser.consts);
  1024. #endif
  1025. // truncate final chunk and link into chain of chunks
  1026. if (parser.cur_chunk != NULL) {
  1027. (void)m_renew_maybe(byte, parser.cur_chunk,
  1028. sizeof(mp_parse_chunk_t) + parser.cur_chunk->alloc,
  1029. sizeof(mp_parse_chunk_t) + parser.cur_chunk->union_.used,
  1030. false);
  1031. parser.cur_chunk->alloc = parser.cur_chunk->union_.used;
  1032. parser.cur_chunk->union_.next = parser.tree.chunk;
  1033. parser.tree.chunk = parser.cur_chunk;
  1034. }
  1035. if (
  1036. lex->tok_kind != MP_TOKEN_END // check we are at the end of the token stream
  1037. || parser.result_stack_top == 0 // check that we got a node (can fail on empty input)
  1038. ) {
  1039. syntax_error:;
  1040. mp_obj_t exc;
  1041. if (lex->tok_kind == MP_TOKEN_INDENT) {
  1042. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  1043. MP_ERROR_TEXT("unexpected indent"));
  1044. } else if (lex->tok_kind == MP_TOKEN_DEDENT_MISMATCH) {
  1045. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  1046. MP_ERROR_TEXT("unindent doesn't match any outer indent level"));
  1047. } else {
  1048. exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  1049. MP_ERROR_TEXT("invalid syntax"));
  1050. }
  1051. // add traceback to give info about file name and location
  1052. // we don't have a 'block' name, so just pass the NULL qstr to indicate this
  1053. mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTRnull);
  1054. nlr_raise(exc);
  1055. }
  1056. // get the root parse node that we created
  1057. assert(parser.result_stack_top == 1);
  1058. parser.tree.root = parser.result_stack[0];
  1059. // free the memory that we don't need anymore
  1060. m_del(rule_stack_t, parser.rule_stack, parser.rule_stack_alloc);
  1061. m_del(mp_parse_node_t, parser.result_stack, parser.result_stack_alloc);
  1062. // we also free the lexer on behalf of the caller
  1063. mp_lexer_free(lex);
  1064. return parser.tree;
  1065. }
  1066. void mp_parse_tree_clear(mp_parse_tree_t *tree) {
  1067. mp_parse_chunk_t *chunk = tree->chunk;
  1068. while (chunk != NULL) {
  1069. mp_parse_chunk_t *next = chunk->union_.next;
  1070. m_del(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc);
  1071. chunk = next;
  1072. }
  1073. }
  1074. #endif // MICROPY_ENABLE_COMPILER