blob: 94a5a5d9cab6849668ea0f14a7f1f83756e36b68 [file] [log] [blame]
Damien429d7192013-10-04 19:53:11 +01001#include <unistd.h>
2#include <stdlib.h>
3#include <stdint.h>
4#include <stdio.h>
5#include <ctype.h>
6#include <string.h>
7#include <assert.h>
8
9#include "misc.h"
10#include "lexer.h"
11#include "machine.h"
12#include "parse.h"
13
14#define RULE_ACT_KIND_MASK (0xf0)
15#define RULE_ACT_ARG_MASK (0x0f)
16#define RULE_ACT_OR (0x10)
17#define RULE_ACT_AND (0x20)
18#define RULE_ACT_LIST (0x30)
19
20#define RULE_ARG_BLANK (0x0000)
21#define RULE_ARG_KIND_MASK (0xf000)
22#define RULE_ARG_ARG_MASK (0x0fff)
23#define RULE_ARG_TOK (0x1000)
24#define RULE_ARG_RULE (0x2000)
25#define RULE_ARG_OPT_TOK (0x3000)
26#define RULE_ARG_OPT_RULE (0x4000)
27
28// (un)comment to use rule names; for debugging
29//#define USE_RULE_NAME (1)
30
31typedef struct _rule_t {
32 byte rule_id;
33 byte act;
34#ifdef USE_RULE_NAME
35 const char *rule_name;
36#endif
37 uint16_t arg[];
38} rule_t;
39
40enum {
41 RULE_none = 0,
42#define DEF_RULE(rule, comp, kind, arg...) RULE_##rule,
43#include "grammar.h"
44#undef DEF_RULE
45 RULE_maximum_number_of,
46};
47
48#define or(n) (RULE_ACT_OR | n)
49#define and(n) (RULE_ACT_AND | n)
50#define one_or_more (RULE_ACT_LIST | 2)
51#define list (RULE_ACT_LIST | 1)
52#define list_with_end (RULE_ACT_LIST | 3)
53#define tok(t) (RULE_ARG_TOK | PY_TOKEN_##t)
54#define rule(r) (RULE_ARG_RULE | RULE_##r)
55#define opt_tok(t) (RULE_ARG_OPT_TOK | PY_TOKEN_##t)
56#define opt_rule(r) (RULE_ARG_OPT_RULE | RULE_##r)
57#ifdef USE_RULE_NAME
58#define DEF_RULE(rule, comp, kind, arg...) static rule_t rule_##rule = { RULE_##rule, kind, #rule, { arg } };
59#else
60#define DEF_RULE(rule, comp, kind, arg...) static rule_t rule_##rule = { RULE_##rule, kind, { arg } };
61#endif
62#include "grammar.h"
63#undef or
64#undef and
65#undef list
66#undef list_with_end
67#undef tok
68#undef rule
69#undef opt_tok
70#undef opt_rule
71#undef one_or_more
72#undef DEF_RULE
73
74static rule_t *rules[] = {
75 NULL,
76#define DEF_RULE(rule, comp, kind, arg...) &rule_##rule,
77#include "grammar.h"
78#undef DEF_RULE
79};
80
81typedef struct _rule_stack_t {
82 byte rule_id;
83 int32_t arg_i; // what should be the size and signedness?
84} rule_stack_t;
85
86typedef struct _parser_t {
87 uint rule_stack_alloc;
88 uint rule_stack_top;
89 rule_stack_t *rule_stack;
90
91 uint result_stack_top;
92 py_parse_node_t *result_stack;
93} parser_t;
94
95static void push_rule(parser_t *parser, rule_t *rule, int arg_i) {
96 if (parser->rule_stack_top >= parser->rule_stack_alloc) {
97 parser->rule_stack_alloc *= 2;
98 parser->rule_stack = m_renew(rule_stack_t, parser->rule_stack, parser->rule_stack_alloc);
99 }
100 parser->rule_stack[parser->rule_stack_top].rule_id = rule->rule_id;
101 parser->rule_stack[parser->rule_stack_top].arg_i = arg_i;
102 parser->rule_stack_top += 1;
103}
104
105static void push_rule_from_arg(parser_t *parser, uint arg) {
106 assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE || (arg & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE);
107 uint rule_id = arg & RULE_ARG_ARG_MASK;
108 assert(rule_id < RULE_maximum_number_of);
109 push_rule(parser, rules[rule_id], 0);
110}
111
112static void pop_rule(parser_t *parser, rule_t **rule, uint *arg_i) {
113 parser->rule_stack_top -= 1;
114 *rule = rules[parser->rule_stack[parser->rule_stack_top].rule_id];
115 *arg_i = parser->rule_stack[parser->rule_stack_top].arg_i;
116}
117
118py_parse_node_t py_parse_node_new_leaf(machine_int_t kind, machine_int_t arg) {
119 return (py_parse_node_t)(kind | (arg << 4));
120}
121
122int num_parse_nodes_allocated = 0;
123py_parse_node_struct_t *parse_node_new_struct(int rule_id, int num_args) {
124 py_parse_node_struct_t *pn = m_malloc(sizeof(py_parse_node_struct_t) + num_args * sizeof(py_parse_node_t));
125 pn->source = 0; // TODO
126 pn->kind_num_nodes = (rule_id & 0xff) | (num_args << 8);
127 num_parse_nodes_allocated += 1;
128 return pn;
129}
130
131void parse_node_show(py_parse_node_t pn, int indent) {
132 for (int i = 0; i < indent; i++) {
133 printf(" ");
134 }
135 if (PY_PARSE_NODE_IS_NULL(pn)) {
136 printf("NULL\n");
137 } else if (PY_PARSE_NODE_IS_LEAF(pn)) {
138 int arg = PY_PARSE_NODE_LEAF_ARG(pn);
139 switch (PY_PARSE_NODE_LEAF_KIND(pn)) {
140 case PY_PARSE_NODE_ID: printf("id(%s)\n", qstr_str(arg)); break;
141 case PY_PARSE_NODE_SMALL_INT: printf("int(%d)\n", arg); break;
142 case PY_PARSE_NODE_INTEGER: printf("int(%s)\n", qstr_str(arg)); break;
143 case PY_PARSE_NODE_DECIMAL: printf("dec(%s)\n", qstr_str(arg)); break;
144 case PY_PARSE_NODE_STRING: printf("str(%s)\n", qstr_str(arg)); break;
145 case PY_PARSE_NODE_BYTES: printf("bytes(%s)\n", qstr_str(arg)); break;
146 case PY_PARSE_NODE_TOKEN: printf("tok(%d)\n", arg); break;
147 default: assert(0);
148 }
149 } else {
150 py_parse_node_struct_t *pns2 = (py_parse_node_struct_t*)pn;
151 int n = pns2->kind_num_nodes >> 8;
152#ifdef USE_RULE_NAME
153 printf("%s(%d) (n=%d)\n", rules[PY_PARSE_NODE_STRUCT_KIND(pns2)]->rule_name, PY_PARSE_NODE_STRUCT_KIND(pns2), n);
154#else
155 printf("rule(%u) (n=%d)\n", (uint)PY_PARSE_NODE_STRUCT_KIND(pns2), n);
156#endif
157 for (int i = 0; i < n; i++) {
158 parse_node_show(pns2->nodes[i], indent + 2);
159 }
160 }
161}
162
163/*
164static void result_stack_show(parser_t *parser) {
165 printf("result stack, most recent first\n");
166 for (int i = parser->result_stack_top - 1; i >= 0; i--) {
167 parse_node_show(parser->result_stack[i], 0);
168 }
169}
170*/
171
172static py_parse_node_t pop_result(parser_t *parser) {
173 assert(parser->result_stack_top > 0);
174 return parser->result_stack[--parser->result_stack_top];
175}
176
177static py_parse_node_t peek_result(parser_t *parser, int pos) {
178 assert(parser->result_stack_top > pos);
179 return parser->result_stack[parser->result_stack_top - 1 - pos];
180}
181
182static void push_result_node(parser_t *parser, py_parse_node_t pn) {
183 parser->result_stack[parser->result_stack_top++] = pn;
184}
185
186static void push_result_token(parser_t *parser, const py_lexer_t *lex) {
187 const py_token_t *tok = py_lexer_cur(lex);
188 py_parse_node_t pn;
189 if (tok->kind == PY_TOKEN_NAME) {
190 pn = py_parse_node_new_leaf(PY_PARSE_NODE_ID, qstr_from_strn_copy(tok->str, tok->len));
191 } else if (tok->kind == PY_TOKEN_NUMBER) {
192 bool dec = false;
193 bool small_int = true;
194 int int_val = 0;
195 int len = tok->len;
196 const char *str = tok->str;
197 int base = 10;
198 int i = 0;
199 if (len >= 3 && str[0] == '0') {
200 if (str[1] == 'o' || str[1] == 'O') {
201 // octal
202 base = 8;
203 i = 2;
204 } else if (str[1] == 'x' || str[1] == 'X') {
205 // hexadecimal
206 base = 16;
207 i = 2;
208 } else if (str[1] == 'b' || str[1] == 'B') {
209 // binary
210 base = 2;
211 i = 2;
212 }
213 }
214 for (; i < len; i++) {
215 if (g_unichar_isdigit(str[i]) && str[i] - '0' < base) {
216 int_val = base * int_val + str[i] - '0';
217 } else if (base == 16 && 'a' <= str[i] && str[i] <= 'f') {
218 int_val = base * int_val + str[i] - 'a' + 10;
219 } else if (base == 16 && 'F' <= str[i] && str[i] <= 'F') {
220 int_val = base * int_val + str[i] - 'A' + 10;
221 } else if (str[i] == '.' || str[i] == 'e' || str[i] == 'E') {
222 dec = true;
223 break;
224 } else {
225 small_int = false;
226 break;
227 }
228 }
229 if (dec) {
230 pn = py_parse_node_new_leaf(PY_PARSE_NODE_DECIMAL, qstr_from_strn_copy(str, len));
231 } else if (small_int && -0x10000 <= int_val && int_val <= 0xffff) {
232 pn = py_parse_node_new_leaf(PY_PARSE_NODE_SMALL_INT, int_val);
233 } else {
234 pn = py_parse_node_new_leaf(PY_PARSE_NODE_INTEGER, qstr_from_strn_copy(str, len));
235 }
236 } else if (tok->kind == PY_TOKEN_STRING) {
237 pn = py_parse_node_new_leaf(PY_PARSE_NODE_STRING, qstr_from_strn_copy(tok->str, tok->len));
238 } else if (tok->kind == PY_TOKEN_BYTES) {
239 pn = py_parse_node_new_leaf(PY_PARSE_NODE_BYTES, qstr_from_strn_copy(tok->str, tok->len));
240 } else {
241 pn = py_parse_node_new_leaf(PY_PARSE_NODE_TOKEN, tok->kind);
242 }
243 push_result_node(parser, pn);
244}
245
246static void push_result_rule(parser_t *parser, rule_t *rule, int num_args) {
247 py_parse_node_struct_t *pn = parse_node_new_struct(rule->rule_id, num_args);
248 for (int i = num_args; i > 0; i--) {
249 pn->nodes[i - 1] = pop_result(parser);
250 }
251 push_result_node(parser, (py_parse_node_t)pn);
252}
253
254py_parse_node_t py_parse(py_lexer_t *lex, int wanted_rule) {
255 wanted_rule = RULE_file_input;
256 parser_t *parser = m_new(parser_t, 1);
257 parser->rule_stack_alloc = 64;
258 parser->rule_stack_top = 0;
259 parser->rule_stack = m_new(rule_stack_t, parser->rule_stack_alloc);
260
261 parser->result_stack = m_new(py_parse_node_t, 1000);
262 parser->result_stack_top = 0;
263
264 push_rule(parser, rules[wanted_rule], 0);
265
266 uint n, i;
267 bool backtrack = false;
268 rule_t *rule;
269 py_token_kind_t tok_kind;
270 bool emit_rule;
271 bool had_trailing_sep;
272
273 for (;;) {
274 next_rule:
275 if (parser->rule_stack_top == 0) {
276 break;
277 }
278
279 pop_rule(parser, &rule, &i);
280 n = rule->act & RULE_ACT_ARG_MASK;
281
282 /*
283 // debugging
284 printf("depth=%d ", parser->rule_stack_top);
285 for (int j = 0; j < parser->rule_stack_top; ++j) {
286 printf(" ");
287 }
288 printf("%s n=%d i=%d bt=%d\n", rule->rule_name, n, i, backtrack);
289 */
290
291 switch (rule->act & RULE_ACT_KIND_MASK) {
292 case RULE_ACT_OR:
293 if (i > 0 && !backtrack) {
294 goto next_rule;
295 } else {
296 backtrack = false;
297 }
298 for (; i < n - 1; ++i) {
299 switch (rule->arg[i] & RULE_ARG_KIND_MASK) {
300 case RULE_ARG_TOK:
301 if (py_lexer_is_kind(lex, rule->arg[i] & RULE_ARG_ARG_MASK)) {
302 push_result_token(parser, lex);
303 py_lexer_to_next(lex);
304 goto next_rule;
305 }
306 break;
307 case RULE_ARG_RULE:
308 push_rule(parser, rule, i + 1);
309 push_rule_from_arg(parser, rule->arg[i]);
310 goto next_rule;
311 default:
312 assert(0);
313 }
314 }
315 if ((rule->arg[i] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
316 if (py_lexer_is_kind(lex, rule->arg[i] & RULE_ARG_ARG_MASK)) {
317 push_result_token(parser, lex);
318 py_lexer_to_next(lex);
319 } else {
320 backtrack = true;
321 goto next_rule;
322 }
323 } else {
324 push_rule_from_arg(parser, rule->arg[i]);
325 }
326 break;
327
328 case RULE_ACT_AND:
329
330 // failed, backtrack if we can, else syntax error
331 if (backtrack) {
332 assert(i > 0);
333 if ((rule->arg[i - 1] & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE) {
334 // an optional rule that failed, so continue with next arg
335 push_result_node(parser, PY_PARSE_NODE_NULL);
336 backtrack = false;
337 } else {
338 // a mandatory rule that failed, so propagate backtrack
339 if (i > 1) {
340 // already eaten tokens so can't backtrack
341 goto syntax_error;
342 } else {
343 goto next_rule;
344 }
345 }
346 }
347
348 // progress through the rule
349 for (; i < n; ++i) {
350 switch (rule->arg[i] & RULE_ARG_KIND_MASK) {
351 case RULE_ARG_TOK:
352 // need to match a token
353 tok_kind = rule->arg[i] & RULE_ARG_ARG_MASK;
354 if (py_lexer_is_kind(lex, tok_kind)) {
355 // matched token
356 if (tok_kind == PY_TOKEN_NAME) {
357 push_result_token(parser, lex);
358 }
359 py_lexer_to_next(lex);
360 } else {
361 // failed to match token
362 if (i > 0) {
363 // already eaten tokens so can't backtrack
364 goto syntax_error;
365 } else {
366 // this rule failed, so backtrack
367 backtrack = true;
368 goto next_rule;
369 }
370 }
371 break;
372 case RULE_ARG_RULE:
373 //if (i + 1 < n) {
374 push_rule(parser, rule, i + 1);
375 //}
376 push_rule_from_arg(parser, rule->arg[i]);
377 goto next_rule;
378 case RULE_ARG_OPT_RULE:
379 push_rule(parser, rule, i + 1);
380 push_rule_from_arg(parser, rule->arg[i]);
381 goto next_rule;
382 default:
383 assert(0);
384 }
385 }
386
387 assert(i == n);
388
389 // matched the rule, so now build the corresponding parse_node
390
391 // count number of arguments for the parse_node
392 i = 0;
393 emit_rule = false;
394 for (int x = 0; x < n; ++x) {
395 if ((rule->arg[x] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
396 tok_kind = rule->arg[x] & RULE_ARG_ARG_MASK;
397 if (tok_kind >= PY_TOKEN_NAME) {
398 emit_rule = true;
399 }
400 if (tok_kind == PY_TOKEN_NAME) {
401 // only tokens which were names are pushed to stack
402 i += 1;
403 }
404 } else {
405 // rules are always pushed
406 i += 1;
407 }
408 }
409
410 // always emit these rules, even if they have only 1 argument
411 if (rule->rule_id == RULE_expr_stmt || rule->rule_id == RULE_yield_stmt) {
412 emit_rule = true;
413 }
414
415 // never emit these rules if they have only 1 argument
416 // NOTE: can't put atom_paren here because we need it to distinguisg, for example, [a,b] from [(a,b)]
417 if (rule->rule_id == RULE_else_stmt || rule->rule_id == RULE_testlist_comp_3b || rule->rule_id == RULE_import_as_names_paren || rule->rule_id == RULE_typedargslist_colon || rule->rule_id == RULE_typedargslist_equal || rule->rule_id == RULE_dictorsetmaker_colon || rule->rule_id == RULE_classdef_2 || rule->rule_id == RULE_with_item_as || rule->rule_id == RULE_assert_stmt_extra || rule->rule_id == RULE_as_name || rule->rule_id == RULE_raise_stmt_from || rule->rule_id == RULE_vfpdef) {
418 emit_rule = false;
419 }
420
421 // always emit these rules, and add an extra blank node at the end (to be used by the compiler to store data)
422 if (rule->rule_id == RULE_funcdef || rule->rule_id == RULE_classdef || rule->rule_id == RULE_comp_for || rule->rule_id == RULE_lambdef || rule->rule_id == RULE_lambdef_nocond) {
423 emit_rule = true;
424 push_result_node(parser, PY_PARSE_NODE_NULL);
425 i += 1;
426 }
427
428 int num_not_nil = 0;
429 for (int x = 0; x < i; ++x) {
430 if (peek_result(parser, x) != PY_PARSE_NODE_NULL) {
431 num_not_nil += 1;
432 }
433 }
434 //printf("done and %s n=%d i=%d notnil=%d\n", rule->rule_name, n, i, num_not_nil);
435 if (emit_rule) {
436 push_result_rule(parser, rule, i);
437 } else if (num_not_nil == 0) {
438 push_result_rule(parser, rule, i); // needed for, eg, atom_paren, testlist_comp_3b
439 //result_stack_show(parser);
440 //assert(0);
441 } else if (num_not_nil == 1) {
442 // single result, leave it on stack
443 py_parse_node_t pn = PY_PARSE_NODE_NULL;
444 for (int x = 0; x < i; ++x) {
445 py_parse_node_t pn2 = pop_result(parser);
446 if (pn2 != PY_PARSE_NODE_NULL) {
447 pn = pn2;
448 }
449 }
450 push_result_node(parser, pn);
451 } else {
452 push_result_rule(parser, rule, i);
453 }
454 break;
455
456 case RULE_ACT_LIST:
457 // n=2 is: item item*
458 // n=1 is: item (sep item)*
459 // n=3 is: item (sep item)* [sep]
460 if (backtrack) {
461 list_backtrack:
462 had_trailing_sep = false;
463 if (n == 2) {
464 if (i == 1) {
465 // fail on item, first time round; propagate backtrack
466 goto next_rule;
467 } else {
468 // fail on item, in later rounds; finish with this rule
469 backtrack = false;
470 }
471 } else {
472 if (i == 1) {
473 // fail on item, first time round; propagate backtrack
474 goto next_rule;
475 } else if ((i & 1) == 1) {
476 // fail on item, in later rounds; have eaten tokens so can't backtrack
477 if (n == 3) {
478 // list allows trailing separator; finish parsing list
479 had_trailing_sep = true;
480 backtrack = false;
481 } else {
482 // list doesn't allowing trailing separator; fail
483 goto syntax_error;
484 }
485 } else {
486 // fail on separator; finish parsing list
487 backtrack = false;
488 }
489 }
490 } else {
491 for (;;) {
492 uint arg = rule->arg[i & 1 & n];
493 switch (arg & RULE_ARG_KIND_MASK) {
494 case RULE_ARG_TOK:
495 if (py_lexer_is_kind(lex, arg & RULE_ARG_ARG_MASK)) {
496 if (i & 1 & n) {
497 // separators which are tokens are not pushed to result stack
498 } else {
499 push_result_token(parser, lex);
500 }
501 py_lexer_to_next(lex);
502 // got element of list, so continue parsing list
503 i += 1;
504 } else {
505 // couldn't get element of list
506 i += 1;
507 backtrack = true;
508 goto list_backtrack;
509 }
510 break;
511 case RULE_ARG_RULE:
512 push_rule(parser, rule, i + 1);
513 push_rule_from_arg(parser, arg);
514 goto next_rule;
515 default:
516 assert(0);
517 }
518 }
519 }
520 assert(i >= 1);
521
522 // compute number of elements in list, result in i
523 i -= 1;
524 if ((n & 1) && (rule->arg[1] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
525 // don't count separators when they are tokens
526 i = (i + 1) / 2;
527 }
528
529 if (i == 1) {
530 // list matched single item
531 if (had_trailing_sep) {
532 // if there was a trailing separator, make a list of a single item
533 push_result_rule(parser, rule, i);
534 } else {
535 // just leave single item on stack (ie don't wrap in a list)
536 }
537 } else {
538 //printf("done list %s %d %d\n", rule->rule_name, n, i);
539 push_result_rule(parser, rule, i);
540 }
541 break;
542
543 default:
544 assert(0);
545 }
546 }
547 if (!py_lexer_is_kind(lex, PY_TOKEN_END)) {
548 py_lexer_show_error(lex, "unexpected token at end:");
549 py_token_show(py_lexer_cur(lex));
550 }
551 //printf("--------------\n");
552 //result_stack_show(parser);
553 assert(parser->result_stack_top == 1);
554 //printf("maximum depth: %d\n", parser->rule_stack_alloc);
555 //printf("number of parse nodes allocated: %d\n", num_parse_nodes_allocated);
556 return parser->result_stack[0];
557
558syntax_error:
559 py_lexer_show_error(lex, "syntax error:");
560#ifdef USE_RULE_NAME
561 py_lexer_show_error(lex, rule->rule_name);
562#endif
563 py_token_show(py_lexer_cur(lex));
564 return PY_PARSE_NODE_NULL;
565}