blob: 124d00ffebda3862f800452e28bb54656c5d3570 [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));
Damien5fa5ae42013-10-06 00:13:15 +0100231 } else if (small_int && -0x800000 <= int_val && int_val <= 0x7fffff) { // XXX check this range formula!
Damien429d7192013-10-04 19:53:11 +0100232 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)]
Damienb14de212013-10-06 00:28:28 +0100417 // TODO possibly put varargslist_name, varargslist_equal here as well
418 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_name || 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) {
Damien429d7192013-10-04 19:53:11 +0100419 emit_rule = false;
420 }
421
422 // always emit these rules, and add an extra blank node at the end (to be used by the compiler to store data)
423 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) {
424 emit_rule = true;
425 push_result_node(parser, PY_PARSE_NODE_NULL);
426 i += 1;
427 }
428
429 int num_not_nil = 0;
430 for (int x = 0; x < i; ++x) {
431 if (peek_result(parser, x) != PY_PARSE_NODE_NULL) {
432 num_not_nil += 1;
433 }
434 }
435 //printf("done and %s n=%d i=%d notnil=%d\n", rule->rule_name, n, i, num_not_nil);
436 if (emit_rule) {
437 push_result_rule(parser, rule, i);
438 } else if (num_not_nil == 0) {
439 push_result_rule(parser, rule, i); // needed for, eg, atom_paren, testlist_comp_3b
440 //result_stack_show(parser);
441 //assert(0);
442 } else if (num_not_nil == 1) {
443 // single result, leave it on stack
444 py_parse_node_t pn = PY_PARSE_NODE_NULL;
445 for (int x = 0; x < i; ++x) {
446 py_parse_node_t pn2 = pop_result(parser);
447 if (pn2 != PY_PARSE_NODE_NULL) {
448 pn = pn2;
449 }
450 }
451 push_result_node(parser, pn);
452 } else {
453 push_result_rule(parser, rule, i);
454 }
455 break;
456
457 case RULE_ACT_LIST:
458 // n=2 is: item item*
459 // n=1 is: item (sep item)*
460 // n=3 is: item (sep item)* [sep]
461 if (backtrack) {
462 list_backtrack:
463 had_trailing_sep = false;
464 if (n == 2) {
465 if (i == 1) {
466 // fail on item, first time round; propagate backtrack
467 goto next_rule;
468 } else {
469 // fail on item, in later rounds; finish with this rule
470 backtrack = false;
471 }
472 } else {
473 if (i == 1) {
474 // fail on item, first time round; propagate backtrack
475 goto next_rule;
476 } else if ((i & 1) == 1) {
477 // fail on item, in later rounds; have eaten tokens so can't backtrack
478 if (n == 3) {
479 // list allows trailing separator; finish parsing list
480 had_trailing_sep = true;
481 backtrack = false;
482 } else {
483 // list doesn't allowing trailing separator; fail
484 goto syntax_error;
485 }
486 } else {
487 // fail on separator; finish parsing list
488 backtrack = false;
489 }
490 }
491 } else {
492 for (;;) {
493 uint arg = rule->arg[i & 1 & n];
494 switch (arg & RULE_ARG_KIND_MASK) {
495 case RULE_ARG_TOK:
496 if (py_lexer_is_kind(lex, arg & RULE_ARG_ARG_MASK)) {
497 if (i & 1 & n) {
498 // separators which are tokens are not pushed to result stack
499 } else {
500 push_result_token(parser, lex);
501 }
502 py_lexer_to_next(lex);
503 // got element of list, so continue parsing list
504 i += 1;
505 } else {
506 // couldn't get element of list
507 i += 1;
508 backtrack = true;
509 goto list_backtrack;
510 }
511 break;
512 case RULE_ARG_RULE:
513 push_rule(parser, rule, i + 1);
514 push_rule_from_arg(parser, arg);
515 goto next_rule;
516 default:
517 assert(0);
518 }
519 }
520 }
521 assert(i >= 1);
522
523 // compute number of elements in list, result in i
524 i -= 1;
525 if ((n & 1) && (rule->arg[1] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
526 // don't count separators when they are tokens
527 i = (i + 1) / 2;
528 }
529
530 if (i == 1) {
531 // list matched single item
532 if (had_trailing_sep) {
533 // if there was a trailing separator, make a list of a single item
534 push_result_rule(parser, rule, i);
535 } else {
536 // just leave single item on stack (ie don't wrap in a list)
537 }
538 } else {
539 //printf("done list %s %d %d\n", rule->rule_name, n, i);
540 push_result_rule(parser, rule, i);
541 }
542 break;
543
544 default:
545 assert(0);
546 }
547 }
Damien91d387d2013-10-09 15:09:52 +0100548
549 // check we are at the end of the token stream
Damien429d7192013-10-04 19:53:11 +0100550 if (!py_lexer_is_kind(lex, PY_TOKEN_END)) {
Damien91d387d2013-10-09 15:09:52 +0100551 goto syntax_error;
Damien429d7192013-10-04 19:53:11 +0100552 }
Damien91d387d2013-10-09 15:09:52 +0100553
Damien429d7192013-10-04 19:53:11 +0100554 //printf("--------------\n");
555 //result_stack_show(parser);
556 assert(parser->result_stack_top == 1);
557 //printf("maximum depth: %d\n", parser->rule_stack_alloc);
558 //printf("number of parse nodes allocated: %d\n", num_parse_nodes_allocated);
559 return parser->result_stack[0];
560
561syntax_error:
Damien91d387d2013-10-09 15:09:52 +0100562 if (py_lexer_is_kind(lex, PY_TOKEN_INDENT)) {
563 py_lexer_show_error_pythonic(lex, "IndentationError: unexpected indent");
564 } else if (py_lexer_is_kind(lex, PY_TOKEN_DEDENT_MISMATCH)) {
565 py_lexer_show_error_pythonic(lex, "IndentationError: unindent does not match any outer indentation level");
566 } else {
567 py_lexer_show_error_pythonic(lex, "syntax error:");
Damien429d7192013-10-04 19:53:11 +0100568#ifdef USE_RULE_NAME
Damien91d387d2013-10-09 15:09:52 +0100569 py_lexer_show_error(lex, rule->rule_name);
Damien429d7192013-10-04 19:53:11 +0100570#endif
Damien91d387d2013-10-09 15:09:52 +0100571 py_token_show(py_lexer_cur(lex));
572 }
Damien429d7192013-10-04 19:53:11 +0100573 return PY_PARSE_NODE_NULL;
574}