blob: a7add8fbb144ee94ef1e17629f8a54b76ff48d4e [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
3#include "../tokenizer.h"
4
5#include "pegen.h"
6#include "parse_string.h"
7
Guido van Rossumc001c092020-04-30 12:12:19 -07008PyObject *
9_PyPegen_new_type_comment(Parser *p, char *s)
10{
11 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
12 if (res == NULL) {
13 return NULL;
14 }
15 if (PyArena_AddPyObject(p->arena, res) < 0) {
16 Py_DECREF(res);
17 return NULL;
18 }
19 return res;
20}
21
22arg_ty
23_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
24{
25 if (tc == NULL) {
26 return a;
27 }
28 char *bytes = PyBytes_AsString(tc->bytes);
29 if (bytes == NULL) {
30 return NULL;
31 }
32 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
33 if (tco == NULL) {
34 return NULL;
35 }
36 return arg(a->arg, a->annotation, tco,
37 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
38 p->arena);
39}
40
Pablo Galindoc5fc1562020-04-22 23:29:27 +010041static int
42init_normalization(Parser *p)
43{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030044 if (p->normalize) {
45 return 1;
46 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010047 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
48 if (!m)
49 {
50 return 0;
51 }
52 p->normalize = PyObject_GetAttrString(m, "normalize");
53 Py_DECREF(m);
54 if (!p->normalize)
55 {
56 return 0;
57 }
58 return 1;
59}
60
Pablo Galindo2b74c832020-04-27 18:02:07 +010061/* Checks if the NOTEQUAL token is valid given the current parser flags
620 indicates success and nonzero indicates failure (an exception may be set) */
63int
64_PyPegen_check_barry_as_flufl(Parser *p) {
65 Token *t = p->tokens[p->fill - 1];
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, "<>")){
71 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
73 } else if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
74 return strcmp(tok_str, "!=");
75 }
76 return 0;
77}
78
Pablo Galindoc5fc1562020-04-22 23:29:27 +010079PyObject *
80_PyPegen_new_identifier(Parser *p, char *n)
81{
82 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
83 if (!id) {
84 goto error;
85 }
86 /* PyUnicode_DecodeUTF8 should always return a ready string. */
87 assert(PyUnicode_IS_READY(id));
88 /* Check whether there are non-ASCII characters in the
89 identifier; if so, normalize to NFKC. */
90 if (!PyUnicode_IS_ASCII(id))
91 {
92 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030093 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010094 {
95 Py_DECREF(id);
96 goto error;
97 }
98 PyObject *form = PyUnicode_InternFromString("NFKC");
99 if (form == NULL)
100 {
101 Py_DECREF(id);
102 goto error;
103 }
104 PyObject *args[2] = {form, id};
105 id2 = _PyObject_FastCall(p->normalize, args, 2);
106 Py_DECREF(id);
107 Py_DECREF(form);
108 if (!id2) {
109 goto error;
110 }
111 if (!PyUnicode_Check(id2))
112 {
113 PyErr_Format(PyExc_TypeError,
114 "unicodedata.normalize() must return a string, not "
115 "%.200s",
116 _PyType_Name(Py_TYPE(id2)));
117 Py_DECREF(id2);
118 goto error;
119 }
120 id = id2;
121 }
122 PyUnicode_InternInPlace(&id);
123 if (PyArena_AddPyObject(p->arena, id) < 0)
124 {
125 Py_DECREF(id);
126 goto error;
127 }
128 return id;
129
130error:
131 p->error_indicator = 1;
132 return NULL;
133}
134
135static PyObject *
136_create_dummy_identifier(Parser *p)
137{
138 return _PyPegen_new_identifier(p, "");
139}
140
141static inline Py_ssize_t
142byte_offset_to_character_offset(PyObject *line, int col_offset)
143{
144 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300145 if (!str) {
146 return 0;
147 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300148 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100149 if (!text) {
150 return 0;
151 }
152 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300153 str = PyUnicode_AsUTF8(text);
154 if (str != NULL && (int)strlen(str) == col_offset) {
155 size = strlen(str);
156 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100157 Py_DECREF(text);
158 return size;
159}
160
161const char *
162_PyPegen_get_expr_name(expr_ty e)
163{
164 switch (e->kind) {
165 case Attribute_kind:
166 return "attribute";
167 case Subscript_kind:
168 return "subscript";
169 case Starred_kind:
170 return "starred";
171 case Name_kind:
172 return "name";
173 case List_kind:
174 return "list";
175 case Tuple_kind:
176 return "tuple";
177 case Lambda_kind:
178 return "lambda";
179 case Call_kind:
180 return "function call";
181 case BoolOp_kind:
182 case BinOp_kind:
183 case UnaryOp_kind:
184 return "operator";
185 case GeneratorExp_kind:
186 return "generator expression";
187 case Yield_kind:
188 case YieldFrom_kind:
189 return "yield expression";
190 case Await_kind:
191 return "await expression";
192 case ListComp_kind:
193 return "list comprehension";
194 case SetComp_kind:
195 return "set comprehension";
196 case DictComp_kind:
197 return "dict comprehension";
198 case Dict_kind:
199 return "dict display";
200 case Set_kind:
201 return "set display";
202 case JoinedStr_kind:
203 case FormattedValue_kind:
204 return "f-string expression";
205 case Constant_kind: {
206 PyObject *value = e->v.Constant.value;
207 if (value == Py_None) {
208 return "None";
209 }
210 if (value == Py_False) {
211 return "False";
212 }
213 if (value == Py_True) {
214 return "True";
215 }
216 if (value == Py_Ellipsis) {
217 return "Ellipsis";
218 }
219 return "literal";
220 }
221 case Compare_kind:
222 return "comparison";
223 case IfExp_kind:
224 return "conditional expression";
225 case NamedExpr_kind:
226 return "named expression";
227 default:
228 PyErr_Format(PyExc_SystemError,
229 "unexpected expression in assignment %d (line %d)",
230 e->kind, e->lineno);
231 return NULL;
232 }
233}
234
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300235static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100236raise_decode_error(Parser *p)
237{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300238 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100239 const char *errtype = NULL;
240 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
241 errtype = "unicode error";
242 }
243 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
244 errtype = "value error";
245 }
246 if (errtype) {
247 PyObject *type, *value, *tback, *errstr;
248 PyErr_Fetch(&type, &value, &tback);
249 errstr = PyObject_Str(value);
250 if (errstr) {
251 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
252 Py_DECREF(errstr);
253 }
254 else {
255 PyErr_Clear();
256 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
257 }
258 Py_XDECREF(type);
259 Py_XDECREF(value);
260 Py_XDECREF(tback);
261 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300262
263 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100264}
265
266static void
267raise_tokenizer_init_error(PyObject *filename)
268{
269 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
270 || PyErr_ExceptionMatches(PyExc_ValueError)
271 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
272 return;
273 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300274 PyObject *errstr = NULL;
275 PyObject *tuple = NULL;
276 PyObject *type, *value, *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100277 PyErr_Fetch(&type, &value, &tback);
278 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300279 if (!errstr) {
280 goto error;
281 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100282
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300283 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100284 if (!tmp) {
285 goto error;
286 }
287
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300288 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100289 Py_DECREF(tmp);
290 if (!value) {
291 goto error;
292 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300293 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100294
295error:
296 Py_XDECREF(type);
297 Py_XDECREF(value);
298 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300299 Py_XDECREF(errstr);
300 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100301}
302
303static inline PyObject *
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300304get_error_line(char *buffer, int is_file)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100305{
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300306 const char *newline;
307 if (is_file) {
308 newline = strrchr(buffer, '\n');
309 } else {
310 newline = strchr(buffer, '\n');
311 }
312
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100313 if (newline) {
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300314 return PyUnicode_DecodeUTF8(buffer, newline - buffer, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100315 }
316 else {
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300317 return PyUnicode_DecodeUTF8(buffer, strlen(buffer), "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100318 }
319}
320
321static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100322tokenizer_error(Parser *p)
323{
324 if (PyErr_Occurred()) {
325 return -1;
326 }
327
328 const char *msg = NULL;
329 PyObject* errtype = PyExc_SyntaxError;
330 switch (p->tok->done) {
331 case E_TOKEN:
332 msg = "invalid token";
333 break;
334 case E_IDENTIFIER:
335 msg = "invalid character in identifier";
336 break;
337 case E_BADPREFIX:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300338 RAISE_SYNTAX_ERROR("invalid string prefix");
339 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100340 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300341 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
342 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100343 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300344 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
345 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300346 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300347 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
348 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100349 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300350 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
351 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100352 case E_INTR:
353 if (!PyErr_Occurred()) {
354 PyErr_SetNone(PyExc_KeyboardInterrupt);
355 }
356 return -1;
357 case E_NOMEM:
358 PyErr_NoMemory();
359 return -1;
360 case E_TABSPACE:
361 errtype = PyExc_TabError;
362 msg = "inconsistent use of tabs and spaces in indentation";
363 break;
364 case E_TOODEEP:
365 errtype = PyExc_IndentationError;
366 msg = "too many levels of indentation";
367 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100368 case E_LINECONT:
369 msg = "unexpected character after line continuation character";
370 break;
371 default:
372 msg = "unknown parsing error";
373 }
374
375 PyErr_Format(errtype, msg);
376 // There is no reliable column information for this error
377 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
378
379 return -1;
380}
381
382void *
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300383_PyPegen_raise_error(Parser *p, PyObject *errtype, int with_col_number, const char *errmsg, ...)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100384{
385 PyObject *value = NULL;
386 PyObject *errstr = NULL;
387 PyObject *loc = NULL;
388 PyObject *tmp = NULL;
389 Token *t = p->tokens[p->fill - 1];
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300390 Py_ssize_t col_number = !with_col_number;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391 va_list va;
392
393 va_start(va, errmsg);
394 errstr = PyUnicode_FromFormatV(errmsg, va);
395 va_end(va);
396 if (!errstr) {
397 goto error;
398 }
399
400 if (p->start_rule == Py_file_input) {
401 loc = PyErr_ProgramTextObject(p->tok->filename, t->lineno);
402 }
403
404 if (!loc) {
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300405 loc = get_error_line(p->tok->buf, p->start_rule == Py_file_input);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100406 }
407
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300408 if (loc && with_col_number) {
409 int col_offset;
410 if (t->col_offset == -1) {
411 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
412 intptr_t, int);
413 } else {
414 col_offset = t->col_offset + 1;
415 }
416 col_number = byte_offset_to_character_offset(loc, col_offset);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100417 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300418 else if (!loc) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100419 Py_INCREF(Py_None);
420 loc = Py_None;
421 }
422
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100423 tmp = Py_BuildValue("(OiiN)", p->tok->filename, t->lineno, col_number, loc);
424 if (!tmp) {
425 goto error;
426 }
427 value = PyTuple_Pack(2, errstr, tmp);
428 Py_DECREF(tmp);
429 if (!value) {
430 goto error;
431 }
432 PyErr_SetObject(errtype, value);
433
434 Py_DECREF(errstr);
435 Py_DECREF(value);
436 return NULL;
437
438error:
439 Py_XDECREF(errstr);
440 Py_XDECREF(loc);
441 return NULL;
442}
443
444void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
445 int kwarg_unpacking = 0;
446 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
447 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
448 if (!keyword->arg) {
449 kwarg_unpacking = 1;
450 }
451 }
452
453 const char *msg = NULL;
454 if (kwarg_unpacking) {
455 msg = "positional argument follows keyword argument unpacking";
456 } else {
457 msg = "positional argument follows keyword argument";
458 }
459
460 return RAISE_SYNTAX_ERROR(msg);
461}
462
463#if 0
464static const char *
465token_name(int type)
466{
467 if (0 <= type && type <= N_TOKENS) {
468 return _PyParser_TokenNames[type];
469 }
470 return "<Huh?>";
471}
472#endif
473
474// Here, mark is the start of the node, while p->mark is the end.
475// If node==NULL, they should be the same.
476int
477_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
478{
479 // Insert in front
480 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
481 if (m == NULL) {
482 return -1;
483 }
484 m->type = type;
485 m->node = node;
486 m->mark = p->mark;
487 m->next = p->tokens[mark]->memo;
488 p->tokens[mark]->memo = m;
489 return 0;
490}
491
492// Like _PyPegen_insert_memo(), but updates an existing node if found.
493int
494_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
495{
496 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
497 if (m->type == type) {
498 // Update existing node.
499 m->node = node;
500 m->mark = p->mark;
501 return 0;
502 }
503 }
504 // Insert new node.
505 return _PyPegen_insert_memo(p, mark, type, node);
506}
507
508// Return dummy NAME.
509void *
510_PyPegen_dummy_name(Parser *p, ...)
511{
512 static void *cache = NULL;
513
514 if (cache != NULL) {
515 return cache;
516 }
517
518 PyObject *id = _create_dummy_identifier(p);
519 if (!id) {
520 return NULL;
521 }
522 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
523 return cache;
524}
525
526static int
527_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
528{
529 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
530 return NAME;
531 }
532 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
533 if (strncmp(k->str, name, name_len) == 0) {
534 return k->type;
535 }
536 }
537 return NAME;
538}
539
Guido van Rossumc001c092020-04-30 12:12:19 -0700540static int
541growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
542 assert(initial_size > 0);
543 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
544 arr->size = initial_size;
545 arr->num_items = 0;
546
547 return arr->items != NULL;
548}
549
550static int
551growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
552 if (arr->num_items >= arr->size) {
553 size_t new_size = arr->size * 2;
554 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
555 if (!new_items_array) {
556 return 0;
557 }
558 arr->items = new_items_array;
559 arr->size = new_size;
560 }
561
562 arr->items[arr->num_items].lineno = lineno;
563 arr->items[arr->num_items].comment = comment; // Take ownership
564 arr->num_items++;
565 return 1;
566}
567
568static void
569growable_comment_array_deallocate(growable_comment_array *arr) {
570 for (unsigned i = 0; i < arr->num_items; i++) {
571 PyMem_Free(arr->items[i].comment);
572 }
573 PyMem_Free(arr->items);
574}
575
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100576int
577_PyPegen_fill_token(Parser *p)
578{
579 const char *start, *end;
580 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700581
582 // Record and skip '# type: ignore' comments
583 while (type == TYPE_IGNORE) {
584 Py_ssize_t len = end - start;
585 char *tag = PyMem_Malloc(len + 1);
586 if (tag == NULL) {
587 PyErr_NoMemory();
588 return -1;
589 }
590 strncpy(tag, start, len);
591 tag[len] = '\0';
592 // Ownership of tag passes to the growable array
593 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
594 PyErr_NoMemory();
595 return -1;
596 }
597 type = PyTokenizer_Get(p->tok, &start, &end);
598 }
599
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100600 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
601 type = NEWLINE; /* Add an extra newline */
602 p->parsing_started = 0;
603
Pablo Galindob94dbd72020-04-27 18:35:58 +0100604 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100605 p->tok->pendin = -p->tok->indent;
606 p->tok->indent = 0;
607 }
608 }
609 else {
610 p->parsing_started = 1;
611 }
612
613 if (p->fill == p->size) {
614 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300615 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
616 if (new_tokens == NULL) {
617 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100618 return -1;
619 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300620 else {
621 p->tokens = new_tokens;
622 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100623 for (int i = p->size; i < newsize; i++) {
624 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300625 if (p->tokens[i] == NULL) {
626 p->size = i; // Needed, in order to cleanup correctly after parser fails
627 PyErr_NoMemory();
628 return -1;
629 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100630 memset(p->tokens[i], '\0', sizeof(Token));
631 }
632 p->size = newsize;
633 }
634
635 Token *t = p->tokens[p->fill];
636 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
637 t->bytes = PyBytes_FromStringAndSize(start, end - start);
638 if (t->bytes == NULL) {
639 return -1;
640 }
641 PyArena_AddPyObject(p->arena, t->bytes);
642
643 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
644 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100645 int end_lineno = p->tok->lineno;
646 int col_offset = -1, end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100647 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100648 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100649 }
650 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100651 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100652 }
653
654 t->lineno = p->starting_lineno + lineno;
655 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
656 t->end_lineno = p->starting_lineno + end_lineno;
657 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
658
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100659 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300660
661 if (type == ERRORTOKEN) {
662 if (p->tok->done == E_DECODE) {
663 return raise_decode_error(p);
664 }
665 else {
666 return tokenizer_error(p);
667 }
668 }
669
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100670 return 0;
671}
672
673// Instrumentation to count the effectiveness of memoization.
674// The array counts the number of tokens skipped by memoization,
675// indexed by type.
676
677#define NSTATISTICS 2000
678static long memo_statistics[NSTATISTICS];
679
680void
681_PyPegen_clear_memo_statistics()
682{
683 for (int i = 0; i < NSTATISTICS; i++) {
684 memo_statistics[i] = 0;
685 }
686}
687
688PyObject *
689_PyPegen_get_memo_statistics()
690{
691 PyObject *ret = PyList_New(NSTATISTICS);
692 if (ret == NULL) {
693 return NULL;
694 }
695 for (int i = 0; i < NSTATISTICS; i++) {
696 PyObject *value = PyLong_FromLong(memo_statistics[i]);
697 if (value == NULL) {
698 Py_DECREF(ret);
699 return NULL;
700 }
701 // PyList_SetItem borrows a reference to value.
702 if (PyList_SetItem(ret, i, value) < 0) {
703 Py_DECREF(ret);
704 return NULL;
705 }
706 }
707 return ret;
708}
709
710int // bool
711_PyPegen_is_memoized(Parser *p, int type, void *pres)
712{
713 if (p->mark == p->fill) {
714 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300715 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100716 return -1;
717 }
718 }
719
720 Token *t = p->tokens[p->mark];
721
722 for (Memo *m = t->memo; m != NULL; m = m->next) {
723 if (m->type == type) {
724 if (0 <= type && type < NSTATISTICS) {
725 long count = m->mark - p->mark;
726 // A memoized negative result counts for one.
727 if (count <= 0) {
728 count = 1;
729 }
730 memo_statistics[type] += count;
731 }
732 p->mark = m->mark;
733 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100734 return 1;
735 }
736 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100737 return 0;
738}
739
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100740
741int
742_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
743{
744 int mark = p->mark;
745 void *res = func(p);
746 p->mark = mark;
747 return (res != NULL) == positive;
748}
749
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100750int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100751_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
752{
753 int mark = p->mark;
754 void *res = func(p, arg);
755 p->mark = mark;
756 return (res != NULL) == positive;
757}
758
759int
760_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
761{
762 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100763 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100764 p->mark = mark;
765 return (res != NULL) == positive;
766}
767
768Token *
769_PyPegen_expect_token(Parser *p, int type)
770{
771 if (p->mark == p->fill) {
772 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300773 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100774 return NULL;
775 }
776 }
777 Token *t = p->tokens[p->mark];
778 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100779 return NULL;
780 }
781 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100782 return t;
783}
784
785Token *
786_PyPegen_get_last_nonnwhitespace_token(Parser *p)
787{
788 assert(p->mark >= 0);
789 Token *token = NULL;
790 for (int m = p->mark - 1; m >= 0; m--) {
791 token = p->tokens[m];
792 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
793 break;
794 }
795 }
796 return token;
797}
798
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100799expr_ty
800_PyPegen_name_token(Parser *p)
801{
802 Token *t = _PyPegen_expect_token(p, NAME);
803 if (t == NULL) {
804 return NULL;
805 }
806 char* s = PyBytes_AsString(t->bytes);
807 if (!s) {
808 return NULL;
809 }
810 PyObject *id = _PyPegen_new_identifier(p, s);
811 if (id == NULL) {
812 return NULL;
813 }
814 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
815 p->arena);
816}
817
818void *
819_PyPegen_string_token(Parser *p)
820{
821 return _PyPegen_expect_token(p, STRING);
822}
823
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100824static PyObject *
825parsenumber_raw(const char *s)
826{
827 const char *end;
828 long x;
829 double dx;
830 Py_complex compl;
831 int imflag;
832
833 assert(s != NULL);
834 errno = 0;
835 end = s + strlen(s) - 1;
836 imflag = *end == 'j' || *end == 'J';
837 if (s[0] == '0') {
838 x = (long)PyOS_strtoul(s, (char **)&end, 0);
839 if (x < 0 && errno == 0) {
840 return PyLong_FromString(s, (char **)0, 0);
841 }
842 }
843 else
844 x = PyOS_strtol(s, (char **)&end, 0);
845 if (*end == '\0') {
846 if (errno != 0)
847 return PyLong_FromString(s, (char **)0, 0);
848 return PyLong_FromLong(x);
849 }
850 /* XXX Huge floats may silently fail */
851 if (imflag) {
852 compl.real = 0.;
853 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
854 if (compl.imag == -1.0 && PyErr_Occurred())
855 return NULL;
856 return PyComplex_FromCComplex(compl);
857 }
858 else {
859 dx = PyOS_string_to_double(s, NULL, NULL);
860 if (dx == -1.0 && PyErr_Occurred())
861 return NULL;
862 return PyFloat_FromDouble(dx);
863 }
864}
865
866static PyObject *
867parsenumber(const char *s)
868{
869 char *dup, *end;
870 PyObject *res = NULL;
871
872 assert(s != NULL);
873
874 if (strchr(s, '_') == NULL) {
875 return parsenumber_raw(s);
876 }
877 /* Create a duplicate without underscores. */
878 dup = PyMem_Malloc(strlen(s) + 1);
879 if (dup == NULL) {
880 return PyErr_NoMemory();
881 }
882 end = dup;
883 for (; *s; s++) {
884 if (*s != '_') {
885 *end++ = *s;
886 }
887 }
888 *end = '\0';
889 res = parsenumber_raw(dup);
890 PyMem_Free(dup);
891 return res;
892}
893
894expr_ty
895_PyPegen_number_token(Parser *p)
896{
897 Token *t = _PyPegen_expect_token(p, NUMBER);
898 if (t == NULL) {
899 return NULL;
900 }
901
902 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100903 if (num_raw == NULL) {
904 return NULL;
905 }
906
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300907 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
908 p->error_indicator = 1;
909 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported"
910 "in Python 3.6 and greater");
911 }
912
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100913 PyObject *c = parsenumber(num_raw);
914
915 if (c == NULL) {
916 return NULL;
917 }
918
919 if (PyArena_AddPyObject(p->arena, c) < 0) {
920 Py_DECREF(c);
921 return NULL;
922 }
923
924 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
925 p->arena);
926}
927
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300928static int // bool
929newline_in_string(Parser *p, const char *cur)
930{
931 for (char c = *cur; cur >= p->tok->buf; c = *--cur) {
932 if (c == '\'' || c == '"') {
933 return 1;
934 }
935 }
936 return 0;
937}
938
939/* Check that the source for a single input statement really is a single
940 statement by looking at what is left in the buffer after parsing.
941 Trailing whitespace and comments are OK. */
942static int // bool
943bad_single_statement(Parser *p)
944{
945 const char *cur = strchr(p->tok->buf, '\n');
946
947 /* Newlines are allowed if preceded by a line continuation character
948 or if they appear inside a string. */
949 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
950 return 0;
951 }
952 char c = *cur;
953
954 for (;;) {
955 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
956 c = *++cur;
957 }
958
959 if (!c) {
960 return 0;
961 }
962
963 if (c != '#') {
964 return 1;
965 }
966
967 /* Suck up comment. */
968 while (c && c != '\n') {
969 c = *++cur;
970 }
971 }
972}
973
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100974void
975_PyPegen_Parser_Free(Parser *p)
976{
977 Py_XDECREF(p->normalize);
978 for (int i = 0; i < p->size; i++) {
979 PyMem_Free(p->tokens[i]);
980 }
981 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700982 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100983 PyMem_Free(p);
984}
985
Pablo Galindo2b74c832020-04-27 18:02:07 +0100986static int
987compute_parser_flags(PyCompilerFlags *flags)
988{
989 int parser_flags = 0;
990 if (!flags) {
991 return 0;
992 }
993 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
994 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
995 }
996 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
997 parser_flags |= PyPARSE_IGNORE_COOKIE;
998 }
999 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1000 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1001 }
1002 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1003 parser_flags |= PyPARSE_TYPE_COMMENTS;
1004 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001005 if (flags->cf_feature_version < 7) {
1006 parser_flags |= PyPARSE_ASYNC_HACKS;
1007 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001008 return parser_flags;
1009}
1010
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001011Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001012_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001013 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001014{
1015 Parser *p = PyMem_Malloc(sizeof(Parser));
1016 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001017 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001018 }
1019 assert(tok != NULL);
1020 p->tok = tok;
1021 p->keywords = NULL;
1022 p->n_keyword_lists = -1;
1023 p->tokens = PyMem_Malloc(sizeof(Token *));
1024 if (!p->tokens) {
1025 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001026 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001027 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001028 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001029 if (!p->tokens) {
1030 PyMem_Free(p->tokens);
1031 PyMem_Free(p);
1032 return (Parser *) PyErr_NoMemory();
1033 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001034 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1035 PyMem_Free(p->tokens[0]);
1036 PyMem_Free(p->tokens);
1037 PyMem_Free(p);
1038 return (Parser *) PyErr_NoMemory();
1039 }
1040
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001041 p->mark = 0;
1042 p->fill = 0;
1043 p->size = 1;
1044
1045 p->errcode = errcode;
1046 p->arena = arena;
1047 p->start_rule = start_rule;
1048 p->parsing_started = 0;
1049 p->normalize = NULL;
1050 p->error_indicator = 0;
1051
1052 p->starting_lineno = 0;
1053 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001054 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001055 p->feature_version = feature_version;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001056
1057 return p;
1058}
1059
1060void *
1061_PyPegen_run_parser(Parser *p)
1062{
1063 void *res = _PyPegen_parse(p);
1064 if (res == NULL) {
1065 if (PyErr_Occurred()) {
1066 return NULL;
1067 }
1068 if (p->fill == 0) {
1069 RAISE_SYNTAX_ERROR("error at start before reading any input");
1070 }
1071 else if (p->tok->done == E_EOF) {
1072 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1073 }
1074 else {
1075 if (p->tokens[p->fill-1]->type == INDENT) {
1076 RAISE_INDENTATION_ERROR("unexpected indent");
1077 }
1078 else if (p->tokens[p->fill-1]->type == DEDENT) {
1079 RAISE_INDENTATION_ERROR("unexpected unindent");
1080 }
1081 else {
1082 RAISE_SYNTAX_ERROR("invalid syntax");
1083 }
1084 }
1085 return NULL;
1086 }
1087
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001088 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1089 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1090 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1091 }
1092
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001093 return res;
1094}
1095
1096mod_ty
1097_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1098 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001099 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001100{
1101 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1102 if (tok == NULL) {
1103 if (PyErr_Occurred()) {
1104 raise_tokenizer_init_error(filename_ob);
1105 return NULL;
1106 }
1107 return NULL;
1108 }
1109 // This transfers the ownership to the tokenizer
1110 tok->filename = filename_ob;
1111 Py_INCREF(filename_ob);
1112
1113 // From here on we need to clean up even if there's an error
1114 mod_ty result = NULL;
1115
Pablo Galindo2b74c832020-04-27 18:02:07 +01001116 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001117 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1118 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001119 if (p == NULL) {
1120 goto error;
1121 }
1122
1123 result = _PyPegen_run_parser(p);
1124 _PyPegen_Parser_Free(p);
1125
1126error:
1127 PyTokenizer_Free(tok);
1128 return result;
1129}
1130
1131mod_ty
1132_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001133 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001134{
1135 FILE *fp = fopen(filename, "rb");
1136 if (fp == NULL) {
1137 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1138 return NULL;
1139 }
1140
1141 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001142 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001143
1144 fclose(fp);
1145 return result;
1146}
1147
1148mod_ty
1149_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001150 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001151{
1152 int exec_input = start_rule == Py_file_input;
1153
1154 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001155 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001156 tok = PyTokenizer_FromUTF8(str, exec_input);
1157 } else {
1158 tok = PyTokenizer_FromString(str, exec_input);
1159 }
1160 if (tok == NULL) {
1161 if (PyErr_Occurred()) {
1162 raise_tokenizer_init_error(filename_ob);
1163 }
1164 return NULL;
1165 }
1166 // This transfers the ownership to the tokenizer
1167 tok->filename = filename_ob;
1168 Py_INCREF(filename_ob);
1169
1170 // We need to clear up from here on
1171 mod_ty result = NULL;
1172
Pablo Galindo2b74c832020-04-27 18:02:07 +01001173 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001174 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Guido van Rossumc001c092020-04-30 12:12:19 -07001175 tok->type_comments = (parser_flags & PyPARSE_TYPE_COMMENTS) > 0;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001176 tok->async_hacks = (parser_flags & PyPARSE_ASYNC_HACKS) > 0;
Guido van Rossumc001c092020-04-30 12:12:19 -07001177
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001178 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1179 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001180 if (p == NULL) {
1181 goto error;
1182 }
1183
1184 result = _PyPegen_run_parser(p);
1185 _PyPegen_Parser_Free(p);
1186
1187error:
1188 PyTokenizer_Free(tok);
1189 return result;
1190}
1191
1192void *
1193_PyPegen_interactive_exit(Parser *p)
1194{
1195 if (p->errcode) {
1196 *(p->errcode) = E_EOF;
1197 }
1198 return NULL;
1199}
1200
1201/* Creates a single-element asdl_seq* that contains a */
1202asdl_seq *
1203_PyPegen_singleton_seq(Parser *p, void *a)
1204{
1205 assert(a != NULL);
1206 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1207 if (!seq) {
1208 return NULL;
1209 }
1210 asdl_seq_SET(seq, 0, a);
1211 return seq;
1212}
1213
1214/* Creates a copy of seq and prepends a to it */
1215asdl_seq *
1216_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1217{
1218 assert(a != NULL);
1219 if (!seq) {
1220 return _PyPegen_singleton_seq(p, a);
1221 }
1222
1223 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1224 if (!new_seq) {
1225 return NULL;
1226 }
1227
1228 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001229 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001230 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1231 }
1232 return new_seq;
1233}
1234
Guido van Rossumc001c092020-04-30 12:12:19 -07001235/* Creates a copy of seq and appends a to it */
1236asdl_seq *
1237_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1238{
1239 assert(a != NULL);
1240 if (!seq) {
1241 return _PyPegen_singleton_seq(p, a);
1242 }
1243
1244 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1245 if (!new_seq) {
1246 return NULL;
1247 }
1248
1249 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1250 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1251 }
1252 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1253 return new_seq;
1254}
1255
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001256static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001257_get_flattened_seq_size(asdl_seq *seqs)
1258{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001259 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001260 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1261 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1262 size += asdl_seq_LEN(inner_seq);
1263 }
1264 return size;
1265}
1266
1267/* Flattens an asdl_seq* of asdl_seq*s */
1268asdl_seq *
1269_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1270{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001271 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001272 assert(flattened_seq_size > 0);
1273
1274 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1275 if (!flattened_seq) {
1276 return NULL;
1277 }
1278
1279 int flattened_seq_idx = 0;
1280 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1281 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001282 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001283 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1284 }
1285 }
1286 assert(flattened_seq_idx == flattened_seq_size);
1287
1288 return flattened_seq;
1289}
1290
1291/* Creates a new name of the form <first_name>.<second_name> */
1292expr_ty
1293_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1294{
1295 assert(first_name != NULL && second_name != NULL);
1296 PyObject *first_identifier = first_name->v.Name.id;
1297 PyObject *second_identifier = second_name->v.Name.id;
1298
1299 if (PyUnicode_READY(first_identifier) == -1) {
1300 return NULL;
1301 }
1302 if (PyUnicode_READY(second_identifier) == -1) {
1303 return NULL;
1304 }
1305 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1306 if (!first_str) {
1307 return NULL;
1308 }
1309 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1310 if (!second_str) {
1311 return NULL;
1312 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001313 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001314
1315 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1316 if (!str) {
1317 return NULL;
1318 }
1319
1320 char *s = PyBytes_AS_STRING(str);
1321 if (!s) {
1322 return NULL;
1323 }
1324
1325 strcpy(s, first_str);
1326 s += strlen(first_str);
1327 *s++ = '.';
1328 strcpy(s, second_str);
1329 s += strlen(second_str);
1330 *s = '\0';
1331
1332 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1333 Py_DECREF(str);
1334 if (!uni) {
1335 return NULL;
1336 }
1337 PyUnicode_InternInPlace(&uni);
1338 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1339 Py_DECREF(uni);
1340 return NULL;
1341 }
1342
1343 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1344}
1345
1346/* Counts the total number of dots in seq's tokens */
1347int
1348_PyPegen_seq_count_dots(asdl_seq *seq)
1349{
1350 int number_of_dots = 0;
1351 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1352 Token *current_expr = asdl_seq_GET(seq, i);
1353 switch (current_expr->type) {
1354 case ELLIPSIS:
1355 number_of_dots += 3;
1356 break;
1357 case DOT:
1358 number_of_dots += 1;
1359 break;
1360 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001361 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001362 }
1363 }
1364
1365 return number_of_dots;
1366}
1367
1368/* Creates an alias with '*' as the identifier name */
1369alias_ty
1370_PyPegen_alias_for_star(Parser *p)
1371{
1372 PyObject *str = PyUnicode_InternFromString("*");
1373 if (!str) {
1374 return NULL;
1375 }
1376 if (PyArena_AddPyObject(p->arena, str) < 0) {
1377 Py_DECREF(str);
1378 return NULL;
1379 }
1380 return alias(str, NULL, p->arena);
1381}
1382
1383/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1384asdl_seq *
1385_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1386{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001387 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001388 assert(len > 0);
1389
1390 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1391 if (!new_seq) {
1392 return NULL;
1393 }
1394 for (Py_ssize_t i = 0; i < len; i++) {
1395 expr_ty e = asdl_seq_GET(seq, i);
1396 asdl_seq_SET(new_seq, i, e->v.Name.id);
1397 }
1398 return new_seq;
1399}
1400
1401/* Constructs a CmpopExprPair */
1402CmpopExprPair *
1403_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1404{
1405 assert(expr != NULL);
1406 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1407 if (!a) {
1408 return NULL;
1409 }
1410 a->cmpop = cmpop;
1411 a->expr = expr;
1412 return a;
1413}
1414
1415asdl_int_seq *
1416_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1417{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001418 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001419 assert(len > 0);
1420
1421 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1422 if (!new_seq) {
1423 return NULL;
1424 }
1425 for (Py_ssize_t i = 0; i < len; i++) {
1426 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1427 asdl_seq_SET(new_seq, i, pair->cmpop);
1428 }
1429 return new_seq;
1430}
1431
1432asdl_seq *
1433_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1434{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001435 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001436 assert(len > 0);
1437
1438 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1439 if (!new_seq) {
1440 return NULL;
1441 }
1442 for (Py_ssize_t i = 0; i < len; i++) {
1443 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1444 asdl_seq_SET(new_seq, i, pair->expr);
1445 }
1446 return new_seq;
1447}
1448
1449/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1450static asdl_seq *
1451_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1452{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001453 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001454 if (len == 0) {
1455 return NULL;
1456 }
1457
1458 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1459 if (!new_seq) {
1460 return NULL;
1461 }
1462 for (Py_ssize_t i = 0; i < len; i++) {
1463 expr_ty e = asdl_seq_GET(seq, i);
1464 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1465 }
1466 return new_seq;
1467}
1468
1469static expr_ty
1470_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1471{
1472 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1473}
1474
1475static expr_ty
1476_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1477{
1478 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1479}
1480
1481static expr_ty
1482_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1483{
1484 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1485}
1486
1487static expr_ty
1488_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1489{
1490 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1491}
1492
1493static expr_ty
1494_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1495{
1496 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1497}
1498
1499static expr_ty
1500_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1501{
1502 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1503}
1504
1505/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1506expr_ty
1507_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1508{
1509 assert(expr != NULL);
1510
1511 expr_ty new = NULL;
1512 switch (expr->kind) {
1513 case Name_kind:
1514 new = _set_name_context(p, expr, ctx);
1515 break;
1516 case Tuple_kind:
1517 new = _set_tuple_context(p, expr, ctx);
1518 break;
1519 case List_kind:
1520 new = _set_list_context(p, expr, ctx);
1521 break;
1522 case Subscript_kind:
1523 new = _set_subscript_context(p, expr, ctx);
1524 break;
1525 case Attribute_kind:
1526 new = _set_attribute_context(p, expr, ctx);
1527 break;
1528 case Starred_kind:
1529 new = _set_starred_context(p, expr, ctx);
1530 break;
1531 default:
1532 new = expr;
1533 }
1534 return new;
1535}
1536
1537/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1538KeyValuePair *
1539_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1540{
1541 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1542 if (!a) {
1543 return NULL;
1544 }
1545 a->key = key;
1546 a->value = value;
1547 return a;
1548}
1549
1550/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1551asdl_seq *
1552_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1553{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001554 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001555 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1556 if (!new_seq) {
1557 return NULL;
1558 }
1559 for (Py_ssize_t i = 0; i < len; i++) {
1560 KeyValuePair *pair = asdl_seq_GET(seq, i);
1561 asdl_seq_SET(new_seq, i, pair->key);
1562 }
1563 return new_seq;
1564}
1565
1566/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1567asdl_seq *
1568_PyPegen_get_values(Parser *p, asdl_seq *seq)
1569{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001570 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001571 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1572 if (!new_seq) {
1573 return NULL;
1574 }
1575 for (Py_ssize_t i = 0; i < len; i++) {
1576 KeyValuePair *pair = asdl_seq_GET(seq, i);
1577 asdl_seq_SET(new_seq, i, pair->value);
1578 }
1579 return new_seq;
1580}
1581
1582/* Constructs a NameDefaultPair */
1583NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001584_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001585{
1586 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1587 if (!a) {
1588 return NULL;
1589 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001590 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001591 a->value = value;
1592 return a;
1593}
1594
1595/* Constructs a SlashWithDefault */
1596SlashWithDefault *
1597_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1598{
1599 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1600 if (!a) {
1601 return NULL;
1602 }
1603 a->plain_names = plain_names;
1604 a->names_with_defaults = names_with_defaults;
1605 return a;
1606}
1607
1608/* Constructs a StarEtc */
1609StarEtc *
1610_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1611{
1612 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1613 if (!a) {
1614 return NULL;
1615 }
1616 a->vararg = vararg;
1617 a->kwonlyargs = kwonlyargs;
1618 a->kwarg = kwarg;
1619 return a;
1620}
1621
1622asdl_seq *
1623_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1624{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001625 Py_ssize_t first_len = asdl_seq_LEN(a);
1626 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001627 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1628 if (!new_seq) {
1629 return NULL;
1630 }
1631
1632 int k = 0;
1633 for (Py_ssize_t i = 0; i < first_len; i++) {
1634 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1635 }
1636 for (Py_ssize_t i = 0; i < second_len; i++) {
1637 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1638 }
1639
1640 return new_seq;
1641}
1642
1643static asdl_seq *
1644_get_names(Parser *p, asdl_seq *names_with_defaults)
1645{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001646 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001647 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1648 if (!seq) {
1649 return NULL;
1650 }
1651 for (Py_ssize_t i = 0; i < len; i++) {
1652 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1653 asdl_seq_SET(seq, i, pair->arg);
1654 }
1655 return seq;
1656}
1657
1658static asdl_seq *
1659_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1660{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001661 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001662 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1663 if (!seq) {
1664 return NULL;
1665 }
1666 for (Py_ssize_t i = 0; i < len; i++) {
1667 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1668 asdl_seq_SET(seq, i, pair->value);
1669 }
1670 return seq;
1671}
1672
1673/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1674arguments_ty
1675_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1676 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1677 asdl_seq *names_with_default, StarEtc *star_etc)
1678{
1679 asdl_seq *posonlyargs;
1680 if (slash_without_default != NULL) {
1681 posonlyargs = slash_without_default;
1682 }
1683 else if (slash_with_default != NULL) {
1684 asdl_seq *slash_with_default_names =
1685 _get_names(p, slash_with_default->names_with_defaults);
1686 if (!slash_with_default_names) {
1687 return NULL;
1688 }
1689 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1690 if (!posonlyargs) {
1691 return NULL;
1692 }
1693 }
1694 else {
1695 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1696 if (!posonlyargs) {
1697 return NULL;
1698 }
1699 }
1700
1701 asdl_seq *posargs;
1702 if (plain_names != NULL && names_with_default != NULL) {
1703 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1704 if (!names_with_default_names) {
1705 return NULL;
1706 }
1707 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1708 if (!posargs) {
1709 return NULL;
1710 }
1711 }
1712 else if (plain_names == NULL && names_with_default != NULL) {
1713 posargs = _get_names(p, names_with_default);
1714 if (!posargs) {
1715 return NULL;
1716 }
1717 }
1718 else if (plain_names != NULL && names_with_default == NULL) {
1719 posargs = plain_names;
1720 }
1721 else {
1722 posargs = _Py_asdl_seq_new(0, p->arena);
1723 if (!posargs) {
1724 return NULL;
1725 }
1726 }
1727
1728 asdl_seq *posdefaults;
1729 if (slash_with_default != NULL && names_with_default != NULL) {
1730 asdl_seq *slash_with_default_values =
1731 _get_defaults(p, slash_with_default->names_with_defaults);
1732 if (!slash_with_default_values) {
1733 return NULL;
1734 }
1735 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1736 if (!names_with_default_values) {
1737 return NULL;
1738 }
1739 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1740 if (!posdefaults) {
1741 return NULL;
1742 }
1743 }
1744 else if (slash_with_default == NULL && names_with_default != NULL) {
1745 posdefaults = _get_defaults(p, names_with_default);
1746 if (!posdefaults) {
1747 return NULL;
1748 }
1749 }
1750 else if (slash_with_default != NULL && names_with_default == NULL) {
1751 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1752 if (!posdefaults) {
1753 return NULL;
1754 }
1755 }
1756 else {
1757 posdefaults = _Py_asdl_seq_new(0, p->arena);
1758 if (!posdefaults) {
1759 return NULL;
1760 }
1761 }
1762
1763 arg_ty vararg = NULL;
1764 if (star_etc != NULL && star_etc->vararg != NULL) {
1765 vararg = star_etc->vararg;
1766 }
1767
1768 asdl_seq *kwonlyargs;
1769 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1770 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1771 if (!kwonlyargs) {
1772 return NULL;
1773 }
1774 }
1775 else {
1776 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1777 if (!kwonlyargs) {
1778 return NULL;
1779 }
1780 }
1781
1782 asdl_seq *kwdefaults;
1783 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1784 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1785 if (!kwdefaults) {
1786 return NULL;
1787 }
1788 }
1789 else {
1790 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1791 if (!kwdefaults) {
1792 return NULL;
1793 }
1794 }
1795
1796 arg_ty kwarg = NULL;
1797 if (star_etc != NULL && star_etc->kwarg != NULL) {
1798 kwarg = star_etc->kwarg;
1799 }
1800
1801 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1802 posdefaults, p->arena);
1803}
1804
1805/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1806 * arguments. */
1807arguments_ty
1808_PyPegen_empty_arguments(Parser *p)
1809{
1810 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1811 if (!posonlyargs) {
1812 return NULL;
1813 }
1814 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1815 if (!posargs) {
1816 return NULL;
1817 }
1818 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1819 if (!posdefaults) {
1820 return NULL;
1821 }
1822 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1823 if (!kwonlyargs) {
1824 return NULL;
1825 }
1826 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1827 if (!kwdefaults) {
1828 return NULL;
1829 }
1830
1831 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1832 p->arena);
1833}
1834
1835/* Encapsulates the value of an operator_ty into an AugOperator struct */
1836AugOperator *
1837_PyPegen_augoperator(Parser *p, operator_ty kind)
1838{
1839 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1840 if (!a) {
1841 return NULL;
1842 }
1843 a->kind = kind;
1844 return a;
1845}
1846
1847/* Construct a FunctionDef equivalent to function_def, but with decorators */
1848stmt_ty
1849_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1850{
1851 assert(function_def != NULL);
1852 if (function_def->kind == AsyncFunctionDef_kind) {
1853 return _Py_AsyncFunctionDef(
1854 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1855 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1856 function_def->v.FunctionDef.type_comment, function_def->lineno,
1857 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1858 p->arena);
1859 }
1860
1861 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1862 function_def->v.FunctionDef.body, decorators,
1863 function_def->v.FunctionDef.returns,
1864 function_def->v.FunctionDef.type_comment, function_def->lineno,
1865 function_def->col_offset, function_def->end_lineno,
1866 function_def->end_col_offset, p->arena);
1867}
1868
1869/* Construct a ClassDef equivalent to class_def, but with decorators */
1870stmt_ty
1871_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1872{
1873 assert(class_def != NULL);
1874 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1875 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1876 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1877 class_def->end_col_offset, p->arena);
1878}
1879
1880/* Construct a KeywordOrStarred */
1881KeywordOrStarred *
1882_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1883{
1884 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1885 if (!a) {
1886 return NULL;
1887 }
1888 a->element = element;
1889 a->is_keyword = is_keyword;
1890 return a;
1891}
1892
1893/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1894static int
1895_seq_number_of_starred_exprs(asdl_seq *seq)
1896{
1897 int n = 0;
1898 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1899 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1900 if (!k->is_keyword) {
1901 n++;
1902 }
1903 }
1904 return n;
1905}
1906
1907/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1908asdl_seq *
1909_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1910{
1911 int new_len = _seq_number_of_starred_exprs(kwargs);
1912 if (new_len == 0) {
1913 return NULL;
1914 }
1915 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1916 if (!new_seq) {
1917 return NULL;
1918 }
1919
1920 int idx = 0;
1921 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1922 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1923 if (!k->is_keyword) {
1924 asdl_seq_SET(new_seq, idx++, k->element);
1925 }
1926 }
1927 return new_seq;
1928}
1929
1930/* Return a new asdl_seq* with only the keywords in kwargs */
1931asdl_seq *
1932_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1933{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001934 Py_ssize_t len = asdl_seq_LEN(kwargs);
1935 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001936 if (new_len == 0) {
1937 return NULL;
1938 }
1939 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1940 if (!new_seq) {
1941 return NULL;
1942 }
1943
1944 int idx = 0;
1945 for (Py_ssize_t i = 0; i < len; i++) {
1946 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1947 if (k->is_keyword) {
1948 asdl_seq_SET(new_seq, idx++, k->element);
1949 }
1950 }
1951 return new_seq;
1952}
1953
1954expr_ty
1955_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1956{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001957 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001958 assert(len > 0);
1959
1960 Token *first = asdl_seq_GET(strings, 0);
1961 Token *last = asdl_seq_GET(strings, len - 1);
1962
1963 int bytesmode = 0;
1964 PyObject *bytes_str = NULL;
1965
1966 FstringParser state;
1967 _PyPegen_FstringParser_Init(&state);
1968
1969 for (Py_ssize_t i = 0; i < len; i++) {
1970 Token *t = asdl_seq_GET(strings, i);
1971
1972 int this_bytesmode;
1973 int this_rawmode;
1974 PyObject *s;
1975 const char *fstr;
1976 Py_ssize_t fstrlen = -1;
1977
1978 char *this_str = PyBytes_AsString(t->bytes);
1979 if (!this_str) {
1980 goto error;
1981 }
1982
1983 if (_PyPegen_parsestr(p, this_str, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen) != 0) {
1984 goto error;
1985 }
1986
1987 /* Check that we are not mixing bytes with unicode. */
1988 if (i != 0 && bytesmode != this_bytesmode) {
1989 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1990 Py_XDECREF(s);
1991 goto error;
1992 }
1993 bytesmode = this_bytesmode;
1994
1995 if (fstr != NULL) {
1996 assert(s == NULL && !bytesmode);
1997
1998 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
1999 this_rawmode, 0, first, t, last);
2000 if (result < 0) {
2001 goto error;
2002 }
2003 }
2004 else {
2005 /* String or byte string. */
2006 assert(s != NULL && fstr == NULL);
2007 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2008
2009 if (bytesmode) {
2010 if (i == 0) {
2011 bytes_str = s;
2012 }
2013 else {
2014 PyBytes_ConcatAndDel(&bytes_str, s);
2015 if (!bytes_str) {
2016 goto error;
2017 }
2018 }
2019 }
2020 else {
2021 /* This is a regular string. Concatenate it. */
2022 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2023 goto error;
2024 }
2025 }
2026 }
2027 }
2028
2029 if (bytesmode) {
2030 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2031 goto error;
2032 }
2033 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2034 last->end_col_offset, p->arena);
2035 }
2036
2037 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2038
2039error:
2040 Py_XDECREF(bytes_str);
2041 _PyPegen_FstringParser_Dealloc(&state);
2042 if (PyErr_Occurred()) {
2043 raise_decode_error(p);
2044 }
2045 return NULL;
2046}
Guido van Rossumc001c092020-04-30 12:12:19 -07002047
2048mod_ty
2049_PyPegen_make_module(Parser *p, asdl_seq *a) {
2050 asdl_seq *type_ignores = NULL;
2051 Py_ssize_t num = p->type_ignore_comments.num_items;
2052 if (num > 0) {
2053 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2054 type_ignores = _Py_asdl_seq_new(num, p->arena);
2055 if (type_ignores == NULL) {
2056 return NULL;
2057 }
2058 for (int i = 0; i < num; i++) {
2059 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2060 if (tag == NULL) {
2061 return NULL;
2062 }
2063 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2064 if (ti == NULL) {
2065 return NULL;
2066 }
2067 asdl_seq_SET(type_ignores, i, ti);
2068 }
2069 }
2070 return Module(a, type_ignores, p->arena);
2071}