parse.c 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  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, _13, ...) __VA_ARGS__
  121. #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,
  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, _14, ...) _14
  139. #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,
  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_QSTRnull;
  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_QSTRnull) {
  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. if (tok == MP_TOKEN_OP_AT || tok == MP_TOKEN_OP_SLASH || tok == MP_TOKEN_OP_DBL_STAR) {
  588. // Can't fold @ or / or **
  589. return false;
  590. }
  591. mp_binary_op_t op = MP_BINARY_OP_LSHIFT + (tok - MP_TOKEN_OP_DBL_LESS);
  592. int rhs_sign = mp_obj_int_sign(arg1);
  593. if (op <= MP_BINARY_OP_RSHIFT) {
  594. // << and >> can't have negative rhs
  595. if (rhs_sign < 0) {
  596. return false;
  597. }
  598. } else if (op >= MP_BINARY_OP_FLOOR_DIVIDE) {
  599. // % and // can't have zero rhs
  600. if (rhs_sign == 0) {
  601. return false;
  602. }
  603. }
  604. arg0 = mp_binary_op(op, arg0, arg1);
  605. }
  606. } else if (rule_id == RULE_factor_2) {
  607. // folding for unary ops: + - ~
  608. mp_parse_node_t pn = peek_result(parser, 0);
  609. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  610. return false;
  611. }
  612. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, 1));
  613. mp_unary_op_t op;
  614. if (tok == MP_TOKEN_OP_TILDE) {
  615. op = MP_UNARY_OP_INVERT;
  616. } else {
  617. assert(tok == MP_TOKEN_OP_PLUS || tok == MP_TOKEN_OP_MINUS); // should be
  618. op = MP_UNARY_OP_POSITIVE + (tok - MP_TOKEN_OP_PLUS);
  619. }
  620. arg0 = mp_unary_op(op, arg0);
  621. #if MICROPY_COMP_CONST
  622. } else if (rule_id == RULE_expr_stmt) {
  623. mp_parse_node_t pn1 = peek_result(parser, 0);
  624. if (!MP_PARSE_NODE_IS_NULL(pn1)
  625. && !(MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_augassign)
  626. || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) {
  627. // this node is of the form <x> = <y>
  628. mp_parse_node_t pn0 = peek_result(parser, 1);
  629. if (MP_PARSE_NODE_IS_ID(pn0)
  630. && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_atom_expr_normal)
  631. && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t*)pn1)->nodes[0])
  632. && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t*)pn1)->nodes[0]) == MP_QSTR_const
  633. && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t*)pn1)->nodes[1], RULE_trailer_paren)
  634. ) {
  635. // code to assign dynamic constants: id = const(value)
  636. // get the id
  637. qstr id = MP_PARSE_NODE_LEAF_ARG(pn0);
  638. // get the value
  639. mp_parse_node_t pn_value = ((mp_parse_node_struct_t*)((mp_parse_node_struct_t*)pn1)->nodes[1])->nodes[0];
  640. mp_obj_t value;
  641. if (!mp_parse_node_get_int_maybe(pn_value, &value)) {
  642. mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  643. "constant must be an integer");
  644. mp_obj_exception_add_traceback(exc, parser->lexer->source_name,
  645. ((mp_parse_node_struct_t*)pn1)->source_line, MP_QSTRnull);
  646. nlr_raise(exc);
  647. }
  648. // store the value in the table of dynamic constants
  649. mp_map_elem_t *elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
  650. assert(elem->value == MP_OBJ_NULL);
  651. elem->value = value;
  652. // If the constant starts with an underscore then treat it as a private
  653. // variable and don't emit any code to store the value to the id.
  654. if (qstr_str(id)[0] == '_') {
  655. pop_result(parser); // pop const(value)
  656. pop_result(parser); // pop id
  657. push_result_rule(parser, 0, RULE_pass_stmt, 0); // replace with "pass"
  658. return true;
  659. }
  660. // replace const(value) with value
  661. pop_result(parser);
  662. push_result_node(parser, pn_value);
  663. // finished folding this assignment, but we still want it to be part of the tree
  664. return false;
  665. }
  666. }
  667. return false;
  668. #endif
  669. #if MICROPY_COMP_MODULE_CONST
  670. } else if (rule_id == RULE_atom_expr_normal) {
  671. mp_parse_node_t pn0 = peek_result(parser, 1);
  672. mp_parse_node_t pn1 = peek_result(parser, 0);
  673. if (!(MP_PARSE_NODE_IS_ID(pn0)
  674. && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) {
  675. return false;
  676. }
  677. // id1.id2
  678. // look it up in constant table, see if it can be replaced with an integer
  679. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pn1;
  680. assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
  681. qstr q_base = MP_PARSE_NODE_LEAF_ARG(pn0);
  682. qstr q_attr = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]);
  683. mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP);
  684. if (elem == NULL) {
  685. return false;
  686. }
  687. mp_obj_t dest[2];
  688. mp_load_method_maybe(elem->value, q_attr, dest);
  689. if (!(dest[0] != MP_OBJ_NULL && mp_obj_is_int(dest[0]) && dest[1] == MP_OBJ_NULL)) {
  690. return false;
  691. }
  692. arg0 = dest[0];
  693. #endif
  694. } else {
  695. return false;
  696. }
  697. // success folding this rule
  698. for (size_t i = num_args; i > 0; i--) {
  699. pop_result(parser);
  700. }
  701. if (mp_obj_is_small_int(arg0)) {
  702. push_result_node(parser, mp_parse_node_new_small_int_checked(parser, arg0));
  703. } else {
  704. // TODO reuse memory for parse node struct?
  705. push_result_node(parser, make_node_const_object(parser, 0, arg0));
  706. }
  707. return true;
  708. }
  709. #endif
  710. STATIC void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args) {
  711. // optimise away parenthesis around an expression if possible
  712. if (rule_id == RULE_atom_paren) {
  713. // there should be just 1 arg for this rule
  714. mp_parse_node_t pn = peek_result(parser, 0);
  715. if (MP_PARSE_NODE_IS_NULL(pn)) {
  716. // need to keep parenthesis for ()
  717. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_testlist_comp)) {
  718. // need to keep parenthesis for (a, b, ...)
  719. } else {
  720. // parenthesis around a single expression, so it's just the expression
  721. return;
  722. }
  723. }
  724. #if MICROPY_COMP_CONST_FOLDING
  725. if (fold_logical_constants(parser, rule_id, &num_args)) {
  726. // we folded this rule so return straight away
  727. return;
  728. }
  729. if (fold_constants(parser, rule_id, num_args)) {
  730. // we folded this rule so return straight away
  731. return;
  732. }
  733. #endif
  734. mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_parse_node_t) * num_args);
  735. pn->source_line = src_line;
  736. pn->kind_num_nodes = (rule_id & 0xff) | (num_args << 8);
  737. for (size_t i = num_args; i > 0; i--) {
  738. pn->nodes[i - 1] = pop_result(parser);
  739. }
  740. push_result_node(parser, (mp_parse_node_t)pn);
  741. }
  742. mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) {
  743. // initialise parser and allocate memory for its stacks
  744. parser_t parser;
  745. parser.rule_stack_alloc = MICROPY_ALLOC_PARSE_RULE_INIT;
  746. parser.rule_stack_top = 0;
  747. parser.rule_stack = m_new(rule_stack_t, parser.rule_stack_alloc);
  748. parser.result_stack_alloc = MICROPY_ALLOC_PARSE_RESULT_INIT;
  749. parser.result_stack_top = 0;
  750. parser.result_stack = m_new(mp_parse_node_t, parser.result_stack_alloc);
  751. parser.lexer = lex;
  752. parser.tree.chunk = NULL;
  753. parser.cur_chunk = NULL;
  754. #if MICROPY_COMP_CONST
  755. mp_map_init(&parser.consts, 0);
  756. #endif
  757. // work out the top-level rule to use, and push it on the stack
  758. size_t top_level_rule;
  759. switch (input_kind) {
  760. case MP_PARSE_SINGLE_INPUT: top_level_rule = RULE_single_input; break;
  761. case MP_PARSE_EVAL_INPUT: top_level_rule = RULE_eval_input; break;
  762. default: top_level_rule = RULE_file_input;
  763. }
  764. push_rule(&parser, lex->tok_line, top_level_rule, 0);
  765. // parse!
  766. bool backtrack = false;
  767. for (;;) {
  768. next_rule:
  769. if (parser.rule_stack_top == 0) {
  770. break;
  771. }
  772. // Pop the next rule to process it
  773. size_t i; // state for the current rule
  774. size_t rule_src_line; // source line for the first token matched by the current rule
  775. uint8_t rule_id = pop_rule(&parser, &i, &rule_src_line);
  776. uint8_t rule_act = rule_act_table[rule_id];
  777. const uint16_t *rule_arg = get_rule_arg(rule_id);
  778. size_t n = rule_act & RULE_ACT_ARG_MASK;
  779. #if 0
  780. // debugging
  781. printf("depth=" UINT_FMT " ", parser.rule_stack_top);
  782. for (int j = 0; j < parser.rule_stack_top; ++j) {
  783. printf(" ");
  784. }
  785. printf("%s n=" UINT_FMT " i=" UINT_FMT " bt=%d\n", rule_name_table[rule_id], n, i, backtrack);
  786. #endif
  787. switch (rule_act & RULE_ACT_KIND_MASK) {
  788. case RULE_ACT_OR:
  789. if (i > 0 && !backtrack) {
  790. goto next_rule;
  791. } else {
  792. backtrack = false;
  793. }
  794. for (; i < n; ++i) {
  795. uint16_t kind = rule_arg[i] & RULE_ARG_KIND_MASK;
  796. if (kind == RULE_ARG_TOK) {
  797. if (lex->tok_kind == (rule_arg[i] & RULE_ARG_ARG_MASK)) {
  798. push_result_token(&parser, rule_id);
  799. mp_lexer_to_next(lex);
  800. goto next_rule;
  801. }
  802. } else {
  803. assert(kind == RULE_ARG_RULE);
  804. if (i + 1 < n) {
  805. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this or-rule
  806. }
  807. push_rule_from_arg(&parser, rule_arg[i]); // push child of or-rule
  808. goto next_rule;
  809. }
  810. }
  811. backtrack = true;
  812. break;
  813. case RULE_ACT_AND: {
  814. // failed, backtrack if we can, else syntax error
  815. if (backtrack) {
  816. assert(i > 0);
  817. if ((rule_arg[i - 1] & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE) {
  818. // an optional rule that failed, so continue with next arg
  819. push_result_node(&parser, MP_PARSE_NODE_NULL);
  820. backtrack = false;
  821. } else {
  822. // a mandatory rule that failed, so propagate backtrack
  823. if (i > 1) {
  824. // already eaten tokens so can't backtrack
  825. goto syntax_error;
  826. } else {
  827. goto next_rule;
  828. }
  829. }
  830. }
  831. // progress through the rule
  832. for (; i < n; ++i) {
  833. if ((rule_arg[i] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  834. // need to match a token
  835. mp_token_kind_t tok_kind = rule_arg[i] & RULE_ARG_ARG_MASK;
  836. if (lex->tok_kind == tok_kind) {
  837. // matched token
  838. if (tok_kind == MP_TOKEN_NAME) {
  839. push_result_token(&parser, rule_id);
  840. }
  841. mp_lexer_to_next(lex);
  842. } else {
  843. // failed to match token
  844. if (i > 0) {
  845. // already eaten tokens so can't backtrack
  846. goto syntax_error;
  847. } else {
  848. // this rule failed, so backtrack
  849. backtrack = true;
  850. goto next_rule;
  851. }
  852. }
  853. } else {
  854. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this and-rule
  855. push_rule_from_arg(&parser, rule_arg[i]); // push child of and-rule
  856. goto next_rule;
  857. }
  858. }
  859. assert(i == n);
  860. // matched the rule, so now build the corresponding parse_node
  861. #if !MICROPY_ENABLE_DOC_STRING
  862. // this code discards lonely statements, such as doc strings
  863. if (input_kind != MP_PARSE_SINGLE_INPUT && rule_id == RULE_expr_stmt && peek_result(&parser, 0) == MP_PARSE_NODE_NULL) {
  864. mp_parse_node_t p = peek_result(&parser, 1);
  865. if ((MP_PARSE_NODE_IS_LEAF(p) && !MP_PARSE_NODE_IS_ID(p))
  866. || MP_PARSE_NODE_IS_STRUCT_KIND(p, RULE_const_object)) {
  867. pop_result(&parser); // MP_PARSE_NODE_NULL
  868. pop_result(&parser); // const expression (leaf or RULE_const_object)
  869. // Pushing the "pass" rule here will overwrite any RULE_const_object
  870. // entry that was on the result stack, allowing the GC to reclaim
  871. // the memory from the const object when needed.
  872. push_result_rule(&parser, rule_src_line, RULE_pass_stmt, 0);
  873. break;
  874. }
  875. }
  876. #endif
  877. // count number of arguments for the parse node
  878. i = 0;
  879. size_t num_not_nil = 0;
  880. for (size_t x = n; x > 0;) {
  881. --x;
  882. if ((rule_arg[x] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  883. mp_token_kind_t tok_kind = rule_arg[x] & RULE_ARG_ARG_MASK;
  884. if (tok_kind == MP_TOKEN_NAME) {
  885. // only tokens which were names are pushed to stack
  886. i += 1;
  887. num_not_nil += 1;
  888. }
  889. } else {
  890. // rules are always pushed
  891. if (peek_result(&parser, i) != MP_PARSE_NODE_NULL) {
  892. num_not_nil += 1;
  893. }
  894. i += 1;
  895. }
  896. }
  897. if (num_not_nil == 1 && (rule_act & RULE_ACT_ALLOW_IDENT)) {
  898. // this rule has only 1 argument and should not be emitted
  899. mp_parse_node_t pn = MP_PARSE_NODE_NULL;
  900. for (size_t x = 0; x < i; ++x) {
  901. mp_parse_node_t pn2 = pop_result(&parser);
  902. if (pn2 != MP_PARSE_NODE_NULL) {
  903. pn = pn2;
  904. }
  905. }
  906. push_result_node(&parser, pn);
  907. } else {
  908. // this rule must be emitted
  909. if (rule_act & RULE_ACT_ADD_BLANK) {
  910. // and add an extra blank node at the end (used by the compiler to store data)
  911. push_result_node(&parser, MP_PARSE_NODE_NULL);
  912. i += 1;
  913. }
  914. push_result_rule(&parser, rule_src_line, rule_id, i);
  915. }
  916. break;
  917. }
  918. default: {
  919. assert((rule_act & RULE_ACT_KIND_MASK) == RULE_ACT_LIST);
  920. // n=2 is: item item*
  921. // n=1 is: item (sep item)*
  922. // n=3 is: item (sep item)* [sep]
  923. bool had_trailing_sep;
  924. if (backtrack) {
  925. list_backtrack:
  926. had_trailing_sep = false;
  927. if (n == 2) {
  928. if (i == 1) {
  929. // fail on item, first time round; propagate backtrack
  930. goto next_rule;
  931. } else {
  932. // fail on item, in later rounds; finish with this rule
  933. backtrack = false;
  934. }
  935. } else {
  936. if (i == 1) {
  937. // fail on item, first time round; propagate backtrack
  938. goto next_rule;
  939. } else if ((i & 1) == 1) {
  940. // fail on item, in later rounds; have eaten tokens so can't backtrack
  941. if (n == 3) {
  942. // list allows trailing separator; finish parsing list
  943. had_trailing_sep = true;
  944. backtrack = false;
  945. } else {
  946. // list doesn't allowing trailing separator; fail
  947. goto syntax_error;
  948. }
  949. } else {
  950. // fail on separator; finish parsing list
  951. backtrack = false;
  952. }
  953. }
  954. } else {
  955. for (;;) {
  956. size_t arg = rule_arg[i & 1 & n];
  957. if ((arg & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  958. if (lex->tok_kind == (arg & RULE_ARG_ARG_MASK)) {
  959. if (i & 1 & n) {
  960. // separators which are tokens are not pushed to result stack
  961. } else {
  962. push_result_token(&parser, rule_id);
  963. }
  964. mp_lexer_to_next(lex);
  965. // got element of list, so continue parsing list
  966. i += 1;
  967. } else {
  968. // couldn't get element of list
  969. i += 1;
  970. backtrack = true;
  971. goto list_backtrack;
  972. }
  973. } else {
  974. assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE);
  975. push_rule(&parser, rule_src_line, rule_id, i + 1); // save this list-rule
  976. push_rule_from_arg(&parser, arg); // push child of list-rule
  977. goto next_rule;
  978. }
  979. }
  980. }
  981. assert(i >= 1);
  982. // compute number of elements in list, result in i
  983. i -= 1;
  984. if ((n & 1) && (rule_arg[1] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  985. // don't count separators when they are tokens
  986. i = (i + 1) / 2;
  987. }
  988. if (i == 1) {
  989. // list matched single item
  990. if (had_trailing_sep) {
  991. // if there was a trailing separator, make a list of a single item
  992. push_result_rule(&parser, rule_src_line, rule_id, i);
  993. } else {
  994. // just leave single item on stack (ie don't wrap in a list)
  995. }
  996. } else {
  997. push_result_rule(&parser, rule_src_line, rule_id, i);
  998. }
  999. break;
  1000. }
  1001. }
  1002. }
  1003. #if MICROPY_COMP_CONST
  1004. mp_map_deinit(&parser.consts);
  1005. #endif
  1006. // truncate final chunk and link into chain of chunks
  1007. if (parser.cur_chunk != NULL) {
  1008. (void)m_renew_maybe(byte, parser.cur_chunk,
  1009. sizeof(mp_parse_chunk_t) + parser.cur_chunk->alloc,
  1010. sizeof(mp_parse_chunk_t) + parser.cur_chunk->union_.used,
  1011. false);
  1012. parser.cur_chunk->alloc = parser.cur_chunk->union_.used;
  1013. parser.cur_chunk->union_.next = parser.tree.chunk;
  1014. parser.tree.chunk = parser.cur_chunk;
  1015. }
  1016. if (
  1017. lex->tok_kind != MP_TOKEN_END // check we are at the end of the token stream
  1018. || parser.result_stack_top == 0 // check that we got a node (can fail on empty input)
  1019. ) {
  1020. syntax_error:;
  1021. mp_obj_t exc;
  1022. if (lex->tok_kind == MP_TOKEN_INDENT) {
  1023. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  1024. "unexpected indent");
  1025. } else if (lex->tok_kind == MP_TOKEN_DEDENT_MISMATCH) {
  1026. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  1027. "unindent doesn't match any outer indent level");
  1028. } else {
  1029. exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  1030. "invalid syntax");
  1031. }
  1032. // add traceback to give info about file name and location
  1033. // we don't have a 'block' name, so just pass the NULL qstr to indicate this
  1034. mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTRnull);
  1035. nlr_raise(exc);
  1036. }
  1037. // get the root parse node that we created
  1038. assert(parser.result_stack_top == 1);
  1039. parser.tree.root = parser.result_stack[0];
  1040. // free the memory that we don't need anymore
  1041. m_del(rule_stack_t, parser.rule_stack, parser.rule_stack_alloc);
  1042. m_del(mp_parse_node_t, parser.result_stack, parser.result_stack_alloc);
  1043. // we also free the lexer on behalf of the caller
  1044. mp_lexer_free(lex);
  1045. return parser.tree;
  1046. }
  1047. void mp_parse_tree_clear(mp_parse_tree_t *tree) {
  1048. mp_parse_chunk_t *chunk = tree->chunk;
  1049. while (chunk != NULL) {
  1050. mp_parse_chunk_t *next = chunk->union_.next;
  1051. m_del(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc);
  1052. chunk = next;
  1053. }
  1054. }
  1055. #endif // MICROPY_ENABLE_COMPILER