blob: 9858f71c83c790033f628c4512249a837341105b [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;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300392 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100393
394 va_start(va, errmsg);
395 errstr = PyUnicode_FromFormatV(errmsg, va);
396 va_end(va);
397 if (!errstr) {
398 goto error;
399 }
400
401 if (p->start_rule == Py_file_input) {
402 loc = PyErr_ProgramTextObject(p->tok->filename, t->lineno);
403 }
404
405 if (!loc) {
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300406 loc = get_error_line(p->tok->buf, p->start_rule == Py_file_input);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100407 }
408
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300409 if (loc && with_col_number) {
410 int col_offset;
411 if (t->col_offset == -1) {
412 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
413 intptr_t, int);
414 } else {
415 col_offset = t->col_offset + 1;
416 }
417 col_number = byte_offset_to_character_offset(loc, col_offset);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100418 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300419 else if (!loc) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100420 Py_INCREF(Py_None);
421 loc = Py_None;
422 }
423
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100424 tmp = Py_BuildValue("(OiiN)", p->tok->filename, t->lineno, col_number, loc);
425 if (!tmp) {
426 goto error;
427 }
428 value = PyTuple_Pack(2, errstr, tmp);
429 Py_DECREF(tmp);
430 if (!value) {
431 goto error;
432 }
433 PyErr_SetObject(errtype, value);
434
435 Py_DECREF(errstr);
436 Py_DECREF(value);
437 return NULL;
438
439error:
440 Py_XDECREF(errstr);
441 Py_XDECREF(loc);
442 return NULL;
443}
444
445void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
446 int kwarg_unpacking = 0;
447 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
448 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
449 if (!keyword->arg) {
450 kwarg_unpacking = 1;
451 }
452 }
453
454 const char *msg = NULL;
455 if (kwarg_unpacking) {
456 msg = "positional argument follows keyword argument unpacking";
457 } else {
458 msg = "positional argument follows keyword argument";
459 }
460
461 return RAISE_SYNTAX_ERROR(msg);
462}
463
464#if 0
465static const char *
466token_name(int type)
467{
468 if (0 <= type && type <= N_TOKENS) {
469 return _PyParser_TokenNames[type];
470 }
471 return "<Huh?>";
472}
473#endif
474
475// Here, mark is the start of the node, while p->mark is the end.
476// If node==NULL, they should be the same.
477int
478_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
479{
480 // Insert in front
481 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
482 if (m == NULL) {
483 return -1;
484 }
485 m->type = type;
486 m->node = node;
487 m->mark = p->mark;
488 m->next = p->tokens[mark]->memo;
489 p->tokens[mark]->memo = m;
490 return 0;
491}
492
493// Like _PyPegen_insert_memo(), but updates an existing node if found.
494int
495_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
496{
497 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
498 if (m->type == type) {
499 // Update existing node.
500 m->node = node;
501 m->mark = p->mark;
502 return 0;
503 }
504 }
505 // Insert new node.
506 return _PyPegen_insert_memo(p, mark, type, node);
507}
508
509// Return dummy NAME.
510void *
511_PyPegen_dummy_name(Parser *p, ...)
512{
513 static void *cache = NULL;
514
515 if (cache != NULL) {
516 return cache;
517 }
518
519 PyObject *id = _create_dummy_identifier(p);
520 if (!id) {
521 return NULL;
522 }
523 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
524 return cache;
525}
526
527static int
528_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
529{
530 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
531 return NAME;
532 }
533 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
534 if (strncmp(k->str, name, name_len) == 0) {
535 return k->type;
536 }
537 }
538 return NAME;
539}
540
Guido van Rossumc001c092020-04-30 12:12:19 -0700541static int
542growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
543 assert(initial_size > 0);
544 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
545 arr->size = initial_size;
546 arr->num_items = 0;
547
548 return arr->items != NULL;
549}
550
551static int
552growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
553 if (arr->num_items >= arr->size) {
554 size_t new_size = arr->size * 2;
555 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
556 if (!new_items_array) {
557 return 0;
558 }
559 arr->items = new_items_array;
560 arr->size = new_size;
561 }
562
563 arr->items[arr->num_items].lineno = lineno;
564 arr->items[arr->num_items].comment = comment; // Take ownership
565 arr->num_items++;
566 return 1;
567}
568
569static void
570growable_comment_array_deallocate(growable_comment_array *arr) {
571 for (unsigned i = 0; i < arr->num_items; i++) {
572 PyMem_Free(arr->items[i].comment);
573 }
574 PyMem_Free(arr->items);
575}
576
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100577int
578_PyPegen_fill_token(Parser *p)
579{
580 const char *start, *end;
581 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700582
583 // Record and skip '# type: ignore' comments
584 while (type == TYPE_IGNORE) {
585 Py_ssize_t len = end - start;
586 char *tag = PyMem_Malloc(len + 1);
587 if (tag == NULL) {
588 PyErr_NoMemory();
589 return -1;
590 }
591 strncpy(tag, start, len);
592 tag[len] = '\0';
593 // Ownership of tag passes to the growable array
594 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
595 PyErr_NoMemory();
596 return -1;
597 }
598 type = PyTokenizer_Get(p->tok, &start, &end);
599 }
600
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100601 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
602 type = NEWLINE; /* Add an extra newline */
603 p->parsing_started = 0;
604
Pablo Galindob94dbd72020-04-27 18:35:58 +0100605 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100606 p->tok->pendin = -p->tok->indent;
607 p->tok->indent = 0;
608 }
609 }
610 else {
611 p->parsing_started = 1;
612 }
613
614 if (p->fill == p->size) {
615 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300616 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
617 if (new_tokens == NULL) {
618 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100619 return -1;
620 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300621 else {
622 p->tokens = new_tokens;
623 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100624 for (int i = p->size; i < newsize; i++) {
625 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300626 if (p->tokens[i] == NULL) {
627 p->size = i; // Needed, in order to cleanup correctly after parser fails
628 PyErr_NoMemory();
629 return -1;
630 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100631 memset(p->tokens[i], '\0', sizeof(Token));
632 }
633 p->size = newsize;
634 }
635
636 Token *t = p->tokens[p->fill];
637 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
638 t->bytes = PyBytes_FromStringAndSize(start, end - start);
639 if (t->bytes == NULL) {
640 return -1;
641 }
642 PyArena_AddPyObject(p->arena, t->bytes);
643
644 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
645 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100646 int end_lineno = p->tok->lineno;
647 int col_offset = -1, end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100648 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100649 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100650 }
651 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100652 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100653 }
654
655 t->lineno = p->starting_lineno + lineno;
656 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
657 t->end_lineno = p->starting_lineno + end_lineno;
658 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
659
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100660 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300661
662 if (type == ERRORTOKEN) {
663 if (p->tok->done == E_DECODE) {
664 return raise_decode_error(p);
665 }
666 else {
667 return tokenizer_error(p);
668 }
669 }
670
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100671 return 0;
672}
673
674// Instrumentation to count the effectiveness of memoization.
675// The array counts the number of tokens skipped by memoization,
676// indexed by type.
677
678#define NSTATISTICS 2000
679static long memo_statistics[NSTATISTICS];
680
681void
682_PyPegen_clear_memo_statistics()
683{
684 for (int i = 0; i < NSTATISTICS; i++) {
685 memo_statistics[i] = 0;
686 }
687}
688
689PyObject *
690_PyPegen_get_memo_statistics()
691{
692 PyObject *ret = PyList_New(NSTATISTICS);
693 if (ret == NULL) {
694 return NULL;
695 }
696 for (int i = 0; i < NSTATISTICS; i++) {
697 PyObject *value = PyLong_FromLong(memo_statistics[i]);
698 if (value == NULL) {
699 Py_DECREF(ret);
700 return NULL;
701 }
702 // PyList_SetItem borrows a reference to value.
703 if (PyList_SetItem(ret, i, value) < 0) {
704 Py_DECREF(ret);
705 return NULL;
706 }
707 }
708 return ret;
709}
710
711int // bool
712_PyPegen_is_memoized(Parser *p, int type, void *pres)
713{
714 if (p->mark == p->fill) {
715 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300716 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100717 return -1;
718 }
719 }
720
721 Token *t = p->tokens[p->mark];
722
723 for (Memo *m = t->memo; m != NULL; m = m->next) {
724 if (m->type == type) {
725 if (0 <= type && type < NSTATISTICS) {
726 long count = m->mark - p->mark;
727 // A memoized negative result counts for one.
728 if (count <= 0) {
729 count = 1;
730 }
731 memo_statistics[type] += count;
732 }
733 p->mark = m->mark;
734 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100735 return 1;
736 }
737 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100738 return 0;
739}
740
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100741
742int
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
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100751int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100752_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
753{
754 int mark = p->mark;
755 void *res = func(p, arg);
756 p->mark = mark;
757 return (res != NULL) == positive;
758}
759
760int
761_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
762{
763 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100764 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100765 p->mark = mark;
766 return (res != NULL) == positive;
767}
768
769Token *
770_PyPegen_expect_token(Parser *p, int type)
771{
772 if (p->mark == p->fill) {
773 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300774 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100775 return NULL;
776 }
777 }
778 Token *t = p->tokens[p->mark];
779 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100780 return NULL;
781 }
782 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100783 return t;
784}
785
786Token *
787_PyPegen_get_last_nonnwhitespace_token(Parser *p)
788{
789 assert(p->mark >= 0);
790 Token *token = NULL;
791 for (int m = p->mark - 1; m >= 0; m--) {
792 token = p->tokens[m];
793 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
794 break;
795 }
796 }
797 return token;
798}
799
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100800expr_ty
801_PyPegen_name_token(Parser *p)
802{
803 Token *t = _PyPegen_expect_token(p, NAME);
804 if (t == NULL) {
805 return NULL;
806 }
807 char* s = PyBytes_AsString(t->bytes);
808 if (!s) {
809 return NULL;
810 }
811 PyObject *id = _PyPegen_new_identifier(p, s);
812 if (id == NULL) {
813 return NULL;
814 }
815 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
816 p->arena);
817}
818
819void *
820_PyPegen_string_token(Parser *p)
821{
822 return _PyPegen_expect_token(p, STRING);
823}
824
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100825static PyObject *
826parsenumber_raw(const char *s)
827{
828 const char *end;
829 long x;
830 double dx;
831 Py_complex compl;
832 int imflag;
833
834 assert(s != NULL);
835 errno = 0;
836 end = s + strlen(s) - 1;
837 imflag = *end == 'j' || *end == 'J';
838 if (s[0] == '0') {
839 x = (long)PyOS_strtoul(s, (char **)&end, 0);
840 if (x < 0 && errno == 0) {
841 return PyLong_FromString(s, (char **)0, 0);
842 }
843 }
844 else
845 x = PyOS_strtol(s, (char **)&end, 0);
846 if (*end == '\0') {
847 if (errno != 0)
848 return PyLong_FromString(s, (char **)0, 0);
849 return PyLong_FromLong(x);
850 }
851 /* XXX Huge floats may silently fail */
852 if (imflag) {
853 compl.real = 0.;
854 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
855 if (compl.imag == -1.0 && PyErr_Occurred())
856 return NULL;
857 return PyComplex_FromCComplex(compl);
858 }
859 else {
860 dx = PyOS_string_to_double(s, NULL, NULL);
861 if (dx == -1.0 && PyErr_Occurred())
862 return NULL;
863 return PyFloat_FromDouble(dx);
864 }
865}
866
867static PyObject *
868parsenumber(const char *s)
869{
870 char *dup, *end;
871 PyObject *res = NULL;
872
873 assert(s != NULL);
874
875 if (strchr(s, '_') == NULL) {
876 return parsenumber_raw(s);
877 }
878 /* Create a duplicate without underscores. */
879 dup = PyMem_Malloc(strlen(s) + 1);
880 if (dup == NULL) {
881 return PyErr_NoMemory();
882 }
883 end = dup;
884 for (; *s; s++) {
885 if (*s != '_') {
886 *end++ = *s;
887 }
888 }
889 *end = '\0';
890 res = parsenumber_raw(dup);
891 PyMem_Free(dup);
892 return res;
893}
894
895expr_ty
896_PyPegen_number_token(Parser *p)
897{
898 Token *t = _PyPegen_expect_token(p, NUMBER);
899 if (t == NULL) {
900 return NULL;
901 }
902
903 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100904 if (num_raw == NULL) {
905 return NULL;
906 }
907
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300908 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
909 p->error_indicator = 1;
910 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported"
911 "in Python 3.6 and greater");
912 }
913
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100914 PyObject *c = parsenumber(num_raw);
915
916 if (c == NULL) {
917 return NULL;
918 }
919
920 if (PyArena_AddPyObject(p->arena, c) < 0) {
921 Py_DECREF(c);
922 return NULL;
923 }
924
925 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
926 p->arena);
927}
928
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300929static int // bool
930newline_in_string(Parser *p, const char *cur)
931{
932 for (char c = *cur; cur >= p->tok->buf; c = *--cur) {
933 if (c == '\'' || c == '"') {
934 return 1;
935 }
936 }
937 return 0;
938}
939
940/* Check that the source for a single input statement really is a single
941 statement by looking at what is left in the buffer after parsing.
942 Trailing whitespace and comments are OK. */
943static int // bool
944bad_single_statement(Parser *p)
945{
946 const char *cur = strchr(p->tok->buf, '\n');
947
948 /* Newlines are allowed if preceded by a line continuation character
949 or if they appear inside a string. */
950 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
951 return 0;
952 }
953 char c = *cur;
954
955 for (;;) {
956 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
957 c = *++cur;
958 }
959
960 if (!c) {
961 return 0;
962 }
963
964 if (c != '#') {
965 return 1;
966 }
967
968 /* Suck up comment. */
969 while (c && c != '\n') {
970 c = *++cur;
971 }
972 }
973}
974
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100975void
976_PyPegen_Parser_Free(Parser *p)
977{
978 Py_XDECREF(p->normalize);
979 for (int i = 0; i < p->size; i++) {
980 PyMem_Free(p->tokens[i]);
981 }
982 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700983 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100984 PyMem_Free(p);
985}
986
Pablo Galindo2b74c832020-04-27 18:02:07 +0100987static int
988compute_parser_flags(PyCompilerFlags *flags)
989{
990 int parser_flags = 0;
991 if (!flags) {
992 return 0;
993 }
994 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
995 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
996 }
997 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
998 parser_flags |= PyPARSE_IGNORE_COOKIE;
999 }
1000 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1001 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1002 }
1003 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1004 parser_flags |= PyPARSE_TYPE_COMMENTS;
1005 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001006 if (flags->cf_feature_version < 7) {
1007 parser_flags |= PyPARSE_ASYNC_HACKS;
1008 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001009 return parser_flags;
1010}
1011
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001012Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001013_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001014 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001015{
1016 Parser *p = PyMem_Malloc(sizeof(Parser));
1017 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001018 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001019 }
1020 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001021 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1022 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001023 p->tok = tok;
1024 p->keywords = NULL;
1025 p->n_keyword_lists = -1;
1026 p->tokens = PyMem_Malloc(sizeof(Token *));
1027 if (!p->tokens) {
1028 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001029 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001030 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001031 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001032 if (!p->tokens) {
1033 PyMem_Free(p->tokens);
1034 PyMem_Free(p);
1035 return (Parser *) PyErr_NoMemory();
1036 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001037 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1038 PyMem_Free(p->tokens[0]);
1039 PyMem_Free(p->tokens);
1040 PyMem_Free(p);
1041 return (Parser *) PyErr_NoMemory();
1042 }
1043
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001044 p->mark = 0;
1045 p->fill = 0;
1046 p->size = 1;
1047
1048 p->errcode = errcode;
1049 p->arena = arena;
1050 p->start_rule = start_rule;
1051 p->parsing_started = 0;
1052 p->normalize = NULL;
1053 p->error_indicator = 0;
1054
1055 p->starting_lineno = 0;
1056 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001057 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001058 p->feature_version = feature_version;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001059
1060 return p;
1061}
1062
1063void *
1064_PyPegen_run_parser(Parser *p)
1065{
1066 void *res = _PyPegen_parse(p);
1067 if (res == NULL) {
1068 if (PyErr_Occurred()) {
1069 return NULL;
1070 }
1071 if (p->fill == 0) {
1072 RAISE_SYNTAX_ERROR("error at start before reading any input");
1073 }
1074 else if (p->tok->done == E_EOF) {
1075 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1076 }
1077 else {
1078 if (p->tokens[p->fill-1]->type == INDENT) {
1079 RAISE_INDENTATION_ERROR("unexpected indent");
1080 }
1081 else if (p->tokens[p->fill-1]->type == DEDENT) {
1082 RAISE_INDENTATION_ERROR("unexpected unindent");
1083 }
1084 else {
1085 RAISE_SYNTAX_ERROR("invalid syntax");
1086 }
1087 }
1088 return NULL;
1089 }
1090
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001091 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1092 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1093 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1094 }
1095
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001096 return res;
1097}
1098
1099mod_ty
1100_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1101 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001102 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001103{
1104 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1105 if (tok == NULL) {
1106 if (PyErr_Occurred()) {
1107 raise_tokenizer_init_error(filename_ob);
1108 return NULL;
1109 }
1110 return NULL;
1111 }
1112 // This transfers the ownership to the tokenizer
1113 tok->filename = filename_ob;
1114 Py_INCREF(filename_ob);
1115
1116 // From here on we need to clean up even if there's an error
1117 mod_ty result = NULL;
1118
Pablo Galindo2b74c832020-04-27 18:02:07 +01001119 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001120 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1121 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001122 if (p == NULL) {
1123 goto error;
1124 }
1125
1126 result = _PyPegen_run_parser(p);
1127 _PyPegen_Parser_Free(p);
1128
1129error:
1130 PyTokenizer_Free(tok);
1131 return result;
1132}
1133
1134mod_ty
1135_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001136 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001137{
1138 FILE *fp = fopen(filename, "rb");
1139 if (fp == NULL) {
1140 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1141 return NULL;
1142 }
1143
1144 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001145 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001146
1147 fclose(fp);
1148 return result;
1149}
1150
1151mod_ty
1152_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001153 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001154{
1155 int exec_input = start_rule == Py_file_input;
1156
1157 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001158 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001159 tok = PyTokenizer_FromUTF8(str, exec_input);
1160 } else {
1161 tok = PyTokenizer_FromString(str, exec_input);
1162 }
1163 if (tok == NULL) {
1164 if (PyErr_Occurred()) {
1165 raise_tokenizer_init_error(filename_ob);
1166 }
1167 return NULL;
1168 }
1169 // This transfers the ownership to the tokenizer
1170 tok->filename = filename_ob;
1171 Py_INCREF(filename_ob);
1172
1173 // We need to clear up from here on
1174 mod_ty result = NULL;
1175
Pablo Galindo2b74c832020-04-27 18:02:07 +01001176 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001177 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
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}