1 #include <Python.h>
2 #include "pycore_ast.h" // _PyAST_Validate(),
3 #include <errcode.h>
4 #include "tokenizer.h"
5
6 #include "pegen.h"
7 #include "string_parser.h"
8
9 PyObject *
_PyPegen_new_type_comment(Parser * p,const char * s)10 _PyPegen_new_type_comment(Parser *p, const char *s)
11 {
12 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
13 if (res == NULL) {
14 return NULL;
15 }
16 if (_PyArena_AddPyObject(p->arena, res) < 0) {
17 Py_DECREF(res);
18 return NULL;
19 }
20 return res;
21 }
22
23 arg_ty
_PyPegen_add_type_comment_to_arg(Parser * p,arg_ty a,Token * tc)24 _PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
25 {
26 if (tc == NULL) {
27 return a;
28 }
29 const char *bytes = PyBytes_AsString(tc->bytes);
30 if (bytes == NULL) {
31 return NULL;
32 }
33 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
34 if (tco == NULL) {
35 return NULL;
36 }
37 return _PyAST_arg(a->arg, a->annotation, tco,
38 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
39 p->arena);
40 }
41
42 static int
init_normalization(Parser * p)43 init_normalization(Parser *p)
44 {
45 if (p->normalize) {
46 return 1;
47 }
48 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
49 if (!m)
50 {
51 return 0;
52 }
53 p->normalize = PyObject_GetAttrString(m, "normalize");
54 Py_DECREF(m);
55 if (!p->normalize)
56 {
57 return 0;
58 }
59 return 1;
60 }
61
62 /* Checks if the NOTEQUAL token is valid given the current parser flags
63 0 indicates success and nonzero indicates failure (an exception may be set) */
64 int
_PyPegen_check_barry_as_flufl(Parser * p,Token * t)65 _PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
66 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 const char* tok_str = PyBytes_AS_STRING(t->bytes);
70 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
71 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
73 }
74 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
75 return strcmp(tok_str, "!=");
76 }
77 return 0;
78 }
79
80 int
_PyPegen_check_legacy_stmt(Parser * p,expr_ty name)81 _PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
82 if (name->kind != Name_kind) {
83 return 0;
84 }
85 const char* candidates[2] = {"print", "exec"};
86 for (int i=0; i<2; i++) {
87 if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
88 return 1;
89 }
90 }
91 return 0;
92 }
93
94 PyObject *
_PyPegen_new_identifier(Parser * p,const char * n)95 _PyPegen_new_identifier(Parser *p, const char *n)
96 {
97 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
98 if (!id) {
99 goto error;
100 }
101 /* PyUnicode_DecodeUTF8 should always return a ready string. */
102 assert(PyUnicode_IS_READY(id));
103 /* Check whether there are non-ASCII characters in the
104 identifier; if so, normalize to NFKC. */
105 if (!PyUnicode_IS_ASCII(id))
106 {
107 PyObject *id2;
108 if (!init_normalization(p))
109 {
110 Py_DECREF(id);
111 goto error;
112 }
113 PyObject *form = PyUnicode_InternFromString("NFKC");
114 if (form == NULL)
115 {
116 Py_DECREF(id);
117 goto error;
118 }
119 PyObject *args[2] = {form, id};
120 id2 = _PyObject_FastCall(p->normalize, args, 2);
121 Py_DECREF(id);
122 Py_DECREF(form);
123 if (!id2) {
124 goto error;
125 }
126 if (!PyUnicode_Check(id2))
127 {
128 PyErr_Format(PyExc_TypeError,
129 "unicodedata.normalize() must return a string, not "
130 "%.200s",
131 _PyType_Name(Py_TYPE(id2)));
132 Py_DECREF(id2);
133 goto error;
134 }
135 id = id2;
136 }
137 PyUnicode_InternInPlace(&id);
138 if (_PyArena_AddPyObject(p->arena, id) < 0)
139 {
140 Py_DECREF(id);
141 goto error;
142 }
143 return id;
144
145 error:
146 p->error_indicator = 1;
147 return NULL;
148 }
149
150 static PyObject *
_create_dummy_identifier(Parser * p)151 _create_dummy_identifier(Parser *p)
152 {
153 return _PyPegen_new_identifier(p, "");
154 }
155
156 static inline Py_ssize_t
byte_offset_to_character_offset(PyObject * line,Py_ssize_t col_offset)157 byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
158 {
159 const char *str = PyUnicode_AsUTF8(line);
160 if (!str) {
161 return 0;
162 }
163 Py_ssize_t len = strlen(str);
164 if (col_offset > len + 1) {
165 col_offset = len + 1;
166 }
167 assert(col_offset >= 0);
168 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
169 if (!text) {
170 return 0;
171 }
172 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
173 Py_DECREF(text);
174 return size;
175 }
176
177 const char *
_PyPegen_get_expr_name(expr_ty e)178 _PyPegen_get_expr_name(expr_ty e)
179 {
180 assert(e != NULL);
181 switch (e->kind) {
182 case Attribute_kind:
183 return "attribute";
184 case Subscript_kind:
185 return "subscript";
186 case Starred_kind:
187 return "starred";
188 case Name_kind:
189 return "name";
190 case List_kind:
191 return "list";
192 case Tuple_kind:
193 return "tuple";
194 case Lambda_kind:
195 return "lambda";
196 case Call_kind:
197 return "function call";
198 case BoolOp_kind:
199 case BinOp_kind:
200 case UnaryOp_kind:
201 return "expression";
202 case GeneratorExp_kind:
203 return "generator expression";
204 case Yield_kind:
205 case YieldFrom_kind:
206 return "yield expression";
207 case Await_kind:
208 return "await expression";
209 case ListComp_kind:
210 return "list comprehension";
211 case SetComp_kind:
212 return "set comprehension";
213 case DictComp_kind:
214 return "dict comprehension";
215 case Dict_kind:
216 return "dict literal";
217 case Set_kind:
218 return "set display";
219 case JoinedStr_kind:
220 case FormattedValue_kind:
221 return "f-string expression";
222 case Constant_kind: {
223 PyObject *value = e->v.Constant.value;
224 if (value == Py_None) {
225 return "None";
226 }
227 if (value == Py_False) {
228 return "False";
229 }
230 if (value == Py_True) {
231 return "True";
232 }
233 if (value == Py_Ellipsis) {
234 return "ellipsis";
235 }
236 return "literal";
237 }
238 case Compare_kind:
239 return "comparison";
240 case IfExp_kind:
241 return "conditional expression";
242 case NamedExpr_kind:
243 return "named expression";
244 default:
245 PyErr_Format(PyExc_SystemError,
246 "unexpected expression in assignment %d (line %d)",
247 e->kind, e->lineno);
248 return NULL;
249 }
250 }
251
252 static int
raise_decode_error(Parser * p)253 raise_decode_error(Parser *p)
254 {
255 assert(PyErr_Occurred());
256 const char *errtype = NULL;
257 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
258 errtype = "unicode error";
259 }
260 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
261 errtype = "value error";
262 }
263 if (errtype) {
264 PyObject *type;
265 PyObject *value;
266 PyObject *tback;
267 PyObject *errstr;
268 PyErr_Fetch(&type, &value, &tback);
269 errstr = PyObject_Str(value);
270 if (errstr) {
271 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
272 Py_DECREF(errstr);
273 }
274 else {
275 PyErr_Clear();
276 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
277 }
278 Py_XDECREF(type);
279 Py_XDECREF(value);
280 Py_XDECREF(tback);
281 }
282
283 return -1;
284 }
285
286 static inline void
raise_unclosed_parentheses_error(Parser * p)287 raise_unclosed_parentheses_error(Parser *p) {
288 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
289 int error_col = p->tok->parencolstack[p->tok->level-1];
290 RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError,
291 error_lineno, error_col, error_lineno, -1,
292 "'%c' was never closed",
293 p->tok->parenstack[p->tok->level-1]);
294 }
295
296 static void
raise_tokenizer_init_error(PyObject * filename)297 raise_tokenizer_init_error(PyObject *filename)
298 {
299 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
300 || PyErr_ExceptionMatches(PyExc_SyntaxError)
301 || PyErr_ExceptionMatches(PyExc_ValueError)
302 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
303 return;
304 }
305 PyObject *errstr = NULL;
306 PyObject *tuple = NULL;
307 PyObject *type;
308 PyObject *value;
309 PyObject *tback;
310 PyErr_Fetch(&type, &value, &tback);
311 errstr = PyObject_Str(value);
312 if (!errstr) {
313 goto error;
314 }
315
316 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
317 if (!tmp) {
318 goto error;
319 }
320
321 tuple = PyTuple_Pack(2, errstr, tmp);
322 Py_DECREF(tmp);
323 if (!value) {
324 goto error;
325 }
326 PyErr_SetObject(PyExc_SyntaxError, tuple);
327
328 error:
329 Py_XDECREF(type);
330 Py_XDECREF(value);
331 Py_XDECREF(tback);
332 Py_XDECREF(errstr);
333 Py_XDECREF(tuple);
334 }
335
336 static int
tokenizer_error(Parser * p)337 tokenizer_error(Parser *p)
338 {
339 if (PyErr_Occurred()) {
340 return -1;
341 }
342
343 const char *msg = NULL;
344 PyObject* errtype = PyExc_SyntaxError;
345 Py_ssize_t col_offset = -1;
346 switch (p->tok->done) {
347 case E_TOKEN:
348 msg = "invalid token";
349 break;
350 case E_EOF:
351 if (p->tok->level) {
352 raise_unclosed_parentheses_error(p);
353 } else {
354 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
355 }
356 return -1;
357 case E_DEDENT:
358 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
359 return -1;
360 case E_INTR:
361 if (!PyErr_Occurred()) {
362 PyErr_SetNone(PyExc_KeyboardInterrupt);
363 }
364 return -1;
365 case E_NOMEM:
366 PyErr_NoMemory();
367 return -1;
368 case E_TABSPACE:
369 errtype = PyExc_TabError;
370 msg = "inconsistent use of tabs and spaces in indentation";
371 break;
372 case E_TOODEEP:
373 errtype = PyExc_IndentationError;
374 msg = "too many levels of indentation";
375 break;
376 case E_LINECONT: {
377 col_offset = p->tok->cur - p->tok->buf - 1;
378 msg = "unexpected character after line continuation character";
379 break;
380 }
381 default:
382 msg = "unknown parsing error";
383 }
384
385 RAISE_ERROR_KNOWN_LOCATION(p, errtype, p->tok->lineno,
386 col_offset >= 0 ? col_offset : 0,
387 p->tok->lineno, -1, msg);
388 return -1;
389 }
390
391 void *
_PyPegen_raise_error(Parser * p,PyObject * errtype,const char * errmsg,...)392 _PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
393 {
394 if (p->fill == 0) {
395 va_list va;
396 va_start(va, errmsg);
397 _PyPegen_raise_error_known_location(p, errtype, 0, 0, 0, -1, errmsg, va);
398 va_end(va);
399 return NULL;
400 }
401
402 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
403 Py_ssize_t col_offset;
404 Py_ssize_t end_col_offset = -1;
405 if (t->col_offset == -1) {
406 if (p->tok->cur == p->tok->buf) {
407 col_offset = 0;
408 } else {
409 const char* start = p->tok->buf ? p->tok->line_start : p->tok->buf;
410 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - start, intptr_t, int);
411 }
412 } else {
413 col_offset = t->col_offset + 1;
414 }
415
416 if (t->end_col_offset != -1) {
417 end_col_offset = t->end_col_offset + 1;
418 }
419
420 va_list va;
421 va_start(va, errmsg);
422 _PyPegen_raise_error_known_location(p, errtype, t->lineno, col_offset, t->end_lineno, end_col_offset, errmsg, va);
423 va_end(va);
424
425 return NULL;
426 }
427
428 static PyObject *
get_error_line(Parser * p,Py_ssize_t lineno)429 get_error_line(Parser *p, Py_ssize_t lineno)
430 {
431 /* If the file descriptor is interactive, the source lines of the current
432 * (multi-line) statement are stored in p->tok->interactive_src_start.
433 * If not, we're parsing from a string, which means that the whole source
434 * is stored in p->tok->str. */
435 assert((p->tok->fp == NULL && p->tok->str != NULL) || p->tok->fp == stdin);
436
437 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
438 assert(cur_line != NULL);
439
440 for (int i = 0; i < lineno - 1; i++) {
441 cur_line = strchr(cur_line, '\n') + 1;
442 }
443
444 char *next_newline;
445 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
446 next_newline = cur_line + strlen(cur_line);
447 }
448 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
449 }
450
451 void *
_PyPegen_raise_error_known_location(Parser * p,PyObject * errtype,Py_ssize_t lineno,Py_ssize_t col_offset,Py_ssize_t end_lineno,Py_ssize_t end_col_offset,const char * errmsg,va_list va)452 _PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
453 Py_ssize_t lineno, Py_ssize_t col_offset,
454 Py_ssize_t end_lineno, Py_ssize_t end_col_offset,
455 const char *errmsg, va_list va)
456 {
457 PyObject *value = NULL;
458 PyObject *errstr = NULL;
459 PyObject *error_line = NULL;
460 PyObject *tmp = NULL;
461 p->error_indicator = 1;
462
463 if (end_lineno == CURRENT_POS) {
464 end_lineno = p->tok->lineno;
465 }
466 if (end_col_offset == CURRENT_POS) {
467 end_col_offset = p->tok->cur - p->tok->line_start;
468 }
469
470 if (p->start_rule == Py_fstring_input) {
471 const char *fstring_msg = "f-string: ";
472 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
473
474 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
475 if (!new_errmsg) {
476 return (void *) PyErr_NoMemory();
477 }
478
479 // Copy both strings into new buffer
480 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
481 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
482 new_errmsg[len] = 0;
483 errmsg = new_errmsg;
484 }
485 errstr = PyUnicode_FromFormatV(errmsg, va);
486 if (!errstr) {
487 goto error;
488 }
489
490 if (p->tok->fp_interactive) {
491 error_line = get_error_line(p, lineno);
492 }
493 else if (p->start_rule == Py_file_input) {
494 error_line = _PyErr_ProgramDecodedTextObject(p->tok->filename,
495 (int) lineno, p->tok->encoding);
496 }
497
498 if (!error_line) {
499 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
500 then we need to find the error line from some other source, because
501 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
502 failed or we're parsing from a string or the REPL. There's a third edge case where
503 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
504 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
505 does not physically exist */
506 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
507
508 if (p->tok->lineno <= lineno && p->tok->inp > p->tok->buf) {
509 Py_ssize_t size = p->tok->inp - p->tok->buf;
510 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
511 }
512 else if (p->tok->fp == NULL || p->tok->fp == stdin) {
513 error_line = get_error_line(p, lineno);
514 }
515 else {
516 error_line = PyUnicode_FromStringAndSize("", 0);
517 }
518 if (!error_line) {
519 goto error;
520 }
521 }
522
523 if (p->start_rule == Py_fstring_input) {
524 col_offset -= p->starting_col_offset;
525 end_col_offset -= p->starting_col_offset;
526 }
527
528 Py_ssize_t col_number = col_offset;
529 Py_ssize_t end_col_number = end_col_offset;
530
531 if (p->tok->encoding != NULL) {
532 col_number = byte_offset_to_character_offset(error_line, col_offset);
533 end_col_number = end_col_number > 0 ?
534 byte_offset_to_character_offset(error_line, end_col_offset) :
535 end_col_number;
536 }
537 tmp = Py_BuildValue("(OiiNii)", p->tok->filename, lineno, col_number, error_line, end_lineno, end_col_number);
538 if (!tmp) {
539 goto error;
540 }
541 value = PyTuple_Pack(2, errstr, tmp);
542 Py_DECREF(tmp);
543 if (!value) {
544 goto error;
545 }
546 PyErr_SetObject(errtype, value);
547
548 Py_DECREF(errstr);
549 Py_DECREF(value);
550 if (p->start_rule == Py_fstring_input) {
551 PyMem_Free((void *)errmsg);
552 }
553 return NULL;
554
555 error:
556 Py_XDECREF(errstr);
557 Py_XDECREF(error_line);
558 if (p->start_rule == Py_fstring_input) {
559 PyMem_Free((void *)errmsg);
560 }
561 return NULL;
562 }
563
564 #if 0
565 static const char *
566 token_name(int type)
567 {
568 if (0 <= type && type <= N_TOKENS) {
569 return _PyParser_TokenNames[type];
570 }
571 return "<Huh?>";
572 }
573 #endif
574
575 // Here, mark is the start of the node, while p->mark is the end.
576 // If node==NULL, they should be the same.
577 int
_PyPegen_insert_memo(Parser * p,int mark,int type,void * node)578 _PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
579 {
580 // Insert in front
581 Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
582 if (m == NULL) {
583 return -1;
584 }
585 m->type = type;
586 m->node = node;
587 m->mark = p->mark;
588 m->next = p->tokens[mark]->memo;
589 p->tokens[mark]->memo = m;
590 return 0;
591 }
592
593 // Like _PyPegen_insert_memo(), but updates an existing node if found.
594 int
_PyPegen_update_memo(Parser * p,int mark,int type,void * node)595 _PyPegen_update_memo(Parser *p, int mark, int type, void *node)
596 {
597 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
598 if (m->type == type) {
599 // Update existing node.
600 m->node = node;
601 m->mark = p->mark;
602 return 0;
603 }
604 }
605 // Insert new node.
606 return _PyPegen_insert_memo(p, mark, type, node);
607 }
608
609 // Return dummy NAME.
610 void *
_PyPegen_dummy_name(Parser * p,...)611 _PyPegen_dummy_name(Parser *p, ...)
612 {
613 static void *cache = NULL;
614
615 if (cache != NULL) {
616 return cache;
617 }
618
619 PyObject *id = _create_dummy_identifier(p);
620 if (!id) {
621 return NULL;
622 }
623 cache = _PyAST_Name(id, Load, 1, 0, 1, 0, p->arena);
624 return cache;
625 }
626
627 static int
_get_keyword_or_name_type(Parser * p,const char * name,int name_len)628 _get_keyword_or_name_type(Parser *p, const char *name, int name_len)
629 {
630 assert(name_len > 0);
631 if (name_len >= p->n_keyword_lists ||
632 p->keywords[name_len] == NULL ||
633 p->keywords[name_len]->type == -1) {
634 return NAME;
635 }
636 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
637 if (strncmp(k->str, name, name_len) == 0) {
638 return k->type;
639 }
640 }
641 return NAME;
642 }
643
644 static int
growable_comment_array_init(growable_comment_array * arr,size_t initial_size)645 growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
646 assert(initial_size > 0);
647 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
648 arr->size = initial_size;
649 arr->num_items = 0;
650
651 return arr->items != NULL;
652 }
653
654 static int
growable_comment_array_add(growable_comment_array * arr,int lineno,char * comment)655 growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
656 if (arr->num_items >= arr->size) {
657 size_t new_size = arr->size * 2;
658 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
659 if (!new_items_array) {
660 return 0;
661 }
662 arr->items = new_items_array;
663 arr->size = new_size;
664 }
665
666 arr->items[arr->num_items].lineno = lineno;
667 arr->items[arr->num_items].comment = comment; // Take ownership
668 arr->num_items++;
669 return 1;
670 }
671
672 static void
growable_comment_array_deallocate(growable_comment_array * arr)673 growable_comment_array_deallocate(growable_comment_array *arr) {
674 for (unsigned i = 0; i < arr->num_items; i++) {
675 PyMem_Free(arr->items[i].comment);
676 }
677 PyMem_Free(arr->items);
678 }
679
680 static int
initialize_token(Parser * p,Token * token,const char * start,const char * end,int token_type)681 initialize_token(Parser *p, Token *token, const char *start, const char *end, int token_type) {
682 assert(token != NULL);
683
684 token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : token_type;
685 token->bytes = PyBytes_FromStringAndSize(start, end - start);
686 if (token->bytes == NULL) {
687 return -1;
688 }
689
690 if (_PyArena_AddPyObject(p->arena, token->bytes) < 0) {
691 Py_DECREF(token->bytes);
692 return -1;
693 }
694
695 token->level = p->tok->level;
696
697 const char *line_start = token_type == STRING ? p->tok->multi_line_start : p->tok->line_start;
698 int lineno = token_type == STRING ? p->tok->first_lineno : p->tok->lineno;
699 int end_lineno = p->tok->lineno;
700
701 int col_offset = (start != NULL && start >= line_start) ? (int)(start - line_start) : -1;
702 int end_col_offset = (end != NULL && end >= p->tok->line_start) ? (int)(end - p->tok->line_start) : -1;
703
704 token->lineno = lineno;
705 token->col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + col_offset : col_offset;
706 token->end_lineno = end_lineno;
707 token->end_col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + end_col_offset : end_col_offset;
708
709 p->fill += 1;
710
711 if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
712 return raise_decode_error(p);
713 }
714
715 return (token_type == ERRORTOKEN ? tokenizer_error(p) : 0);
716 }
717
718 static int
_resize_tokens_array(Parser * p)719 _resize_tokens_array(Parser *p) {
720 int newsize = p->size * 2;
721 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
722 if (new_tokens == NULL) {
723 PyErr_NoMemory();
724 return -1;
725 }
726 p->tokens = new_tokens;
727
728 for (int i = p->size; i < newsize; i++) {
729 p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
730 if (p->tokens[i] == NULL) {
731 p->size = i; // Needed, in order to cleanup correctly after parser fails
732 PyErr_NoMemory();
733 return -1;
734 }
735 }
736 p->size = newsize;
737 return 0;
738 }
739
740 int
_PyPegen_fill_token(Parser * p)741 _PyPegen_fill_token(Parser *p)
742 {
743 const char *start;
744 const char *end;
745 int type = PyTokenizer_Get(p->tok, &start, &end);
746
747 // Record and skip '# type: ignore' comments
748 while (type == TYPE_IGNORE) {
749 Py_ssize_t len = end - start;
750 char *tag = PyMem_Malloc(len + 1);
751 if (tag == NULL) {
752 PyErr_NoMemory();
753 return -1;
754 }
755 strncpy(tag, start, len);
756 tag[len] = '\0';
757 // Ownership of tag passes to the growable array
758 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
759 PyErr_NoMemory();
760 return -1;
761 }
762 type = PyTokenizer_Get(p->tok, &start, &end);
763 }
764
765 // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
766 if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
767 type = NEWLINE; /* Add an extra newline */
768 p->parsing_started = 0;
769
770 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
771 p->tok->pendin = -p->tok->indent;
772 p->tok->indent = 0;
773 }
774 }
775 else {
776 p->parsing_started = 1;
777 }
778
779 // Check if we are at the limit of the token array capacity and resize if needed
780 if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
781 return -1;
782 }
783
784 Token *t = p->tokens[p->fill];
785 return initialize_token(p, t, start, end, type);
786 }
787
788
789 #if defined(Py_DEBUG)
790 // Instrumentation to count the effectiveness of memoization.
791 // The array counts the number of tokens skipped by memoization,
792 // indexed by type.
793
794 #define NSTATISTICS 2000
795 static long memo_statistics[NSTATISTICS];
796
797 void
_PyPegen_clear_memo_statistics()798 _PyPegen_clear_memo_statistics()
799 {
800 for (int i = 0; i < NSTATISTICS; i++) {
801 memo_statistics[i] = 0;
802 }
803 }
804
805 PyObject *
_PyPegen_get_memo_statistics()806 _PyPegen_get_memo_statistics()
807 {
808 PyObject *ret = PyList_New(NSTATISTICS);
809 if (ret == NULL) {
810 return NULL;
811 }
812 for (int i = 0; i < NSTATISTICS; i++) {
813 PyObject *value = PyLong_FromLong(memo_statistics[i]);
814 if (value == NULL) {
815 Py_DECREF(ret);
816 return NULL;
817 }
818 // PyList_SetItem borrows a reference to value.
819 if (PyList_SetItem(ret, i, value) < 0) {
820 Py_DECREF(ret);
821 return NULL;
822 }
823 }
824 return ret;
825 }
826 #endif
827
828 int // bool
_PyPegen_is_memoized(Parser * p,int type,void * pres)829 _PyPegen_is_memoized(Parser *p, int type, void *pres)
830 {
831 if (p->mark == p->fill) {
832 if (_PyPegen_fill_token(p) < 0) {
833 p->error_indicator = 1;
834 return -1;
835 }
836 }
837
838 Token *t = p->tokens[p->mark];
839
840 for (Memo *m = t->memo; m != NULL; m = m->next) {
841 if (m->type == type) {
842 #if defined(PY_DEBUG)
843 if (0 <= type && type < NSTATISTICS) {
844 long count = m->mark - p->mark;
845 // A memoized negative result counts for one.
846 if (count <= 0) {
847 count = 1;
848 }
849 memo_statistics[type] += count;
850 }
851 #endif
852 p->mark = m->mark;
853 *(void **)(pres) = m->node;
854 return 1;
855 }
856 }
857 return 0;
858 }
859
860 int
_PyPegen_lookahead_with_name(int positive,expr_ty (func)(Parser *),Parser * p)861 _PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
862 {
863 int mark = p->mark;
864 void *res = func(p);
865 p->mark = mark;
866 return (res != NULL) == positive;
867 }
868
869 int
_PyPegen_lookahead_with_string(int positive,expr_ty (func)(Parser *,const char *),Parser * p,const char * arg)870 _PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
871 {
872 int mark = p->mark;
873 void *res = func(p, arg);
874 p->mark = mark;
875 return (res != NULL) == positive;
876 }
877
878 int
_PyPegen_lookahead_with_int(int positive,Token * (func)(Parser *,int),Parser * p,int arg)879 _PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
880 {
881 int mark = p->mark;
882 void *res = func(p, arg);
883 p->mark = mark;
884 return (res != NULL) == positive;
885 }
886
887 int
_PyPegen_lookahead(int positive,void * (func)(Parser *),Parser * p)888 _PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
889 {
890 int mark = p->mark;
891 void *res = (void*)func(p);
892 p->mark = mark;
893 return (res != NULL) == positive;
894 }
895
896 Token *
_PyPegen_expect_token(Parser * p,int type)897 _PyPegen_expect_token(Parser *p, int type)
898 {
899 if (p->mark == p->fill) {
900 if (_PyPegen_fill_token(p) < 0) {
901 p->error_indicator = 1;
902 return NULL;
903 }
904 }
905 Token *t = p->tokens[p->mark];
906 if (t->type != type) {
907 return NULL;
908 }
909 p->mark += 1;
910 return t;
911 }
912
913 Token *
_PyPegen_expect_forced_token(Parser * p,int type,const char * expected)914 _PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
915
916 if (p->error_indicator == 1) {
917 return NULL;
918 }
919
920 if (p->mark == p->fill) {
921 if (_PyPegen_fill_token(p) < 0) {
922 p->error_indicator = 1;
923 return NULL;
924 }
925 }
926 Token *t = p->tokens[p->mark];
927 if (t->type != type) {
928 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
929 return NULL;
930 }
931 p->mark += 1;
932 return t;
933 }
934
935 expr_ty
_PyPegen_expect_soft_keyword(Parser * p,const char * keyword)936 _PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
937 {
938 if (p->mark == p->fill) {
939 if (_PyPegen_fill_token(p) < 0) {
940 p->error_indicator = 1;
941 return NULL;
942 }
943 }
944 Token *t = p->tokens[p->mark];
945 if (t->type != NAME) {
946 return NULL;
947 }
948 const char *s = PyBytes_AsString(t->bytes);
949 if (!s) {
950 p->error_indicator = 1;
951 return NULL;
952 }
953 if (strcmp(s, keyword) != 0) {
954 return NULL;
955 }
956 return _PyPegen_name_token(p);
957 }
958
959 Token *
_PyPegen_get_last_nonnwhitespace_token(Parser * p)960 _PyPegen_get_last_nonnwhitespace_token(Parser *p)
961 {
962 assert(p->mark >= 0);
963 Token *token = NULL;
964 for (int m = p->mark - 1; m >= 0; m--) {
965 token = p->tokens[m];
966 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
967 break;
968 }
969 }
970 return token;
971 }
972
973 static expr_ty
_PyPegen_name_from_token(Parser * p,Token * t)974 _PyPegen_name_from_token(Parser *p, Token* t)
975 {
976 if (t == NULL) {
977 return NULL;
978 }
979 const char *s = PyBytes_AsString(t->bytes);
980 if (!s) {
981 p->error_indicator = 1;
982 return NULL;
983 }
984 PyObject *id = _PyPegen_new_identifier(p, s);
985 if (id == NULL) {
986 p->error_indicator = 1;
987 return NULL;
988 }
989 return _PyAST_Name(id, Load, t->lineno, t->col_offset, t->end_lineno,
990 t->end_col_offset, p->arena);
991 }
992
993
994 expr_ty
_PyPegen_name_token(Parser * p)995 _PyPegen_name_token(Parser *p)
996 {
997 Token *t = _PyPegen_expect_token(p, NAME);
998 return _PyPegen_name_from_token(p, t);
999 }
1000
1001 void *
_PyPegen_string_token(Parser * p)1002 _PyPegen_string_token(Parser *p)
1003 {
1004 return _PyPegen_expect_token(p, STRING);
1005 }
1006
1007
_PyPegen_soft_keyword_token(Parser * p)1008 expr_ty _PyPegen_soft_keyword_token(Parser *p) {
1009 Token *t = _PyPegen_expect_token(p, NAME);
1010 if (t == NULL) {
1011 return NULL;
1012 }
1013 char *the_token;
1014 Py_ssize_t size;
1015 PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
1016 for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
1017 if (strncmp(*keyword, the_token, size) == 0) {
1018 return _PyPegen_name_from_token(p, t);
1019 }
1020 }
1021 return NULL;
1022 }
1023
1024 static PyObject *
parsenumber_raw(const char * s)1025 parsenumber_raw(const char *s)
1026 {
1027 const char *end;
1028 long x;
1029 double dx;
1030 Py_complex compl;
1031 int imflag;
1032
1033 assert(s != NULL);
1034 errno = 0;
1035 end = s + strlen(s) - 1;
1036 imflag = *end == 'j' || *end == 'J';
1037 if (s[0] == '0') {
1038 x = (long)PyOS_strtoul(s, (char **)&end, 0);
1039 if (x < 0 && errno == 0) {
1040 return PyLong_FromString(s, (char **)0, 0);
1041 }
1042 }
1043 else {
1044 x = PyOS_strtol(s, (char **)&end, 0);
1045 }
1046 if (*end == '\0') {
1047 if (errno != 0) {
1048 return PyLong_FromString(s, (char **)0, 0);
1049 }
1050 return PyLong_FromLong(x);
1051 }
1052 /* XXX Huge floats may silently fail */
1053 if (imflag) {
1054 compl.real = 0.;
1055 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
1056 if (compl.imag == -1.0 && PyErr_Occurred()) {
1057 return NULL;
1058 }
1059 return PyComplex_FromCComplex(compl);
1060 }
1061 dx = PyOS_string_to_double(s, NULL, NULL);
1062 if (dx == -1.0 && PyErr_Occurred()) {
1063 return NULL;
1064 }
1065 return PyFloat_FromDouble(dx);
1066 }
1067
1068 static PyObject *
parsenumber(const char * s)1069 parsenumber(const char *s)
1070 {
1071 char *dup;
1072 char *end;
1073 PyObject *res = NULL;
1074
1075 assert(s != NULL);
1076
1077 if (strchr(s, '_') == NULL) {
1078 return parsenumber_raw(s);
1079 }
1080 /* Create a duplicate without underscores. */
1081 dup = PyMem_Malloc(strlen(s) + 1);
1082 if (dup == NULL) {
1083 return PyErr_NoMemory();
1084 }
1085 end = dup;
1086 for (; *s; s++) {
1087 if (*s != '_') {
1088 *end++ = *s;
1089 }
1090 }
1091 *end = '\0';
1092 res = parsenumber_raw(dup);
1093 PyMem_Free(dup);
1094 return res;
1095 }
1096
1097 expr_ty
_PyPegen_number_token(Parser * p)1098 _PyPegen_number_token(Parser *p)
1099 {
1100 Token *t = _PyPegen_expect_token(p, NUMBER);
1101 if (t == NULL) {
1102 return NULL;
1103 }
1104
1105 const char *num_raw = PyBytes_AsString(t->bytes);
1106 if (num_raw == NULL) {
1107 p->error_indicator = 1;
1108 return NULL;
1109 }
1110
1111 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1112 p->error_indicator = 1;
1113 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
1114 "in Python 3.6 and greater");
1115 }
1116
1117 PyObject *c = parsenumber(num_raw);
1118
1119 if (c == NULL) {
1120 p->error_indicator = 1;
1121 return NULL;
1122 }
1123
1124 if (_PyArena_AddPyObject(p->arena, c) < 0) {
1125 Py_DECREF(c);
1126 p->error_indicator = 1;
1127 return NULL;
1128 }
1129
1130 return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
1131 t->end_col_offset, p->arena);
1132 }
1133
1134 /* Check that the source for a single input statement really is a single
1135 statement by looking at what is left in the buffer after parsing.
1136 Trailing whitespace and comments are OK. */
1137 static int // bool
bad_single_statement(Parser * p)1138 bad_single_statement(Parser *p)
1139 {
1140 char *cur = p->tok->cur;
1141 char c = *cur;
1142
1143 for (;;) {
1144 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1145 c = *++cur;
1146 }
1147
1148 if (!c) {
1149 return 0;
1150 }
1151
1152 if (c != '#') {
1153 return 1;
1154 }
1155
1156 /* Suck up comment. */
1157 while (c && c != '\n') {
1158 c = *++cur;
1159 }
1160 }
1161 }
1162
1163 void
_PyPegen_Parser_Free(Parser * p)1164 _PyPegen_Parser_Free(Parser *p)
1165 {
1166 Py_XDECREF(p->normalize);
1167 for (int i = 0; i < p->size; i++) {
1168 PyMem_Free(p->tokens[i]);
1169 }
1170 PyMem_Free(p->tokens);
1171 growable_comment_array_deallocate(&p->type_ignore_comments);
1172 PyMem_Free(p);
1173 }
1174
1175 static int
compute_parser_flags(PyCompilerFlags * flags)1176 compute_parser_flags(PyCompilerFlags *flags)
1177 {
1178 int parser_flags = 0;
1179 if (!flags) {
1180 return 0;
1181 }
1182 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1183 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1184 }
1185 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1186 parser_flags |= PyPARSE_IGNORE_COOKIE;
1187 }
1188 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1189 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1190 }
1191 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1192 parser_flags |= PyPARSE_TYPE_COMMENTS;
1193 }
1194 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
1195 parser_flags |= PyPARSE_ASYNC_HACKS;
1196 }
1197 return parser_flags;
1198 }
1199
1200 Parser *
_PyPegen_Parser_New(struct tok_state * tok,int start_rule,int flags,int feature_version,int * errcode,PyArena * arena)1201 _PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
1202 int feature_version, int *errcode, PyArena *arena)
1203 {
1204 Parser *p = PyMem_Malloc(sizeof(Parser));
1205 if (p == NULL) {
1206 return (Parser *) PyErr_NoMemory();
1207 }
1208 assert(tok != NULL);
1209 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1210 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
1211 p->tok = tok;
1212 p->keywords = NULL;
1213 p->n_keyword_lists = -1;
1214 p->soft_keywords = NULL;
1215 p->tokens = PyMem_Malloc(sizeof(Token *));
1216 if (!p->tokens) {
1217 PyMem_Free(p);
1218 return (Parser *) PyErr_NoMemory();
1219 }
1220 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
1221 if (!p->tokens) {
1222 PyMem_Free(p->tokens);
1223 PyMem_Free(p);
1224 return (Parser *) PyErr_NoMemory();
1225 }
1226 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1227 PyMem_Free(p->tokens[0]);
1228 PyMem_Free(p->tokens);
1229 PyMem_Free(p);
1230 return (Parser *) PyErr_NoMemory();
1231 }
1232
1233 p->mark = 0;
1234 p->fill = 0;
1235 p->size = 1;
1236
1237 p->errcode = errcode;
1238 p->arena = arena;
1239 p->start_rule = start_rule;
1240 p->parsing_started = 0;
1241 p->normalize = NULL;
1242 p->error_indicator = 0;
1243
1244 p->starting_lineno = 0;
1245 p->starting_col_offset = 0;
1246 p->flags = flags;
1247 p->feature_version = feature_version;
1248 p->known_err_token = NULL;
1249 p->level = 0;
1250 p->call_invalid_rules = 0;
1251 p->in_raw_rule = 0;
1252 return p;
1253 }
1254
1255 static void
reset_parser_state(Parser * p)1256 reset_parser_state(Parser *p)
1257 {
1258 for (int i = 0; i < p->fill; i++) {
1259 p->tokens[i]->memo = NULL;
1260 }
1261 p->mark = 0;
1262 p->call_invalid_rules = 1;
1263 // Don't try to get extra tokens in interactive mode when trying to
1264 // raise specialized errors in the second pass.
1265 p->tok->interactive_underflow = IUNDERFLOW_STOP;
1266 }
1267
1268 static int
_PyPegen_check_tokenizer_errors(Parser * p)1269 _PyPegen_check_tokenizer_errors(Parser *p) {
1270 // Tokenize the whole input to see if there are any tokenization
1271 // errors such as mistmatching parentheses. These will get priority
1272 // over generic syntax errors only if the line number of the error is
1273 // before the one that we had for the generic error.
1274
1275 // We don't want to tokenize to the end for interactive input
1276 if (p->tok->prompt != NULL) {
1277 return 0;
1278 }
1279
1280 PyObject *type, *value, *traceback;
1281 PyErr_Fetch(&type, &value, &traceback);
1282
1283 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1284 Py_ssize_t current_err_line = current_token->lineno;
1285
1286 int ret = 0;
1287
1288 for (;;) {
1289 const char *start;
1290 const char *end;
1291 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1292 case ERRORTOKEN:
1293 if (p->tok->level != 0) {
1294 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1295 if (current_err_line > error_lineno) {
1296 raise_unclosed_parentheses_error(p);
1297 ret = -1;
1298 goto exit;
1299 }
1300 }
1301 break;
1302 case ENDMARKER:
1303 break;
1304 default:
1305 continue;
1306 }
1307 break;
1308 }
1309
1310
1311 exit:
1312 if (PyErr_Occurred()) {
1313 Py_XDECREF(value);
1314 Py_XDECREF(type);
1315 Py_XDECREF(traceback);
1316 } else {
1317 PyErr_Restore(type, value, traceback);
1318 }
1319 return ret;
1320 }
1321
1322 void *
_PyPegen_run_parser(Parser * p)1323 _PyPegen_run_parser(Parser *p)
1324 {
1325 void *res = _PyPegen_parse(p);
1326 assert(p->level == 0);
1327 if (res == NULL) {
1328 if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_SyntaxError)) {
1329 return NULL;
1330 }
1331 Token *last_token = p->tokens[p->fill - 1];
1332 reset_parser_state(p);
1333 _PyPegen_parse(p);
1334 if (PyErr_Occurred()) {
1335 // Prioritize tokenizer errors to custom syntax errors raised
1336 // on the second phase only if the errors come from the parser.
1337 if (p->tok->done == E_DONE && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
1338 _PyPegen_check_tokenizer_errors(p);
1339 }
1340 return NULL;
1341 }
1342 if (p->fill == 0) {
1343 RAISE_SYNTAX_ERROR("error at start before reading any input");
1344 }
1345 else if (last_token->type == ERRORTOKEN && p->tok->done == E_EOF) {
1346 if (p->tok->level) {
1347 raise_unclosed_parentheses_error(p);
1348 } else {
1349 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1350 }
1351 }
1352 else {
1353 if (p->tokens[p->fill-1]->type == INDENT) {
1354 RAISE_INDENTATION_ERROR("unexpected indent");
1355 }
1356 else if (p->tokens[p->fill-1]->type == DEDENT) {
1357 RAISE_INDENTATION_ERROR("unexpected unindent");
1358 }
1359 else {
1360 // Use the last token we found on the first pass to avoid reporting
1361 // incorrect locations for generic syntax errors just because we reached
1362 // further away when trying to find specific syntax errors in the second
1363 // pass.
1364 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(last_token, "invalid syntax");
1365 // _PyPegen_check_tokenizer_errors will override the existing
1366 // generic SyntaxError we just raised if errors are found.
1367 _PyPegen_check_tokenizer_errors(p);
1368 }
1369 }
1370 return NULL;
1371 }
1372
1373 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1374 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1375 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1376 }
1377
1378 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1379 #if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
1380 if (p->start_rule == Py_single_input ||
1381 p->start_rule == Py_file_input ||
1382 p->start_rule == Py_eval_input)
1383 {
1384 if (!_PyAST_Validate(res)) {
1385 return NULL;
1386 }
1387 }
1388 #endif
1389 return res;
1390 }
1391
1392 mod_ty
_PyPegen_run_parser_from_file_pointer(FILE * fp,int start_rule,PyObject * filename_ob,const char * enc,const char * ps1,const char * ps2,PyCompilerFlags * flags,int * errcode,PyArena * arena)1393 _PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1394 const char *enc, const char *ps1, const char *ps2,
1395 PyCompilerFlags *flags, int *errcode, PyArena *arena)
1396 {
1397 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1398 if (tok == NULL) {
1399 if (PyErr_Occurred()) {
1400 raise_tokenizer_init_error(filename_ob);
1401 return NULL;
1402 }
1403 return NULL;
1404 }
1405 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1406 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1407 tok->fp_interactive = 1;
1408 }
1409 // This transfers the ownership to the tokenizer
1410 tok->filename = filename_ob;
1411 Py_INCREF(filename_ob);
1412
1413 // From here on we need to clean up even if there's an error
1414 mod_ty result = NULL;
1415
1416 int parser_flags = compute_parser_flags(flags);
1417 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1418 errcode, arena);
1419 if (p == NULL) {
1420 goto error;
1421 }
1422
1423 result = _PyPegen_run_parser(p);
1424 _PyPegen_Parser_Free(p);
1425
1426 error:
1427 PyTokenizer_Free(tok);
1428 return result;
1429 }
1430
1431 mod_ty
_PyPegen_run_parser_from_string(const char * str,int start_rule,PyObject * filename_ob,PyCompilerFlags * flags,PyArena * arena)1432 _PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
1433 PyCompilerFlags *flags, PyArena *arena)
1434 {
1435 int exec_input = start_rule == Py_file_input;
1436
1437 struct tok_state *tok;
1438 if (flags != NULL && flags->cf_flags & PyCF_IGNORE_COOKIE) {
1439 tok = PyTokenizer_FromUTF8(str, exec_input);
1440 } else {
1441 tok = PyTokenizer_FromString(str, exec_input);
1442 }
1443 if (tok == NULL) {
1444 if (PyErr_Occurred()) {
1445 raise_tokenizer_init_error(filename_ob);
1446 }
1447 return NULL;
1448 }
1449 // This transfers the ownership to the tokenizer
1450 tok->filename = filename_ob;
1451 Py_INCREF(filename_ob);
1452
1453 // We need to clear up from here on
1454 mod_ty result = NULL;
1455
1456 int parser_flags = compute_parser_flags(flags);
1457 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1458 flags->cf_feature_version : PY_MINOR_VERSION;
1459 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1460 NULL, arena);
1461 if (p == NULL) {
1462 goto error;
1463 }
1464
1465 result = _PyPegen_run_parser(p);
1466 _PyPegen_Parser_Free(p);
1467
1468 error:
1469 PyTokenizer_Free(tok);
1470 return result;
1471 }
1472
1473 asdl_stmt_seq*
_PyPegen_interactive_exit(Parser * p)1474 _PyPegen_interactive_exit(Parser *p)
1475 {
1476 if (p->errcode) {
1477 *(p->errcode) = E_EOF;
1478 }
1479 return NULL;
1480 }
1481
1482 /* Creates a single-element asdl_seq* that contains a */
1483 asdl_seq *
_PyPegen_singleton_seq(Parser * p,void * a)1484 _PyPegen_singleton_seq(Parser *p, void *a)
1485 {
1486 assert(a != NULL);
1487 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
1488 if (!seq) {
1489 return NULL;
1490 }
1491 asdl_seq_SET_UNTYPED(seq, 0, a);
1492 return seq;
1493 }
1494
1495 /* Creates a copy of seq and prepends a to it */
1496 asdl_seq *
_PyPegen_seq_insert_in_front(Parser * p,void * a,asdl_seq * seq)1497 _PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1498 {
1499 assert(a != NULL);
1500 if (!seq) {
1501 return _PyPegen_singleton_seq(p, a);
1502 }
1503
1504 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1505 if (!new_seq) {
1506 return NULL;
1507 }
1508
1509 asdl_seq_SET_UNTYPED(new_seq, 0, a);
1510 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
1511 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
1512 }
1513 return new_seq;
1514 }
1515
1516 /* Creates a copy of seq and appends a to it */
1517 asdl_seq *
_PyPegen_seq_append_to_end(Parser * p,asdl_seq * seq,void * a)1518 _PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1519 {
1520 assert(a != NULL);
1521 if (!seq) {
1522 return _PyPegen_singleton_seq(p, a);
1523 }
1524
1525 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1526 if (!new_seq) {
1527 return NULL;
1528 }
1529
1530 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1531 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
1532 }
1533 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1534 return new_seq;
1535 }
1536
1537 static Py_ssize_t
_get_flattened_seq_size(asdl_seq * seqs)1538 _get_flattened_seq_size(asdl_seq *seqs)
1539 {
1540 Py_ssize_t size = 0;
1541 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1542 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
1543 size += asdl_seq_LEN(inner_seq);
1544 }
1545 return size;
1546 }
1547
1548 /* Flattens an asdl_seq* of asdl_seq*s */
1549 asdl_seq *
_PyPegen_seq_flatten(Parser * p,asdl_seq * seqs)1550 _PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1551 {
1552 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
1553 assert(flattened_seq_size > 0);
1554
1555 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
1556 if (!flattened_seq) {
1557 return NULL;
1558 }
1559
1560 int flattened_seq_idx = 0;
1561 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1562 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
1563 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
1564 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
1565 }
1566 }
1567 assert(flattened_seq_idx == flattened_seq_size);
1568
1569 return flattened_seq;
1570 }
1571
1572 void *
_PyPegen_seq_last_item(asdl_seq * seq)1573 _PyPegen_seq_last_item(asdl_seq *seq)
1574 {
1575 Py_ssize_t len = asdl_seq_LEN(seq);
1576 return asdl_seq_GET_UNTYPED(seq, len - 1);
1577 }
1578
1579 void *
_PyPegen_seq_first_item(asdl_seq * seq)1580 _PyPegen_seq_first_item(asdl_seq *seq)
1581 {
1582 return asdl_seq_GET_UNTYPED(seq, 0);
1583 }
1584
1585
1586 /* Creates a new name of the form <first_name>.<second_name> */
1587 expr_ty
_PyPegen_join_names_with_dot(Parser * p,expr_ty first_name,expr_ty second_name)1588 _PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1589 {
1590 assert(first_name != NULL && second_name != NULL);
1591 PyObject *first_identifier = first_name->v.Name.id;
1592 PyObject *second_identifier = second_name->v.Name.id;
1593
1594 if (PyUnicode_READY(first_identifier) == -1) {
1595 return NULL;
1596 }
1597 if (PyUnicode_READY(second_identifier) == -1) {
1598 return NULL;
1599 }
1600 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1601 if (!first_str) {
1602 return NULL;
1603 }
1604 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1605 if (!second_str) {
1606 return NULL;
1607 }
1608 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
1609
1610 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1611 if (!str) {
1612 return NULL;
1613 }
1614
1615 char *s = PyBytes_AS_STRING(str);
1616 if (!s) {
1617 return NULL;
1618 }
1619
1620 strcpy(s, first_str);
1621 s += strlen(first_str);
1622 *s++ = '.';
1623 strcpy(s, second_str);
1624 s += strlen(second_str);
1625 *s = '\0';
1626
1627 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1628 Py_DECREF(str);
1629 if (!uni) {
1630 return NULL;
1631 }
1632 PyUnicode_InternInPlace(&uni);
1633 if (_PyArena_AddPyObject(p->arena, uni) < 0) {
1634 Py_DECREF(uni);
1635 return NULL;
1636 }
1637
1638 return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1639 }
1640
1641 /* Counts the total number of dots in seq's tokens */
1642 int
_PyPegen_seq_count_dots(asdl_seq * seq)1643 _PyPegen_seq_count_dots(asdl_seq *seq)
1644 {
1645 int number_of_dots = 0;
1646 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1647 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
1648 switch (current_expr->type) {
1649 case ELLIPSIS:
1650 number_of_dots += 3;
1651 break;
1652 case DOT:
1653 number_of_dots += 1;
1654 break;
1655 default:
1656 Py_UNREACHABLE();
1657 }
1658 }
1659
1660 return number_of_dots;
1661 }
1662
1663 /* Creates an alias with '*' as the identifier name */
1664 alias_ty
_PyPegen_alias_for_star(Parser * p,int lineno,int col_offset,int end_lineno,int end_col_offset,PyArena * arena)1665 _PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
1666 int end_col_offset, PyArena *arena) {
1667 PyObject *str = PyUnicode_InternFromString("*");
1668 if (!str) {
1669 return NULL;
1670 }
1671 if (_PyArena_AddPyObject(p->arena, str) < 0) {
1672 Py_DECREF(str);
1673 return NULL;
1674 }
1675 return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
1676 }
1677
1678 /* Creates a new asdl_seq* with the identifiers of all the names in seq */
1679 asdl_identifier_seq *
_PyPegen_map_names_to_ids(Parser * p,asdl_expr_seq * seq)1680 _PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
1681 {
1682 Py_ssize_t len = asdl_seq_LEN(seq);
1683 assert(len > 0);
1684
1685 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
1686 if (!new_seq) {
1687 return NULL;
1688 }
1689 for (Py_ssize_t i = 0; i < len; i++) {
1690 expr_ty e = asdl_seq_GET(seq, i);
1691 asdl_seq_SET(new_seq, i, e->v.Name.id);
1692 }
1693 return new_seq;
1694 }
1695
1696 /* Constructs a CmpopExprPair */
1697 CmpopExprPair *
_PyPegen_cmpop_expr_pair(Parser * p,cmpop_ty cmpop,expr_ty expr)1698 _PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1699 {
1700 assert(expr != NULL);
1701 CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1702 if (!a) {
1703 return NULL;
1704 }
1705 a->cmpop = cmpop;
1706 a->expr = expr;
1707 return a;
1708 }
1709
1710 asdl_int_seq *
_PyPegen_get_cmpops(Parser * p,asdl_seq * seq)1711 _PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1712 {
1713 Py_ssize_t len = asdl_seq_LEN(seq);
1714 assert(len > 0);
1715
1716 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1717 if (!new_seq) {
1718 return NULL;
1719 }
1720 for (Py_ssize_t i = 0; i < len; i++) {
1721 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1722 asdl_seq_SET(new_seq, i, pair->cmpop);
1723 }
1724 return new_seq;
1725 }
1726
1727 asdl_expr_seq *
_PyPegen_get_exprs(Parser * p,asdl_seq * seq)1728 _PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1729 {
1730 Py_ssize_t len = asdl_seq_LEN(seq);
1731 assert(len > 0);
1732
1733 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1734 if (!new_seq) {
1735 return NULL;
1736 }
1737 for (Py_ssize_t i = 0; i < len; i++) {
1738 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1739 asdl_seq_SET(new_seq, i, pair->expr);
1740 }
1741 return new_seq;
1742 }
1743
1744 /* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1745 static asdl_expr_seq *
_set_seq_context(Parser * p,asdl_expr_seq * seq,expr_context_ty ctx)1746 _set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
1747 {
1748 Py_ssize_t len = asdl_seq_LEN(seq);
1749 if (len == 0) {
1750 return NULL;
1751 }
1752
1753 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1754 if (!new_seq) {
1755 return NULL;
1756 }
1757 for (Py_ssize_t i = 0; i < len; i++) {
1758 expr_ty e = asdl_seq_GET(seq, i);
1759 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1760 }
1761 return new_seq;
1762 }
1763
1764 static expr_ty
_set_name_context(Parser * p,expr_ty e,expr_context_ty ctx)1765 _set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1766 {
1767 return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1768 }
1769
1770 static expr_ty
_set_tuple_context(Parser * p,expr_ty e,expr_context_ty ctx)1771 _set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1772 {
1773 return _PyAST_Tuple(
1774 _set_seq_context(p, e->v.Tuple.elts, ctx),
1775 ctx,
1776 EXTRA_EXPR(e, e));
1777 }
1778
1779 static expr_ty
_set_list_context(Parser * p,expr_ty e,expr_context_ty ctx)1780 _set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1781 {
1782 return _PyAST_List(
1783 _set_seq_context(p, e->v.List.elts, ctx),
1784 ctx,
1785 EXTRA_EXPR(e, e));
1786 }
1787
1788 static expr_ty
_set_subscript_context(Parser * p,expr_ty e,expr_context_ty ctx)1789 _set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1790 {
1791 return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
1792 ctx, EXTRA_EXPR(e, e));
1793 }
1794
1795 static expr_ty
_set_attribute_context(Parser * p,expr_ty e,expr_context_ty ctx)1796 _set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1797 {
1798 return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
1799 ctx, EXTRA_EXPR(e, e));
1800 }
1801
1802 static expr_ty
_set_starred_context(Parser * p,expr_ty e,expr_context_ty ctx)1803 _set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1804 {
1805 return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
1806 ctx, EXTRA_EXPR(e, e));
1807 }
1808
1809 /* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1810 expr_ty
_PyPegen_set_expr_context(Parser * p,expr_ty expr,expr_context_ty ctx)1811 _PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1812 {
1813 assert(expr != NULL);
1814
1815 expr_ty new = NULL;
1816 switch (expr->kind) {
1817 case Name_kind:
1818 new = _set_name_context(p, expr, ctx);
1819 break;
1820 case Tuple_kind:
1821 new = _set_tuple_context(p, expr, ctx);
1822 break;
1823 case List_kind:
1824 new = _set_list_context(p, expr, ctx);
1825 break;
1826 case Subscript_kind:
1827 new = _set_subscript_context(p, expr, ctx);
1828 break;
1829 case Attribute_kind:
1830 new = _set_attribute_context(p, expr, ctx);
1831 break;
1832 case Starred_kind:
1833 new = _set_starred_context(p, expr, ctx);
1834 break;
1835 default:
1836 new = expr;
1837 }
1838 return new;
1839 }
1840
1841 /* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1842 KeyValuePair *
_PyPegen_key_value_pair(Parser * p,expr_ty key,expr_ty value)1843 _PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1844 {
1845 KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1846 if (!a) {
1847 return NULL;
1848 }
1849 a->key = key;
1850 a->value = value;
1851 return a;
1852 }
1853
1854 /* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1855 asdl_expr_seq *
_PyPegen_get_keys(Parser * p,asdl_seq * seq)1856 _PyPegen_get_keys(Parser *p, asdl_seq *seq)
1857 {
1858 Py_ssize_t len = asdl_seq_LEN(seq);
1859 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1860 if (!new_seq) {
1861 return NULL;
1862 }
1863 for (Py_ssize_t i = 0; i < len; i++) {
1864 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
1865 asdl_seq_SET(new_seq, i, pair->key);
1866 }
1867 return new_seq;
1868 }
1869
1870 /* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1871 asdl_expr_seq *
_PyPegen_get_values(Parser * p,asdl_seq * seq)1872 _PyPegen_get_values(Parser *p, asdl_seq *seq)
1873 {
1874 Py_ssize_t len = asdl_seq_LEN(seq);
1875 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1876 if (!new_seq) {
1877 return NULL;
1878 }
1879 for (Py_ssize_t i = 0; i < len; i++) {
1880 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
1881 asdl_seq_SET(new_seq, i, pair->value);
1882 }
1883 return new_seq;
1884 }
1885
1886 /* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
1887 KeyPatternPair *
_PyPegen_key_pattern_pair(Parser * p,expr_ty key,pattern_ty pattern)1888 _PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
1889 {
1890 KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
1891 if (!a) {
1892 return NULL;
1893 }
1894 a->key = key;
1895 a->pattern = pattern;
1896 return a;
1897 }
1898
1899 /* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
1900 asdl_expr_seq *
_PyPegen_get_pattern_keys(Parser * p,asdl_seq * seq)1901 _PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
1902 {
1903 Py_ssize_t len = asdl_seq_LEN(seq);
1904 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1905 if (!new_seq) {
1906 return NULL;
1907 }
1908 for (Py_ssize_t i = 0; i < len; i++) {
1909 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1910 asdl_seq_SET(new_seq, i, pair->key);
1911 }
1912 return new_seq;
1913 }
1914
1915 /* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
1916 asdl_pattern_seq *
_PyPegen_get_patterns(Parser * p,asdl_seq * seq)1917 _PyPegen_get_patterns(Parser *p, asdl_seq *seq)
1918 {
1919 Py_ssize_t len = asdl_seq_LEN(seq);
1920 asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
1921 if (!new_seq) {
1922 return NULL;
1923 }
1924 for (Py_ssize_t i = 0; i < len; i++) {
1925 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1926 asdl_seq_SET(new_seq, i, pair->pattern);
1927 }
1928 return new_seq;
1929 }
1930
1931 /* Constructs a NameDefaultPair */
1932 NameDefaultPair *
_PyPegen_name_default_pair(Parser * p,arg_ty arg,expr_ty value,Token * tc)1933 _PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
1934 {
1935 NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1936 if (!a) {
1937 return NULL;
1938 }
1939 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
1940 a->value = value;
1941 return a;
1942 }
1943
1944 /* Constructs a SlashWithDefault */
1945 SlashWithDefault *
_PyPegen_slash_with_default(Parser * p,asdl_arg_seq * plain_names,asdl_seq * names_with_defaults)1946 _PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
1947 {
1948 SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1949 if (!a) {
1950 return NULL;
1951 }
1952 a->plain_names = plain_names;
1953 a->names_with_defaults = names_with_defaults;
1954 return a;
1955 }
1956
1957 /* Constructs a StarEtc */
1958 StarEtc *
_PyPegen_star_etc(Parser * p,arg_ty vararg,asdl_seq * kwonlyargs,arg_ty kwarg)1959 _PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1960 {
1961 StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
1962 if (!a) {
1963 return NULL;
1964 }
1965 a->vararg = vararg;
1966 a->kwonlyargs = kwonlyargs;
1967 a->kwarg = kwarg;
1968 return a;
1969 }
1970
1971 asdl_seq *
_PyPegen_join_sequences(Parser * p,asdl_seq * a,asdl_seq * b)1972 _PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1973 {
1974 Py_ssize_t first_len = asdl_seq_LEN(a);
1975 Py_ssize_t second_len = asdl_seq_LEN(b);
1976 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
1977 if (!new_seq) {
1978 return NULL;
1979 }
1980
1981 int k = 0;
1982 for (Py_ssize_t i = 0; i < first_len; i++) {
1983 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
1984 }
1985 for (Py_ssize_t i = 0; i < second_len; i++) {
1986 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
1987 }
1988
1989 return new_seq;
1990 }
1991
1992 static asdl_arg_seq*
_get_names(Parser * p,asdl_seq * names_with_defaults)1993 _get_names(Parser *p, asdl_seq *names_with_defaults)
1994 {
1995 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
1996 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
1997 if (!seq) {
1998 return NULL;
1999 }
2000 for (Py_ssize_t i = 0; i < len; i++) {
2001 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
2002 asdl_seq_SET(seq, i, pair->arg);
2003 }
2004 return seq;
2005 }
2006
2007 static asdl_expr_seq *
_get_defaults(Parser * p,asdl_seq * names_with_defaults)2008 _get_defaults(Parser *p, asdl_seq *names_with_defaults)
2009 {
2010 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
2011 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
2012 if (!seq) {
2013 return NULL;
2014 }
2015 for (Py_ssize_t i = 0; i < len; i++) {
2016 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
2017 asdl_seq_SET(seq, i, pair->value);
2018 }
2019 return seq;
2020 }
2021
2022 static int
_make_posonlyargs(Parser * p,asdl_arg_seq * slash_without_default,SlashWithDefault * slash_with_default,asdl_arg_seq ** posonlyargs)2023 _make_posonlyargs(Parser *p,
2024 asdl_arg_seq *slash_without_default,
2025 SlashWithDefault *slash_with_default,
2026 asdl_arg_seq **posonlyargs) {
2027 if (slash_without_default != NULL) {
2028 *posonlyargs = slash_without_default;
2029 }
2030 else if (slash_with_default != NULL) {
2031 asdl_arg_seq *slash_with_default_names =
2032 _get_names(p, slash_with_default->names_with_defaults);
2033 if (!slash_with_default_names) {
2034 return -1;
2035 }
2036 *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2037 p,
2038 (asdl_seq*)slash_with_default->plain_names,
2039 (asdl_seq*)slash_with_default_names);
2040 }
2041 else {
2042 *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2043 }
2044 return *posonlyargs == NULL ? -1 : 0;
2045 }
2046
2047 static int
_make_posargs(Parser * p,asdl_arg_seq * plain_names,asdl_seq * names_with_default,asdl_arg_seq ** posargs)2048 _make_posargs(Parser *p,
2049 asdl_arg_seq *plain_names,
2050 asdl_seq *names_with_default,
2051 asdl_arg_seq **posargs) {
2052 if (plain_names != NULL && names_with_default != NULL) {
2053 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
2054 if (!names_with_default_names) {
2055 return -1;
2056 }
2057 *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2058 p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
2059 }
2060 else if (plain_names == NULL && names_with_default != NULL) {
2061 *posargs = _get_names(p, names_with_default);
2062 }
2063 else if (plain_names != NULL && names_with_default == NULL) {
2064 *posargs = plain_names;
2065 }
2066 else {
2067 *posargs = _Py_asdl_arg_seq_new(0, p->arena);
2068 }
2069 return *posargs == NULL ? -1 : 0;
2070 }
2071
2072 static int
_make_posdefaults(Parser * p,SlashWithDefault * slash_with_default,asdl_seq * names_with_default,asdl_expr_seq ** posdefaults)2073 _make_posdefaults(Parser *p,
2074 SlashWithDefault *slash_with_default,
2075 asdl_seq *names_with_default,
2076 asdl_expr_seq **posdefaults) {
2077 if (slash_with_default != NULL && names_with_default != NULL) {
2078 asdl_expr_seq *slash_with_default_values =
2079 _get_defaults(p, slash_with_default->names_with_defaults);
2080 if (!slash_with_default_values) {
2081 return -1;
2082 }
2083 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
2084 if (!names_with_default_values) {
2085 return -1;
2086 }
2087 *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
2088 p,
2089 (asdl_seq*)slash_with_default_values,
2090 (asdl_seq*)names_with_default_values);
2091 }
2092 else if (slash_with_default == NULL && names_with_default != NULL) {
2093 *posdefaults = _get_defaults(p, names_with_default);
2094 }
2095 else if (slash_with_default != NULL && names_with_default == NULL) {
2096 *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
2097 }
2098 else {
2099 *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2100 }
2101 return *posdefaults == NULL ? -1 : 0;
2102 }
2103
2104 static int
_make_kwargs(Parser * p,StarEtc * star_etc,asdl_arg_seq ** kwonlyargs,asdl_expr_seq ** kwdefaults)2105 _make_kwargs(Parser *p, StarEtc *star_etc,
2106 asdl_arg_seq **kwonlyargs,
2107 asdl_expr_seq **kwdefaults) {
2108 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2109 *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
2110 }
2111 else {
2112 *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2113 }
2114
2115 if (*kwonlyargs == NULL) {
2116 return -1;
2117 }
2118
2119 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2120 *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
2121 }
2122 else {
2123 *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2124 }
2125
2126 if (*kwdefaults == NULL) {
2127 return -1;
2128 }
2129
2130 return 0;
2131 }
2132
2133 /* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
2134 arguments_ty
_PyPegen_make_arguments(Parser * p,asdl_arg_seq * slash_without_default,SlashWithDefault * slash_with_default,asdl_arg_seq * plain_names,asdl_seq * names_with_default,StarEtc * star_etc)2135 _PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
2136 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
2137 asdl_seq *names_with_default, StarEtc *star_etc)
2138 {
2139 asdl_arg_seq *posonlyargs;
2140 if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
2141 return NULL;
2142 }
2143
2144 asdl_arg_seq *posargs;
2145 if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
2146 return NULL;
2147 }
2148
2149 asdl_expr_seq *posdefaults;
2150 if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
2151 return NULL;
2152 }
2153
2154 arg_ty vararg = NULL;
2155 if (star_etc != NULL && star_etc->vararg != NULL) {
2156 vararg = star_etc->vararg;
2157 }
2158
2159 asdl_arg_seq *kwonlyargs;
2160 asdl_expr_seq *kwdefaults;
2161 if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
2162 return NULL;
2163 }
2164
2165 arg_ty kwarg = NULL;
2166 if (star_etc != NULL && star_etc->kwarg != NULL) {
2167 kwarg = star_etc->kwarg;
2168 }
2169
2170 return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
2171 kwdefaults, kwarg, posdefaults, p->arena);
2172 }
2173
2174
2175 /* Constructs an empty arguments_ty object, that gets used when a function accepts no
2176 * arguments. */
2177 arguments_ty
_PyPegen_empty_arguments(Parser * p)2178 _PyPegen_empty_arguments(Parser *p)
2179 {
2180 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2181 if (!posonlyargs) {
2182 return NULL;
2183 }
2184 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
2185 if (!posargs) {
2186 return NULL;
2187 }
2188 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2189 if (!posdefaults) {
2190 return NULL;
2191 }
2192 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2193 if (!kwonlyargs) {
2194 return NULL;
2195 }
2196 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2197 if (!kwdefaults) {
2198 return NULL;
2199 }
2200
2201 return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
2202 kwdefaults, NULL, posdefaults, p->arena);
2203 }
2204
2205 /* Encapsulates the value of an operator_ty into an AugOperator struct */
2206 AugOperator *
_PyPegen_augoperator(Parser * p,operator_ty kind)2207 _PyPegen_augoperator(Parser *p, operator_ty kind)
2208 {
2209 AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
2210 if (!a) {
2211 return NULL;
2212 }
2213 a->kind = kind;
2214 return a;
2215 }
2216
2217 /* Construct a FunctionDef equivalent to function_def, but with decorators */
2218 stmt_ty
_PyPegen_function_def_decorators(Parser * p,asdl_expr_seq * decorators,stmt_ty function_def)2219 _PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
2220 {
2221 assert(function_def != NULL);
2222 if (function_def->kind == AsyncFunctionDef_kind) {
2223 return _PyAST_AsyncFunctionDef(
2224 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2225 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2226 function_def->v.FunctionDef.type_comment, function_def->lineno,
2227 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2228 p->arena);
2229 }
2230
2231 return _PyAST_FunctionDef(
2232 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2233 function_def->v.FunctionDef.body, decorators,
2234 function_def->v.FunctionDef.returns,
2235 function_def->v.FunctionDef.type_comment, function_def->lineno,
2236 function_def->col_offset, function_def->end_lineno,
2237 function_def->end_col_offset, p->arena);
2238 }
2239
2240 /* Construct a ClassDef equivalent to class_def, but with decorators */
2241 stmt_ty
_PyPegen_class_def_decorators(Parser * p,asdl_expr_seq * decorators,stmt_ty class_def)2242 _PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
2243 {
2244 assert(class_def != NULL);
2245 return _PyAST_ClassDef(
2246 class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2247 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2248 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2249 class_def->end_col_offset, p->arena);
2250 }
2251
2252 /* Construct a KeywordOrStarred */
2253 KeywordOrStarred *
_PyPegen_keyword_or_starred(Parser * p,void * element,int is_keyword)2254 _PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2255 {
2256 KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
2257 if (!a) {
2258 return NULL;
2259 }
2260 a->element = element;
2261 a->is_keyword = is_keyword;
2262 return a;
2263 }
2264
2265 /* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2266 static int
_seq_number_of_starred_exprs(asdl_seq * seq)2267 _seq_number_of_starred_exprs(asdl_seq *seq)
2268 {
2269 int n = 0;
2270 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
2271 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
2272 if (!k->is_keyword) {
2273 n++;
2274 }
2275 }
2276 return n;
2277 }
2278
2279 /* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
2280 asdl_expr_seq *
_PyPegen_seq_extract_starred_exprs(Parser * p,asdl_seq * kwargs)2281 _PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2282 {
2283 int new_len = _seq_number_of_starred_exprs(kwargs);
2284 if (new_len == 0) {
2285 return NULL;
2286 }
2287 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
2288 if (!new_seq) {
2289 return NULL;
2290 }
2291
2292 int idx = 0;
2293 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
2294 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
2295 if (!k->is_keyword) {
2296 asdl_seq_SET(new_seq, idx++, k->element);
2297 }
2298 }
2299 return new_seq;
2300 }
2301
2302 /* Return a new asdl_seq* with only the keywords in kwargs */
2303 asdl_keyword_seq*
_PyPegen_seq_delete_starred_exprs(Parser * p,asdl_seq * kwargs)2304 _PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2305 {
2306 Py_ssize_t len = asdl_seq_LEN(kwargs);
2307 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
2308 if (new_len == 0) {
2309 return NULL;
2310 }
2311 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
2312 if (!new_seq) {
2313 return NULL;
2314 }
2315
2316 int idx = 0;
2317 for (Py_ssize_t i = 0; i < len; i++) {
2318 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
2319 if (k->is_keyword) {
2320 asdl_seq_SET(new_seq, idx++, k->element);
2321 }
2322 }
2323 return new_seq;
2324 }
2325
2326 expr_ty
_PyPegen_concatenate_strings(Parser * p,asdl_seq * strings)2327 _PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2328 {
2329 Py_ssize_t len = asdl_seq_LEN(strings);
2330 assert(len > 0);
2331
2332 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2333 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
2334
2335 int bytesmode = 0;
2336 PyObject *bytes_str = NULL;
2337
2338 FstringParser state;
2339 _PyPegen_FstringParser_Init(&state);
2340
2341 for (Py_ssize_t i = 0; i < len; i++) {
2342 Token *t = asdl_seq_GET_UNTYPED(strings, i);
2343
2344 int this_bytesmode;
2345 int this_rawmode;
2346 PyObject *s;
2347 const char *fstr;
2348 Py_ssize_t fstrlen = -1;
2349
2350 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
2351 goto error;
2352 }
2353
2354 /* Check that we are not mixing bytes with unicode. */
2355 if (i != 0 && bytesmode != this_bytesmode) {
2356 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2357 Py_XDECREF(s);
2358 goto error;
2359 }
2360 bytesmode = this_bytesmode;
2361
2362 if (fstr != NULL) {
2363 assert(s == NULL && !bytesmode);
2364
2365 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2366 this_rawmode, 0, first, t, last);
2367 if (result < 0) {
2368 goto error;
2369 }
2370 }
2371 else {
2372 /* String or byte string. */
2373 assert(s != NULL && fstr == NULL);
2374 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2375
2376 if (bytesmode) {
2377 if (i == 0) {
2378 bytes_str = s;
2379 }
2380 else {
2381 PyBytes_ConcatAndDel(&bytes_str, s);
2382 if (!bytes_str) {
2383 goto error;
2384 }
2385 }
2386 }
2387 else {
2388 /* This is a regular string. Concatenate it. */
2389 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2390 goto error;
2391 }
2392 }
2393 }
2394 }
2395
2396 if (bytesmode) {
2397 if (_PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2398 goto error;
2399 }
2400 return _PyAST_Constant(bytes_str, NULL, first->lineno,
2401 first->col_offset, last->end_lineno,
2402 last->end_col_offset, p->arena);
2403 }
2404
2405 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2406
2407 error:
2408 Py_XDECREF(bytes_str);
2409 _PyPegen_FstringParser_Dealloc(&state);
2410 if (PyErr_Occurred()) {
2411 raise_decode_error(p);
2412 }
2413 return NULL;
2414 }
2415
2416 expr_ty
_PyPegen_ensure_imaginary(Parser * p,expr_ty exp)2417 _PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
2418 {
2419 if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
2420 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
2421 return NULL;
2422 }
2423 return exp;
2424 }
2425
2426 expr_ty
_PyPegen_ensure_real(Parser * p,expr_ty exp)2427 _PyPegen_ensure_real(Parser *p, expr_ty exp)
2428 {
2429 if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
2430 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
2431 return NULL;
2432 }
2433 return exp;
2434 }
2435
2436 mod_ty
_PyPegen_make_module(Parser * p,asdl_stmt_seq * a)2437 _PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2438 asdl_type_ignore_seq *type_ignores = NULL;
2439 Py_ssize_t num = p->type_ignore_comments.num_items;
2440 if (num > 0) {
2441 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2442 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
2443 if (type_ignores == NULL) {
2444 return NULL;
2445 }
2446 for (int i = 0; i < num; i++) {
2447 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2448 if (tag == NULL) {
2449 return NULL;
2450 }
2451 type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
2452 tag, p->arena);
2453 if (ti == NULL) {
2454 return NULL;
2455 }
2456 asdl_seq_SET(type_ignores, i, ti);
2457 }
2458 }
2459 return _PyAST_Module(a, type_ignores, p->arena);
2460 }
2461
2462 // Error reporting helpers
2463
2464 expr_ty
_PyPegen_get_invalid_target(expr_ty e,TARGETS_TYPE targets_type)2465 _PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
2466 {
2467 if (e == NULL) {
2468 return NULL;
2469 }
2470
2471 #define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2472 Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
2473 for (Py_ssize_t i = 0; i < len; i++) {\
2474 expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
2475 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
2476 if (child != NULL) {\
2477 return child;\
2478 }\
2479 }\
2480 } while (0)
2481
2482 // We only need to visit List and Tuple nodes recursively as those
2483 // are the only ones that can contain valid names in targets when
2484 // they are parsed as expressions. Any other kind of expression
2485 // that is a container (like Sets or Dicts) is directly invalid and
2486 // we don't need to visit it recursively.
2487
2488 switch (e->kind) {
2489 case List_kind:
2490 VISIT_CONTAINER(e, List);
2491 return NULL;
2492 case Tuple_kind:
2493 VISIT_CONTAINER(e, Tuple);
2494 return NULL;
2495 case Starred_kind:
2496 if (targets_type == DEL_TARGETS) {
2497 return e;
2498 }
2499 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2500 case Compare_kind:
2501 // This is needed, because the `a in b` in `for a in b` gets parsed
2502 // as a comparison, and so we need to search the left side of the comparison
2503 // for invalid targets.
2504 if (targets_type == FOR_TARGETS) {
2505 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2506 if (cmpop == In) {
2507 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2508 }
2509 return NULL;
2510 }
2511 return e;
2512 case Name_kind:
2513 case Subscript_kind:
2514 case Attribute_kind:
2515 return NULL;
2516 default:
2517 return e;
2518 }
2519 }
2520
_PyPegen_arguments_parsing_error(Parser * p,expr_ty e)2521 void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2522 int kwarg_unpacking = 0;
2523 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2524 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2525 if (!keyword->arg) {
2526 kwarg_unpacking = 1;
2527 }
2528 }
2529
2530 const char *msg = NULL;
2531 if (kwarg_unpacking) {
2532 msg = "positional argument follows keyword argument unpacking";
2533 } else {
2534 msg = "positional argument follows keyword argument";
2535 }
2536
2537 return RAISE_SYNTAX_ERROR(msg);
2538 }
2539
2540
2541 static inline expr_ty
_PyPegen_get_last_comprehension_item(comprehension_ty comprehension)2542 _PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
2543 if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
2544 return comprehension->iter;
2545 }
2546 return PyPegen_last_item(comprehension->ifs, expr_ty);
2547 }
2548
2549 void *
_PyPegen_nonparen_genexp_in_call(Parser * p,expr_ty args,asdl_comprehension_seq * comprehensions)2550 _PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions)
2551 {
2552 /* The rule that calls this function is 'args for_if_clauses'.
2553 For the input f(L, x for x in y), L and x are in args and
2554 the for is parsed as a for_if_clause. We have to check if
2555 len <= 1, so that input like dict((a, b) for a, b in x)
2556 gets successfully parsed and then we pass the last
2557 argument (x in the above example) as the location of the
2558 error */
2559 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2560 if (len <= 1) {
2561 return NULL;
2562 }
2563
2564 comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
2565
2566 return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
2567 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2568 _PyPegen_get_last_comprehension_item(last_comprehension),
2569 "Generator expression must be parenthesized"
2570 );
2571 }
2572
2573
_PyPegen_collect_call_seqs(Parser * p,asdl_expr_seq * a,asdl_seq * b,int lineno,int col_offset,int end_lineno,int end_col_offset,PyArena * arena)2574 expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
2575 int lineno, int col_offset, int end_lineno,
2576 int end_col_offset, PyArena *arena) {
2577 Py_ssize_t args_len = asdl_seq_LEN(a);
2578 Py_ssize_t total_len = args_len;
2579
2580 if (b == NULL) {
2581 return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2582 end_lineno, end_col_offset, arena);
2583
2584 }
2585
2586 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2587 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
2588
2589 if (starreds) {
2590 total_len += asdl_seq_LEN(starreds);
2591 }
2592
2593 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
2594
2595 Py_ssize_t i = 0;
2596 for (i = 0; i < args_len; i++) {
2597 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2598 }
2599 for (; i < total_len; i++) {
2600 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2601 }
2602
2603 return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2604 col_offset, end_lineno, end_col_offset, arena);
2605 }
2606