parse.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013-2015 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 <sys/types.h>
  30. #include <unistd.h> // for ssize_t
  31. #include <assert.h>
  32. #include <string.h>
  33. #include "py/lexer.h"
  34. #include "py/parse.h"
  35. #include "py/parsenum.h"
  36. #include "py/runtime.h"
  37. #include "py/objint.h"
  38. #include "py/objstr.h"
  39. #include "py/builtin.h"
  40. #if MICROPY_ENABLE_COMPILER
  41. #define RULE_ACT_ARG_MASK (0x0f)
  42. #define RULE_ACT_KIND_MASK (0x30)
  43. #define RULE_ACT_ALLOW_IDENT (0x40)
  44. #define RULE_ACT_ADD_BLANK (0x80)
  45. #define RULE_ACT_OR (0x10)
  46. #define RULE_ACT_AND (0x20)
  47. #define RULE_ACT_LIST (0x30)
  48. #define RULE_ARG_KIND_MASK (0xf000)
  49. #define RULE_ARG_ARG_MASK (0x0fff)
  50. #define RULE_ARG_TOK (0x1000)
  51. #define RULE_ARG_RULE (0x2000)
  52. #define RULE_ARG_OPT_RULE (0x3000)
  53. // (un)comment to use rule names; for debugging
  54. //#define USE_RULE_NAME (1)
  55. typedef struct _rule_t {
  56. byte rule_id;
  57. byte act;
  58. #ifdef USE_RULE_NAME
  59. const char *rule_name;
  60. #endif
  61. uint16_t arg[];
  62. } rule_t;
  63. enum {
  64. // define rules with a compile function
  65. #define DEF_RULE(rule, comp, kind, ...) RULE_##rule,
  66. #define DEF_RULE_NC(rule, kind, ...)
  67. #include "py/grammar.h"
  68. #undef DEF_RULE
  69. #undef DEF_RULE_NC
  70. RULE_const_object, // special node for a constant, generic Python object
  71. // define rules without a compile function
  72. #define DEF_RULE(rule, comp, kind, ...)
  73. #define DEF_RULE_NC(rule, kind, ...) RULE_##rule,
  74. #include "py/grammar.h"
  75. #undef DEF_RULE
  76. #undef DEF_RULE_NC
  77. };
  78. #define or(n) (RULE_ACT_OR | n)
  79. #define and(n) (RULE_ACT_AND | n)
  80. #define and_ident(n) (RULE_ACT_AND | n | RULE_ACT_ALLOW_IDENT)
  81. #define and_blank(n) (RULE_ACT_AND | n | RULE_ACT_ADD_BLANK)
  82. #define one_or_more (RULE_ACT_LIST | 2)
  83. #define list (RULE_ACT_LIST | 1)
  84. #define list_with_end (RULE_ACT_LIST | 3)
  85. #define tok(t) (RULE_ARG_TOK | MP_TOKEN_##t)
  86. #define rule(r) (RULE_ARG_RULE | RULE_##r)
  87. #define opt_rule(r) (RULE_ARG_OPT_RULE | RULE_##r)
  88. #ifdef USE_RULE_NAME
  89. #define DEF_RULE(rule, comp, kind, ...) static const rule_t rule_##rule = { RULE_##rule, kind, #rule, { __VA_ARGS__ } };
  90. #define DEF_RULE_NC(rule, kind, ...) static const rule_t rule_##rule = { RULE_##rule, kind, #rule, { __VA_ARGS__ } };
  91. #else
  92. #define DEF_RULE(rule, comp, kind, ...) static const rule_t rule_##rule = { RULE_##rule, kind, { __VA_ARGS__ } };
  93. #define DEF_RULE_NC(rule, kind, ...) static const rule_t rule_##rule = { RULE_##rule, kind, { __VA_ARGS__ } };
  94. #endif
  95. #include "py/grammar.h"
  96. #undef or
  97. #undef and
  98. #undef list
  99. #undef list_with_end
  100. #undef tok
  101. #undef rule
  102. #undef opt_rule
  103. #undef one_or_more
  104. #undef DEF_RULE
  105. #undef DEF_RULE_NC
  106. STATIC const rule_t *const rules[] = {
  107. // define rules with a compile function
  108. #define DEF_RULE(rule, comp, kind, ...) &rule_##rule,
  109. #define DEF_RULE_NC(rule, kind, ...)
  110. #include "py/grammar.h"
  111. #undef DEF_RULE
  112. #undef DEF_RULE_NC
  113. NULL, // RULE_const_object
  114. // define rules without a compile function
  115. #define DEF_RULE(rule, comp, kind, ...)
  116. #define DEF_RULE_NC(rule, kind, ...) &rule_##rule,
  117. #include "py/grammar.h"
  118. #undef DEF_RULE
  119. #undef DEF_RULE_NC
  120. };
  121. typedef struct _rule_stack_t {
  122. size_t src_line : 8 * sizeof(size_t) - 8; // maximum bits storing source line number
  123. size_t rule_id : 8; // this must be large enough to fit largest rule number
  124. size_t arg_i; // this dictates the maximum nodes in a "list" of things
  125. } rule_stack_t;
  126. typedef struct _mp_parse_chunk_t {
  127. size_t alloc;
  128. union {
  129. size_t used;
  130. struct _mp_parse_chunk_t *next;
  131. } union_;
  132. byte data[];
  133. } mp_parse_chunk_t;
  134. typedef struct _parser_t {
  135. size_t rule_stack_alloc;
  136. size_t rule_stack_top;
  137. rule_stack_t *rule_stack;
  138. size_t result_stack_alloc;
  139. size_t result_stack_top;
  140. mp_parse_node_t *result_stack;
  141. mp_lexer_t *lexer;
  142. mp_parse_tree_t tree;
  143. mp_parse_chunk_t *cur_chunk;
  144. #if MICROPY_COMP_CONST
  145. mp_map_t consts;
  146. #endif
  147. } parser_t;
  148. STATIC void *parser_alloc(parser_t *parser, size_t num_bytes) {
  149. // use a custom memory allocator to store parse nodes sequentially in large chunks
  150. mp_parse_chunk_t *chunk = parser->cur_chunk;
  151. if (chunk != NULL && chunk->union_.used + num_bytes > chunk->alloc) {
  152. // not enough room at end of previously allocated chunk so try to grow
  153. mp_parse_chunk_t *new_data = (mp_parse_chunk_t*)m_renew_maybe(byte, chunk,
  154. sizeof(mp_parse_chunk_t) + chunk->alloc,
  155. sizeof(mp_parse_chunk_t) + chunk->alloc + num_bytes, false);
  156. if (new_data == NULL) {
  157. // could not grow existing memory; shrink it to fit previous
  158. (void)m_renew_maybe(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc,
  159. sizeof(mp_parse_chunk_t) + chunk->union_.used, false);
  160. chunk->alloc = chunk->union_.used;
  161. chunk->union_.next = parser->tree.chunk;
  162. parser->tree.chunk = chunk;
  163. chunk = NULL;
  164. } else {
  165. // could grow existing memory
  166. chunk->alloc += num_bytes;
  167. }
  168. }
  169. if (chunk == NULL) {
  170. // no previous chunk, allocate a new chunk
  171. size_t alloc = MICROPY_ALLOC_PARSE_CHUNK_INIT;
  172. if (alloc < num_bytes) {
  173. alloc = num_bytes;
  174. }
  175. chunk = (mp_parse_chunk_t*)m_new(byte, sizeof(mp_parse_chunk_t) + alloc);
  176. chunk->alloc = alloc;
  177. chunk->union_.used = 0;
  178. parser->cur_chunk = chunk;
  179. }
  180. byte *ret = chunk->data + chunk->union_.used;
  181. chunk->union_.used += num_bytes;
  182. return ret;
  183. }
  184. STATIC void push_rule(parser_t *parser, size_t src_line, const rule_t *rule, size_t arg_i) {
  185. if (parser->rule_stack_top >= parser->rule_stack_alloc) {
  186. 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);
  187. parser->rule_stack = rs;
  188. parser->rule_stack_alloc += MICROPY_ALLOC_PARSE_RULE_INC;
  189. }
  190. rule_stack_t *rs = &parser->rule_stack[parser->rule_stack_top++];
  191. rs->src_line = src_line;
  192. rs->rule_id = rule->rule_id;
  193. rs->arg_i = arg_i;
  194. }
  195. STATIC void push_rule_from_arg(parser_t *parser, size_t arg) {
  196. assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE || (arg & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE);
  197. size_t rule_id = arg & RULE_ARG_ARG_MASK;
  198. push_rule(parser, parser->lexer->tok_line, rules[rule_id], 0);
  199. }
  200. STATIC void pop_rule(parser_t *parser, const rule_t **rule, size_t *arg_i, size_t *src_line) {
  201. parser->rule_stack_top -= 1;
  202. *rule = rules[parser->rule_stack[parser->rule_stack_top].rule_id];
  203. *arg_i = parser->rule_stack[parser->rule_stack_top].arg_i;
  204. *src_line = parser->rule_stack[parser->rule_stack_top].src_line;
  205. }
  206. bool mp_parse_node_is_const_false(mp_parse_node_t pn) {
  207. return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_FALSE)
  208. || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0);
  209. }
  210. bool mp_parse_node_is_const_true(mp_parse_node_t pn) {
  211. return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_TRUE)
  212. || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) != 0);
  213. }
  214. bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) {
  215. if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  216. *o = MP_OBJ_NEW_SMALL_INT(MP_PARSE_NODE_LEAF_SMALL_INT(pn));
  217. return true;
  218. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_const_object)) {
  219. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  220. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  221. // nodes are 32-bit pointers, but need to extract 64-bit object
  222. *o = (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32);
  223. #else
  224. *o = (mp_obj_t)pns->nodes[0];
  225. #endif
  226. return MP_OBJ_IS_INT(*o);
  227. } else {
  228. return false;
  229. }
  230. }
  231. int mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_node_t **nodes) {
  232. if (MP_PARSE_NODE_IS_NULL(*pn)) {
  233. *nodes = NULL;
  234. return 0;
  235. } else if (MP_PARSE_NODE_IS_LEAF(*pn)) {
  236. *nodes = pn;
  237. return 1;
  238. } else {
  239. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)(*pn);
  240. if (MP_PARSE_NODE_STRUCT_KIND(pns) != pn_kind) {
  241. *nodes = pn;
  242. return 1;
  243. } else {
  244. *nodes = pns->nodes;
  245. return MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  246. }
  247. }
  248. }
  249. #if MICROPY_DEBUG_PRINTERS
  250. void mp_parse_node_print(mp_parse_node_t pn, size_t indent) {
  251. if (MP_PARSE_NODE_IS_STRUCT(pn)) {
  252. printf("[% 4d] ", (int)((mp_parse_node_struct_t*)pn)->source_line);
  253. } else {
  254. printf(" ");
  255. }
  256. for (size_t i = 0; i < indent; i++) {
  257. printf(" ");
  258. }
  259. if (MP_PARSE_NODE_IS_NULL(pn)) {
  260. printf("NULL\n");
  261. } else if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
  262. mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn);
  263. printf("int(" INT_FMT ")\n", arg);
  264. } else if (MP_PARSE_NODE_IS_LEAF(pn)) {
  265. uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
  266. switch (MP_PARSE_NODE_LEAF_KIND(pn)) {
  267. case MP_PARSE_NODE_ID: printf("id(%s)\n", qstr_str(arg)); break;
  268. case MP_PARSE_NODE_STRING: printf("str(%s)\n", qstr_str(arg)); break;
  269. case MP_PARSE_NODE_BYTES: printf("bytes(%s)\n", qstr_str(arg)); break;
  270. default:
  271. assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN);
  272. printf("tok(%u)\n", (uint)arg); break;
  273. }
  274. } else {
  275. // node must be a mp_parse_node_struct_t
  276. mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn;
  277. if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_const_object) {
  278. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  279. printf("literal const(%016llx)\n", (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32));
  280. #else
  281. printf("literal const(%p)\n", (mp_obj_t)pns->nodes[0]);
  282. #endif
  283. } else {
  284. size_t n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
  285. #ifdef USE_RULE_NAME
  286. printf("%s(%u) (n=%u)\n", rules[MP_PARSE_NODE_STRUCT_KIND(pns)]->rule_name, (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
  287. #else
  288. printf("rule(%u) (n=%u)\n", (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
  289. #endif
  290. for (size_t i = 0; i < n; i++) {
  291. mp_parse_node_print(pns->nodes[i], indent + 2);
  292. }
  293. }
  294. }
  295. }
  296. #endif // MICROPY_DEBUG_PRINTERS
  297. /*
  298. STATIC void result_stack_show(parser_t *parser) {
  299. printf("result stack, most recent first\n");
  300. for (ssize_t i = parser->result_stack_top - 1; i >= 0; i--) {
  301. mp_parse_node_print(parser->result_stack[i], 0);
  302. }
  303. }
  304. */
  305. STATIC mp_parse_node_t pop_result(parser_t *parser) {
  306. assert(parser->result_stack_top > 0);
  307. return parser->result_stack[--parser->result_stack_top];
  308. }
  309. STATIC mp_parse_node_t peek_result(parser_t *parser, size_t pos) {
  310. assert(parser->result_stack_top > pos);
  311. return parser->result_stack[parser->result_stack_top - 1 - pos];
  312. }
  313. STATIC void push_result_node(parser_t *parser, mp_parse_node_t pn) {
  314. if (parser->result_stack_top >= parser->result_stack_alloc) {
  315. 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);
  316. parser->result_stack = stack;
  317. parser->result_stack_alloc += MICROPY_ALLOC_PARSE_RESULT_INC;
  318. }
  319. parser->result_stack[parser->result_stack_top++] = pn;
  320. }
  321. STATIC mp_parse_node_t make_node_const_object(parser_t *parser, size_t src_line, mp_obj_t obj) {
  322. mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_obj_t));
  323. pn->source_line = src_line;
  324. #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
  325. // nodes are 32-bit pointers, but need to store 64-bit object
  326. pn->kind_num_nodes = RULE_const_object | (2 << 8);
  327. pn->nodes[0] = (uint64_t)obj;
  328. pn->nodes[1] = (uint64_t)obj >> 32;
  329. #else
  330. pn->kind_num_nodes = RULE_const_object | (1 << 8);
  331. pn->nodes[0] = (uintptr_t)obj;
  332. #endif
  333. return (mp_parse_node_t)pn;
  334. }
  335. STATIC void push_result_token(parser_t *parser, const rule_t *rule) {
  336. mp_parse_node_t pn;
  337. mp_lexer_t *lex = parser->lexer;
  338. if (lex->tok_kind == MP_TOKEN_NAME) {
  339. qstr id = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
  340. #if MICROPY_COMP_CONST
  341. // if name is a standalone identifier, look it up in the table of dynamic constants
  342. mp_map_elem_t *elem;
  343. if (rule->rule_id == RULE_atom
  344. && (elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP)) != NULL) {
  345. if (MP_OBJ_IS_SMALL_INT(elem->value)) {
  346. pn = mp_parse_node_new_small_int(MP_OBJ_SMALL_INT_VALUE(elem->value));
  347. } else {
  348. pn = make_node_const_object(parser, lex->tok_line, elem->value);
  349. }
  350. } else {
  351. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
  352. }
  353. #else
  354. (void)rule;
  355. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
  356. #endif
  357. } else if (lex->tok_kind == MP_TOKEN_INTEGER) {
  358. mp_obj_t o = mp_parse_num_integer(lex->vstr.buf, lex->vstr.len, 0, lex);
  359. if (MP_OBJ_IS_SMALL_INT(o)) {
  360. pn = mp_parse_node_new_small_int(MP_OBJ_SMALL_INT_VALUE(o));
  361. } else {
  362. pn = make_node_const_object(parser, lex->tok_line, o);
  363. }
  364. } else if (lex->tok_kind == MP_TOKEN_FLOAT_OR_IMAG) {
  365. mp_obj_t o = mp_parse_num_decimal(lex->vstr.buf, lex->vstr.len, true, false, lex);
  366. pn = make_node_const_object(parser, lex->tok_line, o);
  367. } else if (lex->tok_kind == MP_TOKEN_STRING || lex->tok_kind == MP_TOKEN_BYTES) {
  368. // Don't automatically intern all strings/bytes. doc strings (which are usually large)
  369. // will be discarded by the compiler, and so we shouldn't intern them.
  370. qstr qst = MP_QSTR_NULL;
  371. if (lex->vstr.len <= MICROPY_ALLOC_PARSE_INTERN_STRING_LEN) {
  372. // intern short strings
  373. qst = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
  374. } else {
  375. // check if this string is already interned
  376. qst = qstr_find_strn(lex->vstr.buf, lex->vstr.len);
  377. }
  378. if (qst != MP_QSTR_NULL) {
  379. // qstr exists, make a leaf node
  380. pn = mp_parse_node_new_leaf(lex->tok_kind == MP_TOKEN_STRING ? MP_PARSE_NODE_STRING : MP_PARSE_NODE_BYTES, qst);
  381. } else {
  382. // not interned, make a node holding a pointer to the string/bytes object
  383. mp_obj_t o = mp_obj_new_str_of_type(
  384. lex->tok_kind == MP_TOKEN_STRING ? &mp_type_str : &mp_type_bytes,
  385. (const byte*)lex->vstr.buf, lex->vstr.len);
  386. pn = make_node_const_object(parser, lex->tok_line, o);
  387. }
  388. } else {
  389. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, lex->tok_kind);
  390. }
  391. push_result_node(parser, pn);
  392. }
  393. #if MICROPY_COMP_MODULE_CONST
  394. STATIC const mp_rom_map_elem_t mp_constants_table[] = {
  395. #if MICROPY_PY_UERRNO
  396. { MP_ROM_QSTR(MP_QSTR_errno), MP_ROM_PTR(&mp_module_uerrno) },
  397. #endif
  398. #if MICROPY_PY_UCTYPES
  399. { MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) },
  400. #endif
  401. // Extra constants as defined by a port
  402. MICROPY_PORT_CONSTANTS
  403. };
  404. STATIC MP_DEFINE_CONST_MAP(mp_constants_map, mp_constants_table);
  405. #endif
  406. STATIC void push_result_rule(parser_t *parser, size_t src_line, const rule_t *rule, size_t num_args);
  407. #if MICROPY_COMP_CONST_FOLDING
  408. STATIC bool fold_logical_constants(parser_t *parser, const rule_t *rule, size_t *num_args) {
  409. if (rule->rule_id == RULE_or_test
  410. || rule->rule_id == RULE_and_test) {
  411. // folding for binary logical ops: or and
  412. size_t copy_to = *num_args;
  413. for (size_t i = copy_to; i > 0;) {
  414. mp_parse_node_t pn = peek_result(parser, --i);
  415. parser->result_stack[parser->result_stack_top - copy_to] = pn;
  416. if (i == 0) {
  417. // always need to keep the last value
  418. break;
  419. }
  420. if (rule->rule_id == RULE_or_test) {
  421. if (mp_parse_node_is_const_true(pn)) {
  422. //
  423. break;
  424. } else if (!mp_parse_node_is_const_false(pn)) {
  425. copy_to -= 1;
  426. }
  427. } else {
  428. // RULE_and_test
  429. if (mp_parse_node_is_const_false(pn)) {
  430. break;
  431. } else if (!mp_parse_node_is_const_true(pn)) {
  432. copy_to -= 1;
  433. }
  434. }
  435. }
  436. copy_to -= 1; // copy_to now contains number of args to pop
  437. // pop and discard all the short-circuited expressions
  438. for (size_t i = 0; i < copy_to; ++i) {
  439. pop_result(parser);
  440. }
  441. *num_args -= copy_to;
  442. // we did a complete folding if there's only 1 arg left
  443. return *num_args == 1;
  444. } else if (rule->rule_id == RULE_not_test_2) {
  445. // folding for unary logical op: not
  446. mp_parse_node_t pn = peek_result(parser, 0);
  447. if (mp_parse_node_is_const_false(pn)) {
  448. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_TRUE);
  449. } else if (mp_parse_node_is_const_true(pn)) {
  450. pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_FALSE);
  451. } else {
  452. return false;
  453. }
  454. pop_result(parser);
  455. push_result_node(parser, pn);
  456. return true;
  457. }
  458. return false;
  459. }
  460. STATIC bool fold_constants(parser_t *parser, const rule_t *rule, size_t num_args) {
  461. // this code does folding of arbitrary integer expressions, eg 1 + 2 * 3 + 4
  462. // it does not do partial folding, eg 1 + 2 + x -> 3 + x
  463. mp_obj_t arg0;
  464. if (rule->rule_id == RULE_expr
  465. || rule->rule_id == RULE_xor_expr
  466. || rule->rule_id == RULE_and_expr) {
  467. // folding for binary ops: | ^ &
  468. mp_parse_node_t pn = peek_result(parser, num_args - 1);
  469. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  470. return false;
  471. }
  472. mp_binary_op_t op;
  473. if (rule->rule_id == RULE_expr) {
  474. op = MP_BINARY_OP_OR;
  475. } else if (rule->rule_id == RULE_xor_expr) {
  476. op = MP_BINARY_OP_XOR;
  477. } else {
  478. op = MP_BINARY_OP_AND;
  479. }
  480. for (ssize_t i = num_args - 2; i >= 0; --i) {
  481. pn = peek_result(parser, i);
  482. mp_obj_t arg1;
  483. if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
  484. return false;
  485. }
  486. arg0 = mp_binary_op(op, arg0, arg1);
  487. }
  488. } else if (rule->rule_id == RULE_shift_expr
  489. || rule->rule_id == RULE_arith_expr
  490. || rule->rule_id == RULE_term) {
  491. // folding for binary ops: << >> + - * / % //
  492. mp_parse_node_t pn = peek_result(parser, num_args - 1);
  493. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  494. return false;
  495. }
  496. for (ssize_t i = num_args - 2; i >= 1; i -= 2) {
  497. pn = peek_result(parser, i - 1);
  498. mp_obj_t arg1;
  499. if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
  500. return false;
  501. }
  502. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, i));
  503. static const uint8_t token_to_op[] = {
  504. MP_BINARY_OP_ADD,
  505. MP_BINARY_OP_SUBTRACT,
  506. MP_BINARY_OP_MULTIPLY,
  507. 255,//MP_BINARY_OP_POWER,
  508. 255,//MP_BINARY_OP_TRUE_DIVIDE,
  509. MP_BINARY_OP_FLOOR_DIVIDE,
  510. MP_BINARY_OP_MODULO,
  511. 255,//MP_BINARY_OP_LESS
  512. MP_BINARY_OP_LSHIFT,
  513. 255,//MP_BINARY_OP_MORE
  514. MP_BINARY_OP_RSHIFT,
  515. };
  516. mp_binary_op_t op = token_to_op[tok - MP_TOKEN_OP_PLUS];
  517. if (op == (mp_binary_op_t)255) {
  518. return false;
  519. }
  520. int rhs_sign = mp_obj_int_sign(arg1);
  521. if (op <= MP_BINARY_OP_RSHIFT) {
  522. // << and >> can't have negative rhs
  523. if (rhs_sign < 0) {
  524. return false;
  525. }
  526. } else if (op >= MP_BINARY_OP_FLOOR_DIVIDE) {
  527. // % and // can't have zero rhs
  528. if (rhs_sign == 0) {
  529. return false;
  530. }
  531. }
  532. arg0 = mp_binary_op(op, arg0, arg1);
  533. }
  534. } else if (rule->rule_id == RULE_factor_2) {
  535. // folding for unary ops: + - ~
  536. mp_parse_node_t pn = peek_result(parser, 0);
  537. if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
  538. return false;
  539. }
  540. mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, 1));
  541. mp_unary_op_t op;
  542. if (tok == MP_TOKEN_OP_PLUS) {
  543. op = MP_UNARY_OP_POSITIVE;
  544. } else if (tok == MP_TOKEN_OP_MINUS) {
  545. op = MP_UNARY_OP_NEGATIVE;
  546. } else {
  547. assert(tok == MP_TOKEN_OP_TILDE); // should be
  548. op = MP_UNARY_OP_INVERT;
  549. }
  550. arg0 = mp_unary_op(op, arg0);
  551. #if MICROPY_COMP_CONST
  552. } else if (rule->rule_id == RULE_expr_stmt) {
  553. mp_parse_node_t pn1 = peek_result(parser, 0);
  554. if (!MP_PARSE_NODE_IS_NULL(pn1)
  555. && !(MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_augassign)
  556. || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) {
  557. // this node is of the form <x> = <y>
  558. mp_parse_node_t pn0 = peek_result(parser, 1);
  559. if (MP_PARSE_NODE_IS_ID(pn0)
  560. && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_atom_expr_normal)
  561. && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t*)pn1)->nodes[0])
  562. && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t*)pn1)->nodes[0]) == MP_QSTR_const
  563. && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t*)pn1)->nodes[1], RULE_trailer_paren)
  564. ) {
  565. // code to assign dynamic constants: id = const(value)
  566. // get the id
  567. qstr id = MP_PARSE_NODE_LEAF_ARG(pn0);
  568. // get the value
  569. mp_parse_node_t pn_value = ((mp_parse_node_struct_t*)((mp_parse_node_struct_t*)pn1)->nodes[1])->nodes[0];
  570. mp_obj_t value;
  571. if (!mp_parse_node_get_int_maybe(pn_value, &value)) {
  572. mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  573. "constant must be an integer");
  574. mp_obj_exception_add_traceback(exc, parser->lexer->source_name,
  575. ((mp_parse_node_struct_t*)pn1)->source_line, MP_QSTR_NULL);
  576. nlr_raise(exc);
  577. }
  578. // store the value in the table of dynamic constants
  579. mp_map_elem_t *elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
  580. assert(elem->value == MP_OBJ_NULL);
  581. elem->value = value;
  582. // If the constant starts with an underscore then treat it as a private
  583. // variable and don't emit any code to store the value to the id.
  584. if (qstr_str(id)[0] == '_') {
  585. pop_result(parser); // pop const(value)
  586. pop_result(parser); // pop id
  587. push_result_rule(parser, 0, rules[RULE_pass_stmt], 0); // replace with "pass"
  588. return true;
  589. }
  590. // replace const(value) with value
  591. pop_result(parser);
  592. push_result_node(parser, pn_value);
  593. // finished folding this assignment, but we still want it to be part of the tree
  594. return false;
  595. }
  596. }
  597. return false;
  598. #endif
  599. #if MICROPY_COMP_MODULE_CONST
  600. } else if (rule->rule_id == RULE_atom_expr_normal) {
  601. mp_parse_node_t pn0 = peek_result(parser, 1);
  602. mp_parse_node_t pn1 = peek_result(parser, 0);
  603. if (!(MP_PARSE_NODE_IS_ID(pn0)
  604. && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) {
  605. return false;
  606. }
  607. // id1.id2
  608. // look it up in constant table, see if it can be replaced with an integer
  609. mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pn1;
  610. assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
  611. qstr q_base = MP_PARSE_NODE_LEAF_ARG(pn0);
  612. qstr q_attr = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]);
  613. mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP);
  614. if (elem == NULL) {
  615. return false;
  616. }
  617. mp_obj_t dest[2];
  618. mp_load_method_maybe(elem->value, q_attr, dest);
  619. if (!(dest[0] != MP_OBJ_NULL && MP_OBJ_IS_INT(dest[0]) && dest[1] == MP_OBJ_NULL)) {
  620. return false;
  621. }
  622. arg0 = dest[0];
  623. #endif
  624. } else {
  625. return false;
  626. }
  627. // success folding this rule
  628. for (size_t i = num_args; i > 0; i--) {
  629. pop_result(parser);
  630. }
  631. if (MP_OBJ_IS_SMALL_INT(arg0)) {
  632. push_result_node(parser, mp_parse_node_new_small_int(MP_OBJ_SMALL_INT_VALUE(arg0)));
  633. } else {
  634. // TODO reuse memory for parse node struct?
  635. push_result_node(parser, make_node_const_object(parser, 0, arg0));
  636. }
  637. return true;
  638. }
  639. #endif
  640. STATIC void push_result_rule(parser_t *parser, size_t src_line, const rule_t *rule, size_t num_args) {
  641. // optimise away parenthesis around an expression if possible
  642. if (rule->rule_id == RULE_atom_paren) {
  643. // there should be just 1 arg for this rule
  644. mp_parse_node_t pn = peek_result(parser, 0);
  645. if (MP_PARSE_NODE_IS_NULL(pn)) {
  646. // need to keep parenthesis for ()
  647. } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_testlist_comp)) {
  648. // need to keep parenthesis for (a, b, ...)
  649. } else {
  650. // parenthesis around a single expression, so it's just the expression
  651. return;
  652. }
  653. }
  654. #if MICROPY_COMP_CONST_FOLDING
  655. if (fold_logical_constants(parser, rule, &num_args)) {
  656. // we folded this rule so return straight away
  657. return;
  658. }
  659. if (fold_constants(parser, rule, num_args)) {
  660. // we folded this rule so return straight away
  661. return;
  662. }
  663. #endif
  664. mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_parse_node_t) * num_args);
  665. pn->source_line = src_line;
  666. pn->kind_num_nodes = (rule->rule_id & 0xff) | (num_args << 8);
  667. for (size_t i = num_args; i > 0; i--) {
  668. pn->nodes[i - 1] = pop_result(parser);
  669. }
  670. push_result_node(parser, (mp_parse_node_t)pn);
  671. }
  672. mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) {
  673. // initialise parser and allocate memory for its stacks
  674. parser_t parser;
  675. parser.rule_stack_alloc = MICROPY_ALLOC_PARSE_RULE_INIT;
  676. parser.rule_stack_top = 0;
  677. parser.rule_stack = m_new(rule_stack_t, parser.rule_stack_alloc);
  678. parser.result_stack_alloc = MICROPY_ALLOC_PARSE_RESULT_INIT;
  679. parser.result_stack_top = 0;
  680. parser.result_stack = m_new(mp_parse_node_t, parser.result_stack_alloc);
  681. parser.lexer = lex;
  682. parser.tree.chunk = NULL;
  683. parser.cur_chunk = NULL;
  684. #if MICROPY_COMP_CONST
  685. mp_map_init(&parser.consts, 0);
  686. #endif
  687. // work out the top-level rule to use, and push it on the stack
  688. size_t top_level_rule;
  689. switch (input_kind) {
  690. case MP_PARSE_SINGLE_INPUT: top_level_rule = RULE_single_input; break;
  691. case MP_PARSE_EVAL_INPUT: top_level_rule = RULE_eval_input; break;
  692. default: top_level_rule = RULE_file_input;
  693. }
  694. push_rule(&parser, lex->tok_line, rules[top_level_rule], 0);
  695. // parse!
  696. size_t n, i; // state for the current rule
  697. size_t rule_src_line; // source line for the first token matched by the current rule
  698. bool backtrack = false;
  699. const rule_t *rule = NULL;
  700. for (;;) {
  701. next_rule:
  702. if (parser.rule_stack_top == 0) {
  703. break;
  704. }
  705. pop_rule(&parser, &rule, &i, &rule_src_line);
  706. n = rule->act & RULE_ACT_ARG_MASK;
  707. /*
  708. // debugging
  709. printf("depth=%d ", parser.rule_stack_top);
  710. for (int j = 0; j < parser.rule_stack_top; ++j) {
  711. printf(" ");
  712. }
  713. printf("%s n=%d i=%d bt=%d\n", rule->rule_name, n, i, backtrack);
  714. */
  715. switch (rule->act & RULE_ACT_KIND_MASK) {
  716. case RULE_ACT_OR:
  717. if (i > 0 && !backtrack) {
  718. goto next_rule;
  719. } else {
  720. backtrack = false;
  721. }
  722. for (; i < n; ++i) {
  723. uint16_t kind = rule->arg[i] & RULE_ARG_KIND_MASK;
  724. if (kind == RULE_ARG_TOK) {
  725. if (lex->tok_kind == (rule->arg[i] & RULE_ARG_ARG_MASK)) {
  726. push_result_token(&parser, rule);
  727. mp_lexer_to_next(lex);
  728. goto next_rule;
  729. }
  730. } else {
  731. assert(kind == RULE_ARG_RULE);
  732. if (i + 1 < n) {
  733. push_rule(&parser, rule_src_line, rule, i + 1); // save this or-rule
  734. }
  735. push_rule_from_arg(&parser, rule->arg[i]); // push child of or-rule
  736. goto next_rule;
  737. }
  738. }
  739. backtrack = true;
  740. break;
  741. case RULE_ACT_AND: {
  742. // failed, backtrack if we can, else syntax error
  743. if (backtrack) {
  744. assert(i > 0);
  745. if ((rule->arg[i - 1] & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE) {
  746. // an optional rule that failed, so continue with next arg
  747. push_result_node(&parser, MP_PARSE_NODE_NULL);
  748. backtrack = false;
  749. } else {
  750. // a mandatory rule that failed, so propagate backtrack
  751. if (i > 1) {
  752. // already eaten tokens so can't backtrack
  753. goto syntax_error;
  754. } else {
  755. goto next_rule;
  756. }
  757. }
  758. }
  759. // progress through the rule
  760. for (; i < n; ++i) {
  761. if ((rule->arg[i] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  762. // need to match a token
  763. mp_token_kind_t tok_kind = rule->arg[i] & RULE_ARG_ARG_MASK;
  764. if (lex->tok_kind == tok_kind) {
  765. // matched token
  766. if (tok_kind == MP_TOKEN_NAME) {
  767. push_result_token(&parser, rule);
  768. }
  769. mp_lexer_to_next(lex);
  770. } else {
  771. // failed to match token
  772. if (i > 0) {
  773. // already eaten tokens so can't backtrack
  774. goto syntax_error;
  775. } else {
  776. // this rule failed, so backtrack
  777. backtrack = true;
  778. goto next_rule;
  779. }
  780. }
  781. } else {
  782. push_rule(&parser, rule_src_line, rule, i + 1); // save this and-rule
  783. push_rule_from_arg(&parser, rule->arg[i]); // push child of and-rule
  784. goto next_rule;
  785. }
  786. }
  787. assert(i == n);
  788. // matched the rule, so now build the corresponding parse_node
  789. #if !MICROPY_ENABLE_DOC_STRING
  790. // this code discards lonely statements, such as doc strings
  791. if (input_kind != MP_PARSE_SINGLE_INPUT && rule->rule_id == RULE_expr_stmt && peek_result(&parser, 0) == MP_PARSE_NODE_NULL) {
  792. mp_parse_node_t p = peek_result(&parser, 1);
  793. if ((MP_PARSE_NODE_IS_LEAF(p) && !MP_PARSE_NODE_IS_ID(p))
  794. || MP_PARSE_NODE_IS_STRUCT_KIND(p, RULE_const_object)) {
  795. pop_result(&parser); // MP_PARSE_NODE_NULL
  796. pop_result(&parser); // const expression (leaf or RULE_const_object)
  797. // Pushing the "pass" rule here will overwrite any RULE_const_object
  798. // entry that was on the result stack, allowing the GC to reclaim
  799. // the memory from the const object when needed.
  800. push_result_rule(&parser, rule_src_line, rules[RULE_pass_stmt], 0);
  801. break;
  802. }
  803. }
  804. #endif
  805. // count number of arguments for the parse node
  806. i = 0;
  807. size_t num_not_nil = 0;
  808. for (size_t x = n; x > 0;) {
  809. --x;
  810. if ((rule->arg[x] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  811. mp_token_kind_t tok_kind = rule->arg[x] & RULE_ARG_ARG_MASK;
  812. if (tok_kind == MP_TOKEN_NAME) {
  813. // only tokens which were names are pushed to stack
  814. i += 1;
  815. num_not_nil += 1;
  816. }
  817. } else {
  818. // rules are always pushed
  819. if (peek_result(&parser, i) != MP_PARSE_NODE_NULL) {
  820. num_not_nil += 1;
  821. }
  822. i += 1;
  823. }
  824. }
  825. if (num_not_nil == 1 && (rule->act & RULE_ACT_ALLOW_IDENT)) {
  826. // this rule has only 1 argument and should not be emitted
  827. mp_parse_node_t pn = MP_PARSE_NODE_NULL;
  828. for (size_t x = 0; x < i; ++x) {
  829. mp_parse_node_t pn2 = pop_result(&parser);
  830. if (pn2 != MP_PARSE_NODE_NULL) {
  831. pn = pn2;
  832. }
  833. }
  834. push_result_node(&parser, pn);
  835. } else {
  836. // this rule must be emitted
  837. if (rule->act & RULE_ACT_ADD_BLANK) {
  838. // and add an extra blank node at the end (used by the compiler to store data)
  839. push_result_node(&parser, MP_PARSE_NODE_NULL);
  840. i += 1;
  841. }
  842. push_result_rule(&parser, rule_src_line, rule, i);
  843. }
  844. break;
  845. }
  846. default: {
  847. assert((rule->act & RULE_ACT_KIND_MASK) == RULE_ACT_LIST);
  848. // n=2 is: item item*
  849. // n=1 is: item (sep item)*
  850. // n=3 is: item (sep item)* [sep]
  851. bool had_trailing_sep;
  852. if (backtrack) {
  853. list_backtrack:
  854. had_trailing_sep = false;
  855. if (n == 2) {
  856. if (i == 1) {
  857. // fail on item, first time round; propagate backtrack
  858. goto next_rule;
  859. } else {
  860. // fail on item, in later rounds; finish with this rule
  861. backtrack = false;
  862. }
  863. } else {
  864. if (i == 1) {
  865. // fail on item, first time round; propagate backtrack
  866. goto next_rule;
  867. } else if ((i & 1) == 1) {
  868. // fail on item, in later rounds; have eaten tokens so can't backtrack
  869. if (n == 3) {
  870. // list allows trailing separator; finish parsing list
  871. had_trailing_sep = true;
  872. backtrack = false;
  873. } else {
  874. // list doesn't allowing trailing separator; fail
  875. goto syntax_error;
  876. }
  877. } else {
  878. // fail on separator; finish parsing list
  879. backtrack = false;
  880. }
  881. }
  882. } else {
  883. for (;;) {
  884. size_t arg = rule->arg[i & 1 & n];
  885. if ((arg & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  886. if (lex->tok_kind == (arg & RULE_ARG_ARG_MASK)) {
  887. if (i & 1 & n) {
  888. // separators which are tokens are not pushed to result stack
  889. } else {
  890. push_result_token(&parser, rule);
  891. }
  892. mp_lexer_to_next(lex);
  893. // got element of list, so continue parsing list
  894. i += 1;
  895. } else {
  896. // couldn't get element of list
  897. i += 1;
  898. backtrack = true;
  899. goto list_backtrack;
  900. }
  901. } else {
  902. assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE);
  903. push_rule(&parser, rule_src_line, rule, i + 1); // save this list-rule
  904. push_rule_from_arg(&parser, arg); // push child of list-rule
  905. goto next_rule;
  906. }
  907. }
  908. }
  909. assert(i >= 1);
  910. // compute number of elements in list, result in i
  911. i -= 1;
  912. if ((n & 1) && (rule->arg[1] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
  913. // don't count separators when they are tokens
  914. i = (i + 1) / 2;
  915. }
  916. if (i == 1) {
  917. // list matched single item
  918. if (had_trailing_sep) {
  919. // if there was a trailing separator, make a list of a single item
  920. push_result_rule(&parser, rule_src_line, rule, i);
  921. } else {
  922. // just leave single item on stack (ie don't wrap in a list)
  923. }
  924. } else {
  925. push_result_rule(&parser, rule_src_line, rule, i);
  926. }
  927. break;
  928. }
  929. }
  930. }
  931. #if MICROPY_COMP_CONST
  932. mp_map_deinit(&parser.consts);
  933. #endif
  934. // truncate final chunk and link into chain of chunks
  935. if (parser.cur_chunk != NULL) {
  936. (void)m_renew_maybe(byte, parser.cur_chunk,
  937. sizeof(mp_parse_chunk_t) + parser.cur_chunk->alloc,
  938. sizeof(mp_parse_chunk_t) + parser.cur_chunk->union_.used,
  939. false);
  940. parser.cur_chunk->alloc = parser.cur_chunk->union_.used;
  941. parser.cur_chunk->union_.next = parser.tree.chunk;
  942. parser.tree.chunk = parser.cur_chunk;
  943. }
  944. if (
  945. lex->tok_kind != MP_TOKEN_END // check we are at the end of the token stream
  946. || parser.result_stack_top == 0 // check that we got a node (can fail on empty input)
  947. ) {
  948. syntax_error:;
  949. mp_obj_t exc;
  950. if (lex->tok_kind == MP_TOKEN_INDENT) {
  951. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  952. "unexpected indent");
  953. } else if (lex->tok_kind == MP_TOKEN_DEDENT_MISMATCH) {
  954. exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
  955. "unindent does not match any outer indentation level");
  956. } else {
  957. exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
  958. "invalid syntax");
  959. }
  960. // add traceback to give info about file name and location
  961. // we don't have a 'block' name, so just pass the NULL qstr to indicate this
  962. mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTR_NULL);
  963. nlr_raise(exc);
  964. }
  965. // get the root parse node that we created
  966. assert(parser.result_stack_top == 1);
  967. parser.tree.root = parser.result_stack[0];
  968. // free the memory that we don't need anymore
  969. m_del(rule_stack_t, parser.rule_stack, parser.rule_stack_alloc);
  970. m_del(mp_parse_node_t, parser.result_stack, parser.result_stack_alloc);
  971. // we also free the lexer on behalf of the caller
  972. mp_lexer_free(lex);
  973. return parser.tree;
  974. }
  975. void mp_parse_tree_clear(mp_parse_tree_t *tree) {
  976. mp_parse_chunk_t *chunk = tree->chunk;
  977. while (chunk != NULL) {
  978. mp_parse_chunk_t *next = chunk->union_.next;
  979. m_del(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc);
  980. chunk = next;
  981. }
  982. }
  983. #endif // MICROPY_ENABLE_COMPILER