parse.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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. // (un)comment to use rule names; for debugging
  53. //#define USE_RULE_NAME (1)
  54. enum {
  55. // define rules with a compile function
  56. #define DEF_RULE(rule, comp, kind, ...) RULE_##rule,
  57. #define DEF_RULE_NC(rule, kind, ...)
  58. #include "py/grammar.h"
  59. #undef DEF_RULE
  60. #undef DEF_RULE_NC
  61. RULE_const_object, // special node for a constant, generic Python object
  62. // define rules without a compile function
  63. #define DEF_RULE(rule, comp, kind, ...)
  64. #define DEF_RULE_NC(rule, kind, ...) RULE_##rule,
  65. #include "py/grammar.h"
  66. #undef DEF_RULE
  67. #undef DEF_RULE_NC
  68. };
  69. // Define an array of actions corresponding to each rule
  70. STATIC const uint8_t rule_act_table[] = {
  71. #define or(n) (RULE_ACT_OR | n)
  72. #define and(n) (RULE_ACT_AND | n)
  73. #define and_ident(n) (RULE_ACT_AND | n | RULE_ACT_ALLOW_IDENT)
  74. #define and_blank(n) (RULE_ACT_AND | n | RULE_ACT_ADD_BLANK)
  75. #define one_or_more (RULE_ACT_LIST | 2)
  76. #define list (RULE_ACT_LIST | 1)
  77. #define list_with_end (RULE_ACT_LIST | 3)
  78. #define DEF_RULE(rule, comp, kind, ...) kind,
  79. #define DEF_RULE_NC(rule, kind, ...)
  80. #include "py/grammar.h"
  81. #undef DEF_RULE
  82. #undef DEF_RULE_NC
  83. 0, // RULE_const_object
  84. #define DEF_RULE(rule, comp, kind, ...)
  85. #define DEF_RULE_NC(rule, kind, ...) kind,
  86. #include "py/grammar.h"
  87. #undef DEF_RULE
  88. #undef DEF_RULE_NC
  89. #undef or
  90. #undef and
  91. #undef and_ident
  92. #undef and_blank
  93. #undef one_or_more
  94. #undef list
  95. #undef list_with_end
  96. };
  97. // Define the argument data for each rule, as a combined array
  98. STATIC const uint16_t rule_arg_combined_table[] = {
  99. #define tok(t) (RULE_ARG_TOK | MP_TOKEN_##t)
  100. #define rule(r) (RULE_ARG_RULE | RULE_##r)
  101. #define opt_rule(r) (RULE_ARG_OPT_RULE | RULE_##r)
  102. #define DEF_RULE(rule, comp, kind, ...) __VA_ARGS__,
  103. #define DEF_RULE_NC(rule, kind, ...)
  104. #include "py/grammar.h"
  105. #undef DEF_RULE
  106. #undef DEF_RULE_NC
  107. #define DEF_RULE(rule, comp, kind, ...)
  108. #define DEF_RULE_NC(rule, kind, ...) __VA_ARGS__,
  109. #include "py/grammar.h"
  110. #undef DEF_RULE
  111. #undef DEF_RULE_NC
  112. #undef tok
  113. #undef rule
  114. #undef opt_rule
  115. };
  116. // Macro to create a list of N identifiers where N is the number of variable arguments to the macro
  117. #define RULE_EXPAND(x) x
  118. #define RULE_PADDING(rule, ...) RULE_PADDING2(rule, __VA_ARGS__, RULE_PADDING_IDS(rule))
  119. #define RULE_PADDING2(rule, ...) RULE_EXPAND(RULE_PADDING3(rule, __VA_ARGS__))
  120. #define RULE_PADDING3(rule, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, ...) __VA_ARGS__
  121. #define RULE_PADDING_IDS(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,
  122. // Use an enum to create constants specifying how much room a rule takes in rule_arg_combined_table
  123. enum {
  124. #define DEF_RULE(rule, comp, kind, ...) RULE_PADDING(rule, __VA_ARGS__)
  125. #define DEF_RULE_NC(rule, kind, ...)
  126. #include "py/grammar.h"
  127. #undef DEF_RULE
  128. #undef DEF_RULE_NC
  129. #define DEF_RULE(rule, comp, kind, ...)
  130. #define DEF_RULE_NC(rule, kind, ...) RULE_PADDING(rule, __VA_ARGS__)
  131. #include "py/grammar.h"
  132. #undef DEF_RULE
  133. #undef DEF_RULE_NC
  134. };
  135. // Macro to compute the start of a rule in rule_arg_combined_table
  136. #define RULE_ARG_OFFSET(rule, ...) RULE_ARG_OFFSET2(rule, __VA_ARGS__, RULE_ARG_OFFSET_IDS(rule))
  137. #define RULE_ARG_OFFSET2(rule, ...) RULE_EXPAND(RULE_ARG_OFFSET3(rule, __VA_ARGS__))
  138. #define RULE_ARG_OFFSET3(rule, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, ...) _13
  139. #define RULE_ARG_OFFSET_IDS(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,
  140. // Use the above enum values to create a table of offsets for each rule's arg
  141. // data, which indexes rule_arg_combined_table. The offsets require 9 bits of
  142. // storage but only the lower 8 bits are stored here. The 9th bit is computed
  143. // in get_rule_arg using the FIRST_RULE_WITH_OFFSET_ABOVE_255 constant.
  144. STATIC const uint8_t rule_arg_offset_table[] = {
  145. #define DEF_RULE(rule, comp, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) & 0xff,
  146. #define DEF_RULE_NC(rule, kind, ...)
  147. #include "py/grammar.h"
  148. #undef DEF_RULE
  149. #undef DEF_RULE_NC
  150. 0, // RULE_const_object
  151. #define DEF_RULE(rule, comp, kind, ...)
  152. #define DEF_RULE_NC(rule, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) & 0xff,
  153. #include "py/grammar.h"
  154. #undef DEF_RULE
  155. #undef DEF_RULE_NC
  156. };
  157. // Define a constant that's used to determine the 9th bit of the values in rule_arg_offset_table
  158. static const size_t FIRST_RULE_WITH_OFFSET_ABOVE_255 =
  159. #define DEF_RULE(rule, comp, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) >= 0x100 ? RULE_##rule :
  160. #define DEF_RULE_NC(rule, kind, ...)
  161. #include "py/grammar.h"
  162. #undef DEF_RULE
  163. #undef DEF_RULE_NC
  164. #define DEF_RULE(rule, comp, kind, ...)
  165. #define DEF_RULE_NC(rule, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) >= 0x100 ? RULE_##rule :
  166. #include "py/grammar.h"
  167. #undef DEF_RULE
  168. #undef DEF_RULE_NC
  169. 0;
  170. #if USE_RULE_NAME
  171. // Define an array of rule names corresponding to each rule
  172. STATIC const char *const rule_name_table[] = {
  173. #define DEF_RULE(rule, comp, kind, ...) #rule,
  174. #define DEF_RULE_NC(rule, kind, ...)
  175. #include "py/grammar.h"
  176. #undef DEF_RULE
  177. #undef DEF_RULE_NC
  178. "", // RULE_const_object
  179. #define DEF_RULE(rule, comp, kind, ...)
  180. #define DEF_RULE_NC(rule, kind, ...) #rule,
  181. #include "py/grammar.h"
  182. #undef DEF_RULE
  183. #undef DEF_RULE_NC
  184. };
  185. #endif
  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. int 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(mp_parse_node_t pn, size_t indent) {
  324. if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  325. printf("[% 4d] ", (int)((mp_parse_node_struct_t*)pn)->source_line);
  326. } else {
  327. printf(" ");
  328. }
  329. for (size_t i = 0; i < indent; i++) {
  330. printf(" ");
  331. }
  332. if (MP_PARSE_NODE_IS_NULL(pn)) {
  333. printf("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. printf("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: printf("id(%s)\n", qstr_str(arg)); break;
  341. case MP_PARSE_NODE_STRING: printf("str(%s)\n", qstr_str(arg)); break;
  342. case MP_PARSE_NODE_BYTES: printf("bytes(%s)\n", qstr_str(arg)); break;
  343. default:
  344. assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN);
  345. printf("tok(%u)\n", (uint)arg); break;
  346. }
  347. } else {
  348. // node must be a mp_parse_node_struct_t
  349. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  350. if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_const_object) {
  351. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  352. printf("literal const(%016llx)\n", (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32));
  353. #else
  354. printf("literal const(%p)\n", (mp_obj_t)pns->nodes[0]);
  355. #endif
  356. } else {
  357. size_t n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  358. #if USE_RULE_NAME
  359. printf("%s(%u) (n=%u)\n", rule_name_table[MP_PARSE_NODE_STRUCT_KIND(pns)], (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
  360. #else
  361. printf("rule(%u) (n=%u)\n", (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
  362. #endif
  363. for (size_t i = 0; i < n; i++) {
  364. mp_parse_node_print(pns->nodes[i], indent + 2);
  365. }
  366. }
  367. }
  368. }
  369. #endif // MICROPY_DEBUG_PRINTERS
  370. /*
  371. STATIC void result_stack_show(parser_t *parser) {
  372. printf("result stack, most recent first\n");
  373. for (ssize_t i = parser->result_stack_top - 1; i >= 0; i--) {
  374. mp_parse_node_print(parser->result_stack[i], 0);
  375. }
  376. }
  377. */
  378. STATIC mp_parse_node_t pop_result(parser_t *parser) {
  379. assert(parser->result_stack_top > 0);
  380. return parser->result_stack[--parser->result_stack_top];
  381. }
  382. STATIC mp_parse_node_t peek_result(parser_t *parser, size_t pos) {
  383. assert(parser->result_stack_top > pos);
  384. return parser->result_stack[parser->result_stack_top - 1 - pos];
  385. }
  386. STATIC void push_result_node(parser_t *parser, mp_parse_node_t pn) {
  387. if (parser->result_stack_top >= parser->result_stack_alloc) {
  388. 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);
  389. parser->result_stack = stack;
  390. parser->result_stack_alloc += MICROPY_ALLOC_PARSE_RESULT_INC;
  391. }
  392. parser->result_stack[parser->result_stack_top++] = pn;
  393. }
  394. STATIC mp_parse_node_t make_node_const_object(parser_t *parser, size_t src_line, mp_obj_t obj) {
  395. mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_obj_t));
  396. pn->source_line = src_line;
  397. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  398. // nodes are 32-bit pointers, but need to store 64-bit object
  399. pn->kind_num_nodes = RULE_const_object | (2 << 8);
  400. pn->nodes[0] = (uint64_t)obj;
  401. pn->nodes[1] = (uint64_t)obj >> 32;
  402. #else
  403. pn->kind_num_nodes = RULE_const_object | (1 << 8);
  404. pn->nodes[0] = (uintptr_t)obj;
  405. #endif
  406. return (mp_parse_node_t)pn;
  407. }
  408. STATIC mp_parse_node_t mp_parse_node_new_small_int_checked(parser_t *parser, mp_obj_t o_val) {
  409. (void)parser;
  410. mp_int_t val = MP_OBJ_SMALL_INT_VALUE(o_val);
  411. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  412. // A parse node is only 32-bits and the small-int value must fit in 31-bits
  413. if (((val ^ (val << 1)) & 0xffffffff80000000) != 0) {
  414. return make_node_const_object(parser, 0, o_val);
  415. }
  416. #endif
  417. return mp_parse_node_new_small_int(val);
  418. }
  419. STATIC void push_result_token(parser_t *parser, uint8_t rule_id) {
  420. mp_parse_node_t pn;
  421. mp_lexer_t *lex = parser->lexer;
  422. if (lex->tok_kind == MP_TOKEN_NAME) {
  423. qstr id = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
  424. #if MICROPY_COMP_CONST
  425. // if name is a standalone identifier, look it up in the table of dynamic constants
  426. mp_map_elem_t *elem;
  427. if (rule_id == RULE_atom
  428. && (elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP)) != NULL) {
  429. if (MP_OBJ_IS_SMALL_INT(elem->value)) {
  430. pn = mp_parse_node_new_small_int_checked(parser, elem->value);
  431. } else {
  432. pn = make_node_const_object(parser, lex->tok_line, elem->value);
  433. }
  434. } else {
  435. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
  436. }
  437. #else
  438. (void)rule_id;
  439. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
  440. #endif
  441. } else if (lex->tok_kind == MP_TOKEN_INTEGER) {
  442. mp_obj_t o = mp_parse_num_integer(lex->vstr.buf, lex->vstr.len, 0, lex);
  443. if (MP_OBJ_IS_SMALL_INT(o)) {
  444. pn = mp_parse_node_new_small_int_checked(parser, o);
  445. } else {
  446. pn = make_node_const_object(parser, lex->tok_line, o);
  447. }
  448. } else if (lex->tok_kind == MP_TOKEN_FLOAT_OR_IMAG) {
  449. mp_obj_t o = mp_parse_num_decimal(lex->vstr.buf, lex->vstr.len, true, false, lex);
  450. pn = make_node_const_object(parser, lex->tok_line, o);
  451. } else if (lex->tok_kind == MP_TOKEN_STRING || lex->tok_kind == MP_TOKEN_BYTES) {
  452. // Don't automatically intern all strings/bytes. doc strings (which are usually large)
  453. // will be discarded by the compiler, and so we shouldn't intern them.
  454. qstr qst = MP_QSTR_NULL;
  455. if (lex->vstr.len <= MICROPY_ALLOC_PARSE_INTERN_STRING_LEN) {
  456. // intern short strings
  457. qst = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
  458. } else {
  459. // check if this string is already interned
  460. qst = qstr_find_strn(lex->vstr.buf, lex->vstr.len);
  461. }
  462. if (qst != MP_QSTR_NULL) {
  463. // qstr exists, make a leaf node
  464. pn = mp_parse_node_new_leaf(lex->tok_kind == MP_TOKEN_STRING ? MP_PARSE_NODE_STRING : MP_PARSE_NODE_BYTES, qst);
  465. } else {
  466. // not interned, make a node holding a pointer to the string/bytes object
  467. mp_obj_t o = mp_obj_new_str_copy(
  468. lex->tok_kind == MP_TOKEN_STRING ? &mp_type_str : &mp_type_bytes,
  469. (const byte*)lex->vstr.buf, lex->vstr.len);
  470. pn = make_node_const_object(parser, lex->tok_line, o);
  471. }
  472. } else {
  473. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, lex->tok_kind);
  474. }
  475. push_result_node(parser, pn);
  476. }
  477. #if MICROPY_COMP_MODULE_CONST
  478. STATIC const mp_rom_map_elem_t mp_constants_table[] = {
  479. #if MICROPY_PY_UERRNO
  480. { MP_ROM_QSTR(MP_QSTR_errno), MP_ROM_PTR(&mp_module_uerrno) },
  481. #endif
  482. #if MICROPY_PY_UCTYPES
  483. { MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) },
  484. #endif
  485. // Extra constants as defined by a port
  486. MICROPY_PORT_CONSTANTS
  487. };
  488. STATIC MP_DEFINE_CONST_MAP(mp_constants_map, mp_constants_table);
  489. #endif
  490. STATIC void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args);
  491. #if MICROPY_COMP_CONST_FOLDING
  492. STATIC bool fold_logical_constants(parser_t *parser, uint8_t rule_id, size_t *num_args) {
  493. if (rule_id == RULE_or_test
  494. || rule_id == RULE_and_test) {
  495. // folding for binary logical ops: or and
  496. size_t copy_to = *num_args;
  497. for (size_t i = copy_to; i > 0;) {
  498. mp_parse_node_t pn = peek_result(parser, --i);
  499. parser->result_stack[parser->result_stack_top - copy_to] = pn;
  500. if (i == 0) {
  501. // always need to keep the last value
  502. break;
  503. }
  504. if (rule_id == RULE_or_test) {
  505. if (mp_parse_node_is_const_true(pn)) {
  506. //
  507. break;
  508. } else if (!mp_parse_node_is_const_false(pn)) {
  509. copy_to -= 1;
  510. }
  511. } else {
  512. // RULE_and_test
  513. if (mp_parse_node_is_const_false(pn)) {
  514. break;
  515. } else if (!mp_parse_node_is_const_true(pn)) {
  516. copy_to -= 1;
  517. }
  518. }
  519. }
  520. copy_to -= 1; // copy_to now contains number of args to pop
  521. // pop and discard all the short-circuited expressions
  522. for (size_t i = 0; i < copy_to; ++i) {
  523. pop_result(parser);
  524. }
  525. *num_args -= copy_to;
  526. // we did a complete folding if there's only 1 arg left
  527. return *num_args == 1;
  528. } else if (rule_id == RULE_not_test_2) {
  529. // folding for unary logical op: not
  530. mp_parse_node_t pn = peek_result(parser, 0);
  531. if (mp_parse_node_is_const_false(pn)) {
  532. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_TRUE);
  533. } else if (mp_parse_node_is_const_true(pn)) {
  534. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_FALSE);
  535. } else {
  536. return false;
  537. }
  538. pop_result(parser);
  539. push_result_node(parser, pn);
  540. return true;
  541. }
  542. return false;
  543. }
  544. STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) {
  545. // this code does folding of arbitrary integer expressions, eg 1 + 2 * 3 + 4
  546. // it does not do partial folding, eg 1 + 2 + x -> 3 + x
  547. mp_obj_t arg0;
  548. if (rule_id == RULE_expr
  549. || rule_id == RULE_xor_expr
  550. || rule_id == RULE_and_expr) {
  551. // folding for binary ops: | ^ &
  552. mp_parse_node_t pn = peek_result(parser, num_args - 1);
  553. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  554. return false;
  555. }
  556. mp_binary_op_t op;
  557. if (rule_id == RULE_expr) {
  558. op = MP_BINARY_OP_OR;
  559. } else if (rule_id == RULE_xor_expr) {
  560. op = MP_BINARY_OP_XOR;
  561. } else {
  562. op = MP_BINARY_OP_AND;
  563. }
  564. for (ssize_t i = num_args - 2; i >= 0; --i) {
  565. pn = peek_result(parser, i);
  566. mp_obj_t arg1;
  567. if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
  568. return false;
  569. }
  570. arg0 = mp_binary_op(op, arg0, arg1);
  571. }
  572. } else if (rule_id == RULE_shift_expr
  573. || rule_id == RULE_arith_expr
  574. || rule_id == RULE_term) {
  575. // folding for binary ops: << >> + - * / % //
  576. mp_parse_node_t pn = peek_result(parser, num_args - 1);
  577. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  578. return false;
  579. }
  580. for (ssize_t i = num_args - 2; i >= 1; i -= 2) {
  581. pn = peek_result(parser, i - 1);
  582. mp_obj_t arg1;
  583. if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
  584. return false;
  585. }
  586. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, i));
  587. static const uint8_t token_to_op[] = {
  588. MP_BINARY_OP_ADD,
  589. MP_BINARY_OP_SUBTRACT,
  590. MP_BINARY_OP_MULTIPLY,
  591. 255,//MP_BINARY_OP_POWER,
  592. 255,//MP_BINARY_OP_TRUE_DIVIDE,
  593. MP_BINARY_OP_FLOOR_DIVIDE,
  594. MP_BINARY_OP_MODULO,
  595. 255,//MP_BINARY_OP_LESS
  596. MP_BINARY_OP_LSHIFT,
  597. 255,//MP_BINARY_OP_MORE
  598. MP_BINARY_OP_RSHIFT,
  599. };
  600. mp_binary_op_t op = token_to_op[tok - MP_TOKEN_OP_PLUS];
  601. if (op == (mp_binary_op_t)255) {
  602. return false;
  603. }
  604. int rhs_sign = mp_obj_int_sign(arg1);
  605. if (op <= MP_BINARY_OP_RSHIFT) {
  606. // << and >> can't have negative rhs
  607. if (rhs_sign < 0) {
  608. return false;
  609. }
  610. } else if (op >= MP_BINARY_OP_FLOOR_DIVIDE) {
  611. // % and // can't have zero rhs
  612. if (rhs_sign == 0) {
  613. return false;
  614. }
  615. }
  616. arg0 = mp_binary_op(op, arg0, arg1);
  617. }
  618. } else if (rule_id == RULE_factor_2) {
  619. // folding for unary ops: + - ~
  620. mp_parse_node_t pn = peek_result(parser, 0);
  621. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  622. return false;
  623. }
  624. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, 1));
  625. mp_unary_op_t op;
  626. if (tok == MP_TOKEN_OP_PLUS) {
  627. op = MP_UNARY_OP_POSITIVE;
  628. } else if (tok == MP_TOKEN_OP_MINUS) {
  629. op = MP_UNARY_OP_NEGATIVE;
  630. } else {
  631. assert(tok == MP_TOKEN_OP_TILDE); // should be
  632. op = MP_UNARY_OP_INVERT;
  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. "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_QSTR_NULL);
  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: top_level_rule = RULE_single_input; break;
  775. case MP_PARSE_EVAL_INPUT: top_level_rule = RULE_eval_input; break;
  776. default: top_level_rule = RULE_file_input;
  777. }
  778. push_rule(&parser, lex->tok_line, top_level_rule, 0);
  779. // parse!
  780. bool backtrack = false;
  781. for (;;) {
  782. next_rule:
  783. if (parser.rule_stack_top == 0) {
  784. break;
  785. }
  786. // Pop the next rule to process it
  787. size_t i; // state for the current rule
  788. size_t rule_src_line; // source line for the first token matched by the current rule
  789. uint8_t rule_id = pop_rule(&parser, &i, &rule_src_line);
  790. uint8_t rule_act = rule_act_table[rule_id];
  791. const uint16_t *rule_arg = get_rule_arg(rule_id);
  792. size_t n = rule_act & RULE_ACT_ARG_MASK;
  793. #if 0
  794. // debugging
  795. printf("depth=" UINT_FMT " ", parser.rule_stack_top);
  796. for (int j = 0; j < parser.rule_stack_top; ++j) {
  797. printf(" ");
  798. }
  799. printf("%s n=" UINT_FMT " i=" UINT_FMT " bt=%d\n", rule_name_table[rule_id], n, i, backtrack);
  800. #endif
  801. switch (rule_act & RULE_ACT_KIND_MASK) {
  802. case RULE_ACT_OR:
  803. if (i > 0 && !backtrack) {
  804. goto next_rule;
  805. } else {
  806. backtrack = false;
  807. }
  808. for (; i < n; ++i) {
  809. uint16_t kind = rule_arg[i] & RULE_ARG_KIND_MASK;
  810. if (kind == RULE_ARG_TOK) {
  811. if (lex->tok_kind == (rule_arg[i] & RULE_ARG_ARG_MASK)) {
  812. push_result_token(&parser, rule_id);
  813. mp_lexer_to_next(lex);
  814. goto next_rule;
  815. }
  816. } else {
  817. assert(kind == RULE_ARG_RULE);
  818. if (i + 1 < n) {
  819. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this or-rule
  820. }
  821. push_rule_from_arg(&parser, rule_arg[i]); // push child of or-rule
  822. goto next_rule;
  823. }
  824. }
  825. backtrack = true;
  826. break;
  827. case RULE_ACT_AND: {
  828. // failed, backtrack if we can, else syntax error
  829. if (backtrack) {
  830. assert(i > 0);
  831. if ((rule_arg[i - 1] & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE) {
  832. // an optional rule that failed, so continue with next arg
  833. push_result_node(&parser, MP_PARSE_NODE_NULL);
  834. backtrack = false;
  835. } else {
  836. // a mandatory rule that failed, so propagate backtrack
  837. if (i > 1) {
  838. // already eaten tokens so can't backtrack
  839. goto syntax_error;
  840. } else {
  841. goto next_rule;
  842. }
  843. }
  844. }
  845. // progress through the rule
  846. for (; i < n; ++i) {
  847. if ((rule_arg[i] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  848. // need to match a token
  849. mp_token_kind_t tok_kind = rule_arg[i] & RULE_ARG_ARG_MASK;
  850. if (lex->tok_kind == tok_kind) {
  851. // matched token
  852. if (tok_kind == MP_TOKEN_NAME) {
  853. push_result_token(&parser, rule_id);
  854. }
  855. mp_lexer_to_next(lex);
  856. } else {
  857. // failed to match token
  858. if (i > 0) {
  859. // already eaten tokens so can't backtrack
  860. goto syntax_error;
  861. } else {
  862. // this rule failed, so backtrack
  863. backtrack = true;
  864. goto next_rule;
  865. }
  866. }
  867. } else {
  868. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this and-rule
  869. push_rule_from_arg(&parser, rule_arg[i]); // push child of and-rule
  870. goto next_rule;
  871. }
  872. }
  873. assert(i == n);
  874. // matched the rule, so now build the corresponding parse_node
  875. #if !MICROPY_ENABLE_DOC_STRING
  876. // this code discards lonely statements, such as doc strings
  877. if (input_kind != MP_PARSE_SINGLE_INPUT && rule_id == RULE_expr_stmt && peek_result(&parser, 0) == MP_PARSE_NODE_NULL) {
  878. mp_parse_node_t p = peek_result(&parser, 1);
  879. if ((MP_PARSE_NODE_IS_LEAF(p) && !MP_PARSE_NODE_IS_ID(p))
  880. || MP_PARSE_NODE_IS_STRUCT_KIND(p, RULE_const_object)) {
  881. pop_result(&parser); // MP_PARSE_NODE_NULL
  882. pop_result(&parser); // const expression (leaf or RULE_const_object)
  883. // Pushing the "pass" rule here will overwrite any RULE_const_object
  884. // entry that was on the result stack, allowing the GC to reclaim
  885. // the memory from the const object when needed.
  886. push_result_rule(&parser, rule_src_line, RULE_pass_stmt, 0);
  887. break;
  888. }
  889. }
  890. #endif
  891. // count number of arguments for the parse node
  892. i = 0;
  893. size_t num_not_nil = 0;
  894. for (size_t x = n; x > 0;) {
  895. --x;
  896. if ((rule_arg[x] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  897. mp_token_kind_t tok_kind = rule_arg[x] & RULE_ARG_ARG_MASK;
  898. if (tok_kind == MP_TOKEN_NAME) {
  899. // only tokens which were names are pushed to stack
  900. i += 1;
  901. num_not_nil += 1;
  902. }
  903. } else {
  904. // rules are always pushed
  905. if (peek_result(&parser, i) != MP_PARSE_NODE_NULL) {
  906. num_not_nil += 1;
  907. }
  908. i += 1;
  909. }
  910. }
  911. if (num_not_nil == 1 && (rule_act & RULE_ACT_ALLOW_IDENT)) {
  912. // this rule has only 1 argument and should not be emitted
  913. mp_parse_node_t pn = MP_PARSE_NODE_NULL;
  914. for (size_t x = 0; x < i; ++x) {
  915. mp_parse_node_t pn2 = pop_result(&parser);
  916. if (pn2 != MP_PARSE_NODE_NULL) {
  917. pn = pn2;
  918. }
  919. }
  920. push_result_node(&parser, pn);
  921. } else {
  922. // this rule must be emitted
  923. if (rule_act & RULE_ACT_ADD_BLANK) {
  924. // and add an extra blank node at the end (used by the compiler to store data)
  925. push_result_node(&parser, MP_PARSE_NODE_NULL);
  926. i += 1;
  927. }
  928. push_result_rule(&parser, rule_src_line, rule_id, i);
  929. }
  930. break;
  931. }
  932. default: {
  933. assert((rule_act & RULE_ACT_KIND_MASK) == RULE_ACT_LIST);
  934. // n=2 is: item item*
  935. // n=1 is: item (sep item)*
  936. // n=3 is: item (sep item)* [sep]
  937. bool had_trailing_sep;
  938. if (backtrack) {
  939. list_backtrack:
  940. had_trailing_sep = false;
  941. if (n == 2) {
  942. if (i == 1) {
  943. // fail on item, first time round; propagate backtrack
  944. goto next_rule;
  945. } else {
  946. // fail on item, in later rounds; finish with this rule
  947. backtrack = false;
  948. }
  949. } else {
  950. if (i == 1) {
  951. // fail on item, first time round; propagate backtrack
  952. goto next_rule;
  953. } else if ((i & 1) == 1) {
  954. // fail on item, in later rounds; have eaten tokens so can't backtrack
  955. if (n == 3) {
  956. // list allows trailing separator; finish parsing list
  957. had_trailing_sep = true;
  958. backtrack = false;
  959. } else {
  960. // list doesn't allowing trailing separator; fail
  961. goto syntax_error;
  962. }
  963. } else {
  964. // fail on separator; finish parsing list
  965. backtrack = false;
  966. }
  967. }
  968. } else {
  969. for (;;) {
  970. size_t arg = rule_arg[i & 1 & n];
  971. if ((arg & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  972. if (lex->tok_kind == (arg & RULE_ARG_ARG_MASK)) {
  973. if (i & 1 & n) {
  974. // separators which are tokens are not pushed to result stack
  975. } else {
  976. push_result_token(&parser, rule_id);
  977. }
  978. mp_lexer_to_next(lex);
  979. // got element of list, so continue parsing list
  980. i += 1;
  981. } else {
  982. // couldn't get element of list
  983. i += 1;
  984. backtrack = true;
  985. goto list_backtrack;
  986. }
  987. } else {
  988. assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE);
  989. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this list-rule
  990. push_rule_from_arg(&parser, arg); // push child of list-rule
  991. goto next_rule;
  992. }
  993. }
  994. }
  995. assert(i >= 1);
  996. // compute number of elements in list, result in i
  997. i -= 1;
  998. if ((n & 1) && (rule_arg[1] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  999. // don't count separators when they are tokens
  1000. i = (i + 1) / 2;
  1001. }
  1002. if (i == 1) {
  1003. // list matched single item
  1004. if (had_trailing_sep) {
  1005. // if there was a trailing separator, make a list of a single item
  1006. push_result_rule(&parser, rule_src_line, rule_id, i);
  1007. } else {
  1008. // just leave single item on stack (ie don't wrap in a list)
  1009. }
  1010. } else {
  1011. push_result_rule(&parser, rule_src_line, rule_id, i);
  1012. }
  1013. break;
  1014. }
  1015. }
  1016. }
  1017. #if MICROPY_COMP_CONST
  1018. mp_map_deinit(&parser.consts);
  1019. #endif
  1020. // truncate final chunk and link into chain of chunks
  1021. if (parser.cur_chunk != NULL) {
  1022. (void)m_renew_maybe(byte, parser.cur_chunk,
  1023. sizeof(mp_parse_chunk_t) + parser.cur_chunk->alloc,
  1024. sizeof(mp_parse_chunk_t) + parser.cur_chunk->union_.used,
  1025. false);
  1026. parser.cur_chunk->alloc = parser.cur_chunk->union_.used;
  1027. parser.cur_chunk->union_.next = parser.tree.chunk;
  1028. parser.tree.chunk = parser.cur_chunk;
  1029. }
  1030. if (
  1031. lex->tok_kind != MP_TOKEN_END // check we are at the end of the token stream
  1032. || parser.result_stack_top == 0 // check that we got a node (can fail on empty input)
  1033. ) {
  1034. syntax_error:;
  1035. mp_obj_t exc;
  1036. if (lex->tok_kind == MP_TOKEN_INDENT) {
  1037. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  1038. "unexpected indent");
  1039. } else if (lex->tok_kind == MP_TOKEN_DEDENT_MISMATCH) {
  1040. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  1041. "unindent does not match any outer indentation level");
  1042. } else {
  1043. exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  1044. "invalid syntax");
  1045. }
  1046. // add traceback to give info about file name and location
  1047. // we don't have a 'block' name, so just pass the NULL qstr to indicate this
  1048. mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTR_NULL);
  1049. nlr_raise(exc);
  1050. }
  1051. // get the root parse node that we created
  1052. assert(parser.result_stack_top == 1);
  1053. parser.tree.root = parser.result_stack[0];
  1054. // free the memory that we don't need anymore
  1055. m_del(rule_stack_t, parser.rule_stack, parser.rule_stack_alloc);
  1056. m_del(mp_parse_node_t, parser.result_stack, parser.result_stack_alloc);
  1057. // we also free the lexer on behalf of the caller
  1058. mp_lexer_free(lex);
  1059. return parser.tree;
  1060. }
  1061. void mp_parse_tree_clear(mp_parse_tree_t *tree) {
  1062. mp_parse_chunk_t *chunk = tree->chunk;
  1063. while (chunk != NULL) {
  1064. mp_parse_chunk_t *next = chunk->union_.next;
  1065. m_del(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc);
  1066. chunk = next;
  1067. }
  1068. }
  1069. #endif // MICROPY_ENABLE_COMPILER