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