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