blob: 78891af82500733cc5c37953fd8727cc9073d57a [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"
Pablo Galindobc2c0e92020-07-28 00:12:31 +01007#include "ast.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01008
Guido van Rossumc001c092020-04-30 12:12:19 -07009PyObject *
10_PyPegen_new_type_comment(Parser *p, char *s)
11{
12 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
13 if (res == NULL) {
14 return NULL;
15 }
16 if (PyArena_AddPyObject(p->arena, res) < 0) {
17 Py_DECREF(res);
18 return NULL;
19 }
20 return res;
21}
22
23arg_ty
24_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
25{
26 if (tc == NULL) {
27 return a;
28 }
29 char *bytes = PyBytes_AsString(tc->bytes);
30 if (bytes == NULL) {
31 return NULL;
32 }
33 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
34 if (tco == NULL) {
35 return NULL;
36 }
37 return arg(a->arg, a->annotation, tco,
38 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
39 p->arena);
40}
41
Pablo Galindoc5fc1562020-04-22 23:29:27 +010042static int
43init_normalization(Parser *p)
44{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030045 if (p->normalize) {
46 return 1;
47 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010048 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
49 if (!m)
50 {
51 return 0;
52 }
53 p->normalize = PyObject_GetAttrString(m, "normalize");
54 Py_DECREF(m);
55 if (!p->normalize)
56 {
57 return 0;
58 }
59 return 1;
60}
61
Pablo Galindo2b74c832020-04-27 18:02:07 +010062/* Checks if the NOTEQUAL token is valid given the current parser flags
630 indicates success and nonzero indicates failure (an exception may be set) */
64int
65_PyPegen_check_barry_as_flufl(Parser *p) {
66 Token *t = p->tokens[p->fill - 1];
67 assert(t->bytes != NULL);
68 assert(t->type == NOTEQUAL);
69
70 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindo30b59fd2020-06-15 15:08:00 +010071 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010072 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
73 return -1;
Pablo Galindo30b59fd2020-06-15 15:08:00 +010074 }
75 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010076 return strcmp(tok_str, "!=");
77 }
78 return 0;
79}
80
Pablo Galindoc5fc1562020-04-22 23:29:27 +010081PyObject *
82_PyPegen_new_identifier(Parser *p, char *n)
83{
84 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
85 if (!id) {
86 goto error;
87 }
88 /* PyUnicode_DecodeUTF8 should always return a ready string. */
89 assert(PyUnicode_IS_READY(id));
90 /* Check whether there are non-ASCII characters in the
91 identifier; if so, normalize to NFKC. */
92 if (!PyUnicode_IS_ASCII(id))
93 {
94 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030095 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010096 {
97 Py_DECREF(id);
98 goto error;
99 }
100 PyObject *form = PyUnicode_InternFromString("NFKC");
101 if (form == NULL)
102 {
103 Py_DECREF(id);
104 goto error;
105 }
106 PyObject *args[2] = {form, id};
107 id2 = _PyObject_FastCall(p->normalize, args, 2);
108 Py_DECREF(id);
109 Py_DECREF(form);
110 if (!id2) {
111 goto error;
112 }
113 if (!PyUnicode_Check(id2))
114 {
115 PyErr_Format(PyExc_TypeError,
116 "unicodedata.normalize() must return a string, not "
117 "%.200s",
118 _PyType_Name(Py_TYPE(id2)));
119 Py_DECREF(id2);
120 goto error;
121 }
122 id = id2;
123 }
124 PyUnicode_InternInPlace(&id);
125 if (PyArena_AddPyObject(p->arena, id) < 0)
126 {
127 Py_DECREF(id);
128 goto error;
129 }
130 return id;
131
132error:
133 p->error_indicator = 1;
134 return NULL;
135}
136
137static PyObject *
138_create_dummy_identifier(Parser *p)
139{
140 return _PyPegen_new_identifier(p, "");
141}
142
143static inline Py_ssize_t
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700144byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100145{
146 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300147 if (!str) {
148 return 0;
149 }
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700150 assert(col_offset >= 0 && (unsigned long)col_offset <= strlen(str));
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300151 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100152 if (!text) {
153 return 0;
154 }
155 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
156 Py_DECREF(text);
157 return size;
158}
159
160const char *
161_PyPegen_get_expr_name(expr_ty e)
162{
Miss Islington (bot)8df4f392020-06-08 02:22:06 -0700163 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100164 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) {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100247 PyObject *type;
248 PyObject *value;
249 PyObject *tback;
250 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100251 PyErr_Fetch(&type, &value, &tback);
252 errstr = PyObject_Str(value);
253 if (errstr) {
254 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
255 Py_DECREF(errstr);
256 }
257 else {
258 PyErr_Clear();
259 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
260 }
261 Py_XDECREF(type);
262 Py_XDECREF(value);
263 Py_XDECREF(tback);
264 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300265
266 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100267}
268
269static void
270raise_tokenizer_init_error(PyObject *filename)
271{
272 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
273 || PyErr_ExceptionMatches(PyExc_ValueError)
274 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
275 return;
276 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300277 PyObject *errstr = NULL;
278 PyObject *tuple = NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100279 PyObject *type;
280 PyObject *value;
281 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100282 PyErr_Fetch(&type, &value, &tback);
283 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300284 if (!errstr) {
285 goto error;
286 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100287
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300288 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100289 if (!tmp) {
290 goto error;
291 }
292
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300293 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100294 Py_DECREF(tmp);
295 if (!value) {
296 goto error;
297 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300298 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100299
300error:
301 Py_XDECREF(type);
302 Py_XDECREF(value);
303 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300304 Py_XDECREF(errstr);
305 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100306}
307
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100309tokenizer_error(Parser *p)
310{
311 if (PyErr_Occurred()) {
312 return -1;
313 }
314
315 const char *msg = NULL;
316 PyObject* errtype = PyExc_SyntaxError;
317 switch (p->tok->done) {
318 case E_TOKEN:
319 msg = "invalid token";
320 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100321 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300322 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
323 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100324 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300325 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
326 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300327 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300328 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
329 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100330 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300331 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
332 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100333 case E_INTR:
334 if (!PyErr_Occurred()) {
335 PyErr_SetNone(PyExc_KeyboardInterrupt);
336 }
337 return -1;
338 case E_NOMEM:
339 PyErr_NoMemory();
340 return -1;
341 case E_TABSPACE:
342 errtype = PyExc_TabError;
343 msg = "inconsistent use of tabs and spaces in indentation";
344 break;
345 case E_TOODEEP:
346 errtype = PyExc_IndentationError;
347 msg = "too many levels of indentation";
348 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100349 case E_LINECONT:
350 msg = "unexpected character after line continuation character";
351 break;
352 default:
353 msg = "unknown parsing error";
354 }
355
356 PyErr_Format(errtype, msg);
357 // There is no reliable column information for this error
358 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
359
360 return -1;
361}
362
363void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300364_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
365{
366 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700367 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300368 if (t->col_offset == -1) {
369 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
370 intptr_t, int);
371 } else {
372 col_offset = t->col_offset + 1;
373 }
374
375 va_list va;
376 va_start(va, errmsg);
377 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
378 col_offset, errmsg, va);
379 va_end(va);
380
381 return NULL;
382}
383
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300384void *
385_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700386 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300387 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100388{
389 PyObject *value = NULL;
390 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300391 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100392 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300393 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100394
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700395 if (p->start_rule == Py_fstring_input) {
396 const char *fstring_msg = "f-string: ";
397 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
398
399 char *new_errmsg = PyMem_RawMalloc(len + 1); // Lengths of both strings plus NULL character
400 if (!new_errmsg) {
401 return (void *) PyErr_NoMemory();
402 }
403
404 // Copy both strings into new buffer
405 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
406 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
407 new_errmsg[len] = 0;
408 errmsg = new_errmsg;
409 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100410 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100411 if (!errstr) {
412 goto error;
413 }
414
415 if (p->start_rule == Py_file_input) {
Miss Islington (bot)c9f83c12020-06-20 10:35:03 -0700416 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100417 }
418
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300419 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100420 Py_ssize_t size = p->tok->inp - p->tok->buf;
Pablo Galindobcc30362020-05-14 21:11:48 +0100421 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300422 if (!error_line) {
423 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300424 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100425 }
426
Pablo Galindodab533d2020-06-28 01:15:28 +0100427 if (p->start_rule == Py_fstring_input) {
428 col_offset -= p->starting_col_offset;
429 }
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700430 Py_ssize_t col_number = col_offset;
431
432 if (p->tok->encoding != NULL) {
433 col_number = byte_offset_to_character_offset(error_line, col_offset);
434 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300435
436 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100437 if (!tmp) {
438 goto error;
439 }
440 value = PyTuple_Pack(2, errstr, tmp);
441 Py_DECREF(tmp);
442 if (!value) {
443 goto error;
444 }
445 PyErr_SetObject(errtype, value);
446
447 Py_DECREF(errstr);
448 Py_DECREF(value);
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700449 if (p->start_rule == Py_fstring_input) {
450 PyMem_RawFree((void *)errmsg);
451 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100452 return NULL;
453
454error:
455 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300456 Py_XDECREF(error_line);
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700457 if (p->start_rule == Py_fstring_input) {
458 PyMem_RawFree((void *)errmsg);
459 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100460 return NULL;
461}
462
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100463#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{
Miss Islington (bot)edeaf612020-07-06 16:35:10 -0700529 assert(name_len > 0);
Pablo Galindo54f115d2020-07-06 20:29:59 +0100530 if (name_len >= p->n_keyword_lists ||
531 p->keywords[name_len] == NULL ||
532 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100533 return NAME;
534 }
Pablo Galindo54f115d2020-07-06 20:29:59 +0100535 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100536 if (strncmp(k->str, name, name_len) == 0) {
537 return k->type;
538 }
539 }
540 return NAME;
541}
542
Guido van Rossumc001c092020-04-30 12:12:19 -0700543static int
544growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
545 assert(initial_size > 0);
546 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
547 arr->size = initial_size;
548 arr->num_items = 0;
549
550 return arr->items != NULL;
551}
552
553static int
554growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
555 if (arr->num_items >= arr->size) {
556 size_t new_size = arr->size * 2;
557 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
558 if (!new_items_array) {
559 return 0;
560 }
561 arr->items = new_items_array;
562 arr->size = new_size;
563 }
564
565 arr->items[arr->num_items].lineno = lineno;
566 arr->items[arr->num_items].comment = comment; // Take ownership
567 arr->num_items++;
568 return 1;
569}
570
571static void
572growable_comment_array_deallocate(growable_comment_array *arr) {
573 for (unsigned i = 0; i < arr->num_items; i++) {
574 PyMem_Free(arr->items[i].comment);
575 }
576 PyMem_Free(arr->items);
577}
578
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100579int
580_PyPegen_fill_token(Parser *p)
581{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100582 const char *start;
583 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100584 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700585
586 // Record and skip '# type: ignore' comments
587 while (type == TYPE_IGNORE) {
588 Py_ssize_t len = end - start;
589 char *tag = PyMem_Malloc(len + 1);
590 if (tag == NULL) {
591 PyErr_NoMemory();
592 return -1;
593 }
594 strncpy(tag, start, len);
595 tag[len] = '\0';
596 // Ownership of tag passes to the growable array
597 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
598 PyErr_NoMemory();
599 return -1;
600 }
601 type = PyTokenizer_Get(p->tok, &start, &end);
602 }
603
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100604 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
605 type = NEWLINE; /* Add an extra newline */
606 p->parsing_started = 0;
607
Pablo Galindob94dbd72020-04-27 18:35:58 +0100608 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100609 p->tok->pendin = -p->tok->indent;
610 p->tok->indent = 0;
611 }
612 }
613 else {
614 p->parsing_started = 1;
615 }
616
617 if (p->fill == p->size) {
618 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300619 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
620 if (new_tokens == NULL) {
621 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100622 return -1;
623 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100624 p->tokens = new_tokens;
625
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100626 for (int i = p->size; i < newsize; i++) {
627 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300628 if (p->tokens[i] == NULL) {
629 p->size = i; // Needed, in order to cleanup correctly after parser fails
630 PyErr_NoMemory();
631 return -1;
632 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100633 memset(p->tokens[i], '\0', sizeof(Token));
634 }
635 p->size = newsize;
636 }
637
638 Token *t = p->tokens[p->fill];
639 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
640 t->bytes = PyBytes_FromStringAndSize(start, end - start);
641 if (t->bytes == NULL) {
642 return -1;
643 }
644 PyArena_AddPyObject(p->arena, t->bytes);
645
646 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
647 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100648 int end_lineno = p->tok->lineno;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100649 int col_offset = -1;
650 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100651 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100652 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100653 }
654 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100655 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100656 }
657
658 t->lineno = p->starting_lineno + lineno;
659 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
660 t->end_lineno = p->starting_lineno + end_lineno;
661 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
662
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100663 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300664
665 if (type == ERRORTOKEN) {
666 if (p->tok->done == E_DECODE) {
667 return raise_decode_error(p);
668 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100669 return tokenizer_error(p);
670
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300671 }
672
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100673 return 0;
674}
675
676// Instrumentation to count the effectiveness of memoization.
677// The array counts the number of tokens skipped by memoization,
678// indexed by type.
679
680#define NSTATISTICS 2000
681static long memo_statistics[NSTATISTICS];
682
683void
684_PyPegen_clear_memo_statistics()
685{
686 for (int i = 0; i < NSTATISTICS; i++) {
687 memo_statistics[i] = 0;
688 }
689}
690
691PyObject *
692_PyPegen_get_memo_statistics()
693{
694 PyObject *ret = PyList_New(NSTATISTICS);
695 if (ret == NULL) {
696 return NULL;
697 }
698 for (int i = 0; i < NSTATISTICS; i++) {
699 PyObject *value = PyLong_FromLong(memo_statistics[i]);
700 if (value == NULL) {
701 Py_DECREF(ret);
702 return NULL;
703 }
704 // PyList_SetItem borrows a reference to value.
705 if (PyList_SetItem(ret, i, value) < 0) {
706 Py_DECREF(ret);
707 return NULL;
708 }
709 }
710 return ret;
711}
712
713int // bool
714_PyPegen_is_memoized(Parser *p, int type, void *pres)
715{
716 if (p->mark == p->fill) {
717 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300718 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100719 return -1;
720 }
721 }
722
723 Token *t = p->tokens[p->mark];
724
725 for (Memo *m = t->memo; m != NULL; m = m->next) {
726 if (m->type == type) {
727 if (0 <= type && type < NSTATISTICS) {
728 long count = m->mark - p->mark;
729 // A memoized negative result counts for one.
730 if (count <= 0) {
731 count = 1;
732 }
733 memo_statistics[type] += count;
734 }
735 p->mark = m->mark;
736 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100737 return 1;
738 }
739 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100740 return 0;
741}
742
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100743int
744_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
745{
746 int mark = p->mark;
747 void *res = func(p);
748 p->mark = mark;
749 return (res != NULL) == positive;
750}
751
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100752int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300753_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
754{
755 int mark = p->mark;
756 void *res = func(p, arg);
757 p->mark = mark;
758 return (res != NULL) == positive;
759}
760
761int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100762_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
763{
764 int mark = p->mark;
765 void *res = func(p, arg);
766 p->mark = mark;
767 return (res != NULL) == positive;
768}
769
770int
771_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
772{
773 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100774 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100775 p->mark = mark;
776 return (res != NULL) == positive;
777}
778
779Token *
780_PyPegen_expect_token(Parser *p, int type)
781{
782 if (p->mark == p->fill) {
783 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300784 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100785 return NULL;
786 }
787 }
788 Token *t = p->tokens[p->mark];
789 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100790 return NULL;
791 }
792 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100793 return t;
794}
795
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300796expr_ty
797_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
798{
799 if (p->mark == p->fill) {
800 if (_PyPegen_fill_token(p) < 0) {
801 p->error_indicator = 1;
802 return NULL;
803 }
804 }
805 Token *t = p->tokens[p->mark];
806 if (t->type != NAME) {
807 return NULL;
808 }
809 char* s = PyBytes_AsString(t->bytes);
810 if (!s) {
811 p->error_indicator = 1;
812 return NULL;
813 }
814 if (strcmp(s, keyword) != 0) {
815 return NULL;
816 }
817 return _PyPegen_name_token(p);
818}
819
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100820Token *
821_PyPegen_get_last_nonnwhitespace_token(Parser *p)
822{
823 assert(p->mark >= 0);
824 Token *token = NULL;
825 for (int m = p->mark - 1; m >= 0; m--) {
826 token = p->tokens[m];
827 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
828 break;
829 }
830 }
831 return token;
832}
833
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100834expr_ty
835_PyPegen_name_token(Parser *p)
836{
837 Token *t = _PyPegen_expect_token(p, NAME);
838 if (t == NULL) {
839 return NULL;
840 }
841 char* s = PyBytes_AsString(t->bytes);
842 if (!s) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300843 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100844 return NULL;
845 }
846 PyObject *id = _PyPegen_new_identifier(p, s);
847 if (id == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300848 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100849 return NULL;
850 }
851 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
852 p->arena);
853}
854
855void *
856_PyPegen_string_token(Parser *p)
857{
858 return _PyPegen_expect_token(p, STRING);
859}
860
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100861static PyObject *
862parsenumber_raw(const char *s)
863{
864 const char *end;
865 long x;
866 double dx;
867 Py_complex compl;
868 int imflag;
869
870 assert(s != NULL);
871 errno = 0;
872 end = s + strlen(s) - 1;
873 imflag = *end == 'j' || *end == 'J';
874 if (s[0] == '0') {
875 x = (long)PyOS_strtoul(s, (char **)&end, 0);
876 if (x < 0 && errno == 0) {
877 return PyLong_FromString(s, (char **)0, 0);
878 }
879 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100880 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100881 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100882 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100883 if (*end == '\0') {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100884 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100885 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100886 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100887 return PyLong_FromLong(x);
888 }
889 /* XXX Huge floats may silently fail */
890 if (imflag) {
891 compl.real = 0.;
892 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100893 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100894 return NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100895 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100896 return PyComplex_FromCComplex(compl);
897 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100898 dx = PyOS_string_to_double(s, NULL, NULL);
899 if (dx == -1.0 && PyErr_Occurred()) {
900 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100901 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100902 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100903}
904
905static PyObject *
906parsenumber(const char *s)
907{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100908 char *dup;
909 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100910 PyObject *res = NULL;
911
912 assert(s != NULL);
913
914 if (strchr(s, '_') == NULL) {
915 return parsenumber_raw(s);
916 }
917 /* Create a duplicate without underscores. */
918 dup = PyMem_Malloc(strlen(s) + 1);
919 if (dup == NULL) {
920 return PyErr_NoMemory();
921 }
922 end = dup;
923 for (; *s; s++) {
924 if (*s != '_') {
925 *end++ = *s;
926 }
927 }
928 *end = '\0';
929 res = parsenumber_raw(dup);
930 PyMem_Free(dup);
931 return res;
932}
933
934expr_ty
935_PyPegen_number_token(Parser *p)
936{
937 Token *t = _PyPegen_expect_token(p, NUMBER);
938 if (t == NULL) {
939 return NULL;
940 }
941
942 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100943 if (num_raw == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300944 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100945 return NULL;
946 }
947
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300948 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
949 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700950 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300951 "in Python 3.6 and greater");
952 }
953
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100954 PyObject *c = parsenumber(num_raw);
955
956 if (c == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300957 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100958 return NULL;
959 }
960
961 if (PyArena_AddPyObject(p->arena, c) < 0) {
962 Py_DECREF(c);
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300963 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100964 return NULL;
965 }
966
967 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
968 p->arena);
969}
970
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300971static int // bool
972newline_in_string(Parser *p, const char *cur)
973{
Miss Islington (bot)15fec562020-06-05 17:13:14 -0700974 for (const char *c = cur; c >= p->tok->buf; c--) {
975 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300976 return 1;
977 }
978 }
979 return 0;
980}
981
982/* Check that the source for a single input statement really is a single
983 statement by looking at what is left in the buffer after parsing.
984 Trailing whitespace and comments are OK. */
985static int // bool
986bad_single_statement(Parser *p)
987{
988 const char *cur = strchr(p->tok->buf, '\n');
989
990 /* Newlines are allowed if preceded by a line continuation character
991 or if they appear inside a string. */
Miss Skeleton (bot)0b290dd2020-10-25 16:24:56 -0700992 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
993 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300994 return 0;
995 }
996 char c = *cur;
997
998 for (;;) {
999 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1000 c = *++cur;
1001 }
1002
1003 if (!c) {
1004 return 0;
1005 }
1006
1007 if (c != '#') {
1008 return 1;
1009 }
1010
1011 /* Suck up comment. */
1012 while (c && c != '\n') {
1013 c = *++cur;
1014 }
1015 }
1016}
1017
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001018void
1019_PyPegen_Parser_Free(Parser *p)
1020{
1021 Py_XDECREF(p->normalize);
1022 for (int i = 0; i < p->size; i++) {
1023 PyMem_Free(p->tokens[i]);
1024 }
1025 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001026 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001027 PyMem_Free(p);
1028}
1029
Pablo Galindo2b74c832020-04-27 18:02:07 +01001030static int
1031compute_parser_flags(PyCompilerFlags *flags)
1032{
1033 int parser_flags = 0;
1034 if (!flags) {
1035 return 0;
1036 }
1037 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1038 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1039 }
1040 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1041 parser_flags |= PyPARSE_IGNORE_COOKIE;
1042 }
1043 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1044 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1045 }
1046 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1047 parser_flags |= PyPARSE_TYPE_COMMENTS;
1048 }
Guido van Rossum2a1ee1d2020-06-27 17:34:30 -07001049 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001050 parser_flags |= PyPARSE_ASYNC_HACKS;
1051 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001052 return parser_flags;
1053}
1054
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001055Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001056_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001057 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001058{
1059 Parser *p = PyMem_Malloc(sizeof(Parser));
1060 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001061 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001062 }
1063 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001064 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1065 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001066 p->tok = tok;
1067 p->keywords = NULL;
1068 p->n_keyword_lists = -1;
1069 p->tokens = PyMem_Malloc(sizeof(Token *));
1070 if (!p->tokens) {
1071 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001072 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001073 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001074 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001075 if (!p->tokens) {
1076 PyMem_Free(p->tokens);
1077 PyMem_Free(p);
1078 return (Parser *) PyErr_NoMemory();
1079 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001080 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1081 PyMem_Free(p->tokens[0]);
1082 PyMem_Free(p->tokens);
1083 PyMem_Free(p);
1084 return (Parser *) PyErr_NoMemory();
1085 }
1086
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001087 p->mark = 0;
1088 p->fill = 0;
1089 p->size = 1;
1090
1091 p->errcode = errcode;
1092 p->arena = arena;
1093 p->start_rule = start_rule;
1094 p->parsing_started = 0;
1095 p->normalize = NULL;
1096 p->error_indicator = 0;
1097
1098 p->starting_lineno = 0;
1099 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001100 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001101 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001102 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001103 p->level = 0;
Lysandros Nikolaou24a7c292020-10-28 02:14:15 +02001104 p->call_invalid_rules = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001105
1106 return p;
1107}
1108
Lysandros Nikolaou24a7c292020-10-28 02:14:15 +02001109static void
1110reset_parser_state(Parser *p)
1111{
1112 for (int i = 0; i < p->fill; i++) {
1113 p->tokens[i]->memo = NULL;
1114 }
1115 p->mark = 0;
1116 p->call_invalid_rules = 1;
1117}
1118
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001119void *
1120_PyPegen_run_parser(Parser *p)
1121{
1122 void *res = _PyPegen_parse(p);
1123 if (res == NULL) {
Lysandros Nikolaou24a7c292020-10-28 02:14:15 +02001124 reset_parser_state(p);
1125 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001126 if (PyErr_Occurred()) {
1127 return NULL;
1128 }
1129 if (p->fill == 0) {
1130 RAISE_SYNTAX_ERROR("error at start before reading any input");
1131 }
1132 else if (p->tok->done == E_EOF) {
1133 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1134 }
1135 else {
1136 if (p->tokens[p->fill-1]->type == INDENT) {
1137 RAISE_INDENTATION_ERROR("unexpected indent");
1138 }
1139 else if (p->tokens[p->fill-1]->type == DEDENT) {
1140 RAISE_INDENTATION_ERROR("unexpected unindent");
1141 }
1142 else {
1143 RAISE_SYNTAX_ERROR("invalid syntax");
1144 }
1145 }
1146 return NULL;
1147 }
1148
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001149 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1150 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1151 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1152 }
1153
Pablo Galindobc2c0e92020-07-28 00:12:31 +01001154#if defined(Py_DEBUG) && defined(Py_BUILD_CORE)
1155 if (p->start_rule == Py_single_input ||
1156 p->start_rule == Py_file_input ||
1157 p->start_rule == Py_eval_input)
1158 {
1159 assert(PyAST_Validate(res));
1160 }
1161#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001162 return res;
1163}
1164
1165mod_ty
1166_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1167 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001168 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001169{
1170 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1171 if (tok == NULL) {
1172 if (PyErr_Occurred()) {
1173 raise_tokenizer_init_error(filename_ob);
1174 return NULL;
1175 }
1176 return NULL;
1177 }
1178 // This transfers the ownership to the tokenizer
1179 tok->filename = filename_ob;
1180 Py_INCREF(filename_ob);
1181
1182 // From here on we need to clean up even if there's an error
1183 mod_ty result = NULL;
1184
Pablo Galindo2b74c832020-04-27 18:02:07 +01001185 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001186 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1187 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001188 if (p == NULL) {
1189 goto error;
1190 }
1191
1192 result = _PyPegen_run_parser(p);
1193 _PyPegen_Parser_Free(p);
1194
1195error:
1196 PyTokenizer_Free(tok);
1197 return result;
1198}
1199
1200mod_ty
1201_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001202 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001203{
1204 FILE *fp = fopen(filename, "rb");
1205 if (fp == NULL) {
1206 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1207 return NULL;
1208 }
1209
1210 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001211 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001212
1213 fclose(fp);
1214 return result;
1215}
1216
1217mod_ty
1218_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001219 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001220{
1221 int exec_input = start_rule == Py_file_input;
1222
1223 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001224 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001225 tok = PyTokenizer_FromUTF8(str, exec_input);
1226 } else {
1227 tok = PyTokenizer_FromString(str, exec_input);
1228 }
1229 if (tok == NULL) {
1230 if (PyErr_Occurred()) {
1231 raise_tokenizer_init_error(filename_ob);
1232 }
1233 return NULL;
1234 }
1235 // This transfers the ownership to the tokenizer
1236 tok->filename = filename_ob;
1237 Py_INCREF(filename_ob);
1238
1239 // We need to clear up from here on
1240 mod_ty result = NULL;
1241
Pablo Galindo2b74c832020-04-27 18:02:07 +01001242 int parser_flags = compute_parser_flags(flags);
Guido van Rossum2a1ee1d2020-06-27 17:34:30 -07001243 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1244 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001245 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1246 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001247 if (p == NULL) {
1248 goto error;
1249 }
1250
1251 result = _PyPegen_run_parser(p);
1252 _PyPegen_Parser_Free(p);
1253
1254error:
1255 PyTokenizer_Free(tok);
1256 return result;
1257}
1258
1259void *
1260_PyPegen_interactive_exit(Parser *p)
1261{
1262 if (p->errcode) {
1263 *(p->errcode) = E_EOF;
1264 }
1265 return NULL;
1266}
1267
1268/* Creates a single-element asdl_seq* that contains a */
1269asdl_seq *
1270_PyPegen_singleton_seq(Parser *p, void *a)
1271{
1272 assert(a != NULL);
1273 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1274 if (!seq) {
1275 return NULL;
1276 }
1277 asdl_seq_SET(seq, 0, a);
1278 return seq;
1279}
1280
1281/* Creates a copy of seq and prepends a to it */
1282asdl_seq *
1283_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1284{
1285 assert(a != NULL);
1286 if (!seq) {
1287 return _PyPegen_singleton_seq(p, a);
1288 }
1289
1290 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1291 if (!new_seq) {
1292 return NULL;
1293 }
1294
1295 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001296 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001297 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1298 }
1299 return new_seq;
1300}
1301
Guido van Rossumc001c092020-04-30 12:12:19 -07001302/* Creates a copy of seq and appends a to it */
1303asdl_seq *
1304_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1305{
1306 assert(a != NULL);
1307 if (!seq) {
1308 return _PyPegen_singleton_seq(p, a);
1309 }
1310
1311 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1312 if (!new_seq) {
1313 return NULL;
1314 }
1315
1316 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1317 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1318 }
1319 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1320 return new_seq;
1321}
1322
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001323static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001324_get_flattened_seq_size(asdl_seq *seqs)
1325{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001326 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001327 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1328 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1329 size += asdl_seq_LEN(inner_seq);
1330 }
1331 return size;
1332}
1333
1334/* Flattens an asdl_seq* of asdl_seq*s */
1335asdl_seq *
1336_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1337{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001338 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001339 assert(flattened_seq_size > 0);
1340
1341 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1342 if (!flattened_seq) {
1343 return NULL;
1344 }
1345
1346 int flattened_seq_idx = 0;
1347 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1348 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001349 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001350 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1351 }
1352 }
1353 assert(flattened_seq_idx == flattened_seq_size);
1354
1355 return flattened_seq;
1356}
1357
1358/* Creates a new name of the form <first_name>.<second_name> */
1359expr_ty
1360_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1361{
1362 assert(first_name != NULL && second_name != NULL);
1363 PyObject *first_identifier = first_name->v.Name.id;
1364 PyObject *second_identifier = second_name->v.Name.id;
1365
1366 if (PyUnicode_READY(first_identifier) == -1) {
1367 return NULL;
1368 }
1369 if (PyUnicode_READY(second_identifier) == -1) {
1370 return NULL;
1371 }
1372 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1373 if (!first_str) {
1374 return NULL;
1375 }
1376 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1377 if (!second_str) {
1378 return NULL;
1379 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001380 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001381
1382 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1383 if (!str) {
1384 return NULL;
1385 }
1386
1387 char *s = PyBytes_AS_STRING(str);
1388 if (!s) {
1389 return NULL;
1390 }
1391
1392 strcpy(s, first_str);
1393 s += strlen(first_str);
1394 *s++ = '.';
1395 strcpy(s, second_str);
1396 s += strlen(second_str);
1397 *s = '\0';
1398
1399 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1400 Py_DECREF(str);
1401 if (!uni) {
1402 return NULL;
1403 }
1404 PyUnicode_InternInPlace(&uni);
1405 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1406 Py_DECREF(uni);
1407 return NULL;
1408 }
1409
1410 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1411}
1412
1413/* Counts the total number of dots in seq's tokens */
1414int
1415_PyPegen_seq_count_dots(asdl_seq *seq)
1416{
1417 int number_of_dots = 0;
1418 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1419 Token *current_expr = asdl_seq_GET(seq, i);
1420 switch (current_expr->type) {
1421 case ELLIPSIS:
1422 number_of_dots += 3;
1423 break;
1424 case DOT:
1425 number_of_dots += 1;
1426 break;
1427 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001428 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001429 }
1430 }
1431
1432 return number_of_dots;
1433}
1434
1435/* Creates an alias with '*' as the identifier name */
1436alias_ty
1437_PyPegen_alias_for_star(Parser *p)
1438{
1439 PyObject *str = PyUnicode_InternFromString("*");
1440 if (!str) {
1441 return NULL;
1442 }
1443 if (PyArena_AddPyObject(p->arena, str) < 0) {
1444 Py_DECREF(str);
1445 return NULL;
1446 }
1447 return alias(str, NULL, p->arena);
1448}
1449
1450/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1451asdl_seq *
1452_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1453{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001454 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001455 assert(len > 0);
1456
1457 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1458 if (!new_seq) {
1459 return NULL;
1460 }
1461 for (Py_ssize_t i = 0; i < len; i++) {
1462 expr_ty e = asdl_seq_GET(seq, i);
1463 asdl_seq_SET(new_seq, i, e->v.Name.id);
1464 }
1465 return new_seq;
1466}
1467
1468/* Constructs a CmpopExprPair */
1469CmpopExprPair *
1470_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1471{
1472 assert(expr != NULL);
1473 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1474 if (!a) {
1475 return NULL;
1476 }
1477 a->cmpop = cmpop;
1478 a->expr = expr;
1479 return a;
1480}
1481
1482asdl_int_seq *
1483_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1484{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001485 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001486 assert(len > 0);
1487
1488 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1489 if (!new_seq) {
1490 return NULL;
1491 }
1492 for (Py_ssize_t i = 0; i < len; i++) {
1493 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1494 asdl_seq_SET(new_seq, i, pair->cmpop);
1495 }
1496 return new_seq;
1497}
1498
1499asdl_seq *
1500_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1501{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001502 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001503 assert(len > 0);
1504
1505 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1506 if (!new_seq) {
1507 return NULL;
1508 }
1509 for (Py_ssize_t i = 0; i < len; i++) {
1510 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1511 asdl_seq_SET(new_seq, i, pair->expr);
1512 }
1513 return new_seq;
1514}
1515
1516/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1517static asdl_seq *
1518_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1519{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001520 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001521 if (len == 0) {
1522 return NULL;
1523 }
1524
1525 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1526 if (!new_seq) {
1527 return NULL;
1528 }
1529 for (Py_ssize_t i = 0; i < len; i++) {
1530 expr_ty e = asdl_seq_GET(seq, i);
1531 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1532 }
1533 return new_seq;
1534}
1535
1536static expr_ty
1537_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1538{
1539 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1540}
1541
1542static expr_ty
1543_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1544{
1545 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1546}
1547
1548static expr_ty
1549_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1550{
1551 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1552}
1553
1554static expr_ty
1555_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1556{
1557 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1558}
1559
1560static expr_ty
1561_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1562{
1563 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1564}
1565
1566static expr_ty
1567_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1568{
1569 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1570}
1571
1572/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1573expr_ty
1574_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1575{
1576 assert(expr != NULL);
1577
1578 expr_ty new = NULL;
1579 switch (expr->kind) {
1580 case Name_kind:
1581 new = _set_name_context(p, expr, ctx);
1582 break;
1583 case Tuple_kind:
1584 new = _set_tuple_context(p, expr, ctx);
1585 break;
1586 case List_kind:
1587 new = _set_list_context(p, expr, ctx);
1588 break;
1589 case Subscript_kind:
1590 new = _set_subscript_context(p, expr, ctx);
1591 break;
1592 case Attribute_kind:
1593 new = _set_attribute_context(p, expr, ctx);
1594 break;
1595 case Starred_kind:
1596 new = _set_starred_context(p, expr, ctx);
1597 break;
1598 default:
1599 new = expr;
1600 }
1601 return new;
1602}
1603
1604/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1605KeyValuePair *
1606_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1607{
1608 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1609 if (!a) {
1610 return NULL;
1611 }
1612 a->key = key;
1613 a->value = value;
1614 return a;
1615}
1616
1617/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1618asdl_seq *
1619_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1620{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001621 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001622 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1623 if (!new_seq) {
1624 return NULL;
1625 }
1626 for (Py_ssize_t i = 0; i < len; i++) {
1627 KeyValuePair *pair = asdl_seq_GET(seq, i);
1628 asdl_seq_SET(new_seq, i, pair->key);
1629 }
1630 return new_seq;
1631}
1632
1633/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1634asdl_seq *
1635_PyPegen_get_values(Parser *p, asdl_seq *seq)
1636{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001637 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001638 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1639 if (!new_seq) {
1640 return NULL;
1641 }
1642 for (Py_ssize_t i = 0; i < len; i++) {
1643 KeyValuePair *pair = asdl_seq_GET(seq, i);
1644 asdl_seq_SET(new_seq, i, pair->value);
1645 }
1646 return new_seq;
1647}
1648
1649/* Constructs a NameDefaultPair */
1650NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001651_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001652{
1653 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1654 if (!a) {
1655 return NULL;
1656 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001657 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001658 a->value = value;
1659 return a;
1660}
1661
1662/* Constructs a SlashWithDefault */
1663SlashWithDefault *
1664_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1665{
1666 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1667 if (!a) {
1668 return NULL;
1669 }
1670 a->plain_names = plain_names;
1671 a->names_with_defaults = names_with_defaults;
1672 return a;
1673}
1674
1675/* Constructs a StarEtc */
1676StarEtc *
1677_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1678{
1679 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1680 if (!a) {
1681 return NULL;
1682 }
1683 a->vararg = vararg;
1684 a->kwonlyargs = kwonlyargs;
1685 a->kwarg = kwarg;
1686 return a;
1687}
1688
1689asdl_seq *
1690_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1691{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001692 Py_ssize_t first_len = asdl_seq_LEN(a);
1693 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001694 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1695 if (!new_seq) {
1696 return NULL;
1697 }
1698
1699 int k = 0;
1700 for (Py_ssize_t i = 0; i < first_len; i++) {
1701 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1702 }
1703 for (Py_ssize_t i = 0; i < second_len; i++) {
1704 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1705 }
1706
1707 return new_seq;
1708}
1709
1710static asdl_seq *
1711_get_names(Parser *p, asdl_seq *names_with_defaults)
1712{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001713 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001714 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1715 if (!seq) {
1716 return NULL;
1717 }
1718 for (Py_ssize_t i = 0; i < len; i++) {
1719 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1720 asdl_seq_SET(seq, i, pair->arg);
1721 }
1722 return seq;
1723}
1724
1725static asdl_seq *
1726_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1727{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001728 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001729 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1730 if (!seq) {
1731 return NULL;
1732 }
1733 for (Py_ssize_t i = 0; i < len; i++) {
1734 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1735 asdl_seq_SET(seq, i, pair->value);
1736 }
1737 return seq;
1738}
1739
1740/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1741arguments_ty
1742_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1743 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1744 asdl_seq *names_with_default, StarEtc *star_etc)
1745{
1746 asdl_seq *posonlyargs;
1747 if (slash_without_default != NULL) {
1748 posonlyargs = slash_without_default;
1749 }
1750 else if (slash_with_default != NULL) {
1751 asdl_seq *slash_with_default_names =
1752 _get_names(p, slash_with_default->names_with_defaults);
1753 if (!slash_with_default_names) {
1754 return NULL;
1755 }
1756 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1757 if (!posonlyargs) {
1758 return NULL;
1759 }
1760 }
1761 else {
1762 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1763 if (!posonlyargs) {
1764 return NULL;
1765 }
1766 }
1767
1768 asdl_seq *posargs;
1769 if (plain_names != NULL && names_with_default != NULL) {
1770 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1771 if (!names_with_default_names) {
1772 return NULL;
1773 }
1774 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1775 if (!posargs) {
1776 return NULL;
1777 }
1778 }
1779 else if (plain_names == NULL && names_with_default != NULL) {
1780 posargs = _get_names(p, names_with_default);
1781 if (!posargs) {
1782 return NULL;
1783 }
1784 }
1785 else if (plain_names != NULL && names_with_default == NULL) {
1786 posargs = plain_names;
1787 }
1788 else {
1789 posargs = _Py_asdl_seq_new(0, p->arena);
1790 if (!posargs) {
1791 return NULL;
1792 }
1793 }
1794
1795 asdl_seq *posdefaults;
1796 if (slash_with_default != NULL && names_with_default != NULL) {
1797 asdl_seq *slash_with_default_values =
1798 _get_defaults(p, slash_with_default->names_with_defaults);
1799 if (!slash_with_default_values) {
1800 return NULL;
1801 }
1802 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1803 if (!names_with_default_values) {
1804 return NULL;
1805 }
1806 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1807 if (!posdefaults) {
1808 return NULL;
1809 }
1810 }
1811 else if (slash_with_default == NULL && names_with_default != NULL) {
1812 posdefaults = _get_defaults(p, names_with_default);
1813 if (!posdefaults) {
1814 return NULL;
1815 }
1816 }
1817 else if (slash_with_default != NULL && names_with_default == NULL) {
1818 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1819 if (!posdefaults) {
1820 return NULL;
1821 }
1822 }
1823 else {
1824 posdefaults = _Py_asdl_seq_new(0, p->arena);
1825 if (!posdefaults) {
1826 return NULL;
1827 }
1828 }
1829
1830 arg_ty vararg = NULL;
1831 if (star_etc != NULL && star_etc->vararg != NULL) {
1832 vararg = star_etc->vararg;
1833 }
1834
1835 asdl_seq *kwonlyargs;
1836 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1837 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1838 if (!kwonlyargs) {
1839 return NULL;
1840 }
1841 }
1842 else {
1843 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1844 if (!kwonlyargs) {
1845 return NULL;
1846 }
1847 }
1848
1849 asdl_seq *kwdefaults;
1850 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1851 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1852 if (!kwdefaults) {
1853 return NULL;
1854 }
1855 }
1856 else {
1857 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1858 if (!kwdefaults) {
1859 return NULL;
1860 }
1861 }
1862
1863 arg_ty kwarg = NULL;
1864 if (star_etc != NULL && star_etc->kwarg != NULL) {
1865 kwarg = star_etc->kwarg;
1866 }
1867
1868 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1869 posdefaults, p->arena);
1870}
1871
1872/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1873 * arguments. */
1874arguments_ty
1875_PyPegen_empty_arguments(Parser *p)
1876{
1877 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1878 if (!posonlyargs) {
1879 return NULL;
1880 }
1881 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1882 if (!posargs) {
1883 return NULL;
1884 }
1885 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1886 if (!posdefaults) {
1887 return NULL;
1888 }
1889 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1890 if (!kwonlyargs) {
1891 return NULL;
1892 }
1893 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1894 if (!kwdefaults) {
1895 return NULL;
1896 }
1897
1898 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1899 p->arena);
1900}
1901
1902/* Encapsulates the value of an operator_ty into an AugOperator struct */
1903AugOperator *
1904_PyPegen_augoperator(Parser *p, operator_ty kind)
1905{
1906 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1907 if (!a) {
1908 return NULL;
1909 }
1910 a->kind = kind;
1911 return a;
1912}
1913
1914/* Construct a FunctionDef equivalent to function_def, but with decorators */
1915stmt_ty
1916_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1917{
1918 assert(function_def != NULL);
1919 if (function_def->kind == AsyncFunctionDef_kind) {
1920 return _Py_AsyncFunctionDef(
1921 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1922 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1923 function_def->v.FunctionDef.type_comment, function_def->lineno,
1924 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1925 p->arena);
1926 }
1927
1928 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1929 function_def->v.FunctionDef.body, decorators,
1930 function_def->v.FunctionDef.returns,
1931 function_def->v.FunctionDef.type_comment, function_def->lineno,
1932 function_def->col_offset, function_def->end_lineno,
1933 function_def->end_col_offset, p->arena);
1934}
1935
1936/* Construct a ClassDef equivalent to class_def, but with decorators */
1937stmt_ty
1938_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1939{
1940 assert(class_def != NULL);
1941 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1942 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1943 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1944 class_def->end_col_offset, p->arena);
1945}
1946
1947/* Construct a KeywordOrStarred */
1948KeywordOrStarred *
1949_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1950{
1951 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1952 if (!a) {
1953 return NULL;
1954 }
1955 a->element = element;
1956 a->is_keyword = is_keyword;
1957 return a;
1958}
1959
1960/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1961static int
1962_seq_number_of_starred_exprs(asdl_seq *seq)
1963{
1964 int n = 0;
1965 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1966 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1967 if (!k->is_keyword) {
1968 n++;
1969 }
1970 }
1971 return n;
1972}
1973
1974/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1975asdl_seq *
1976_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1977{
1978 int new_len = _seq_number_of_starred_exprs(kwargs);
1979 if (new_len == 0) {
1980 return NULL;
1981 }
1982 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1983 if (!new_seq) {
1984 return NULL;
1985 }
1986
1987 int idx = 0;
1988 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1989 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1990 if (!k->is_keyword) {
1991 asdl_seq_SET(new_seq, idx++, k->element);
1992 }
1993 }
1994 return new_seq;
1995}
1996
1997/* Return a new asdl_seq* with only the keywords in kwargs */
1998asdl_seq *
1999_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2000{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002001 Py_ssize_t len = asdl_seq_LEN(kwargs);
2002 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002003 if (new_len == 0) {
2004 return NULL;
2005 }
2006 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
2007 if (!new_seq) {
2008 return NULL;
2009 }
2010
2011 int idx = 0;
2012 for (Py_ssize_t i = 0; i < len; i++) {
2013 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
2014 if (k->is_keyword) {
2015 asdl_seq_SET(new_seq, idx++, k->element);
2016 }
2017 }
2018 return new_seq;
2019}
2020
2021expr_ty
2022_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2023{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002024 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002025 assert(len > 0);
2026
2027 Token *first = asdl_seq_GET(strings, 0);
2028 Token *last = asdl_seq_GET(strings, len - 1);
2029
2030 int bytesmode = 0;
2031 PyObject *bytes_str = NULL;
2032
2033 FstringParser state;
2034 _PyPegen_FstringParser_Init(&state);
2035
2036 for (Py_ssize_t i = 0; i < len; i++) {
2037 Token *t = asdl_seq_GET(strings, i);
2038
2039 int this_bytesmode;
2040 int this_rawmode;
2041 PyObject *s;
2042 const char *fstr;
2043 Py_ssize_t fstrlen = -1;
2044
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002045 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002046 goto error;
2047 }
2048
2049 /* Check that we are not mixing bytes with unicode. */
2050 if (i != 0 && bytesmode != this_bytesmode) {
2051 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2052 Py_XDECREF(s);
2053 goto error;
2054 }
2055 bytesmode = this_bytesmode;
2056
2057 if (fstr != NULL) {
2058 assert(s == NULL && !bytesmode);
2059
2060 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2061 this_rawmode, 0, first, t, last);
2062 if (result < 0) {
2063 goto error;
2064 }
2065 }
2066 else {
2067 /* String or byte string. */
2068 assert(s != NULL && fstr == NULL);
2069 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2070
2071 if (bytesmode) {
2072 if (i == 0) {
2073 bytes_str = s;
2074 }
2075 else {
2076 PyBytes_ConcatAndDel(&bytes_str, s);
2077 if (!bytes_str) {
2078 goto error;
2079 }
2080 }
2081 }
2082 else {
2083 /* This is a regular string. Concatenate it. */
2084 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2085 goto error;
2086 }
2087 }
2088 }
2089 }
2090
2091 if (bytesmode) {
2092 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2093 goto error;
2094 }
2095 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2096 last->end_col_offset, p->arena);
2097 }
2098
2099 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2100
2101error:
2102 Py_XDECREF(bytes_str);
2103 _PyPegen_FstringParser_Dealloc(&state);
2104 if (PyErr_Occurred()) {
2105 raise_decode_error(p);
2106 }
2107 return NULL;
2108}
Guido van Rossumc001c092020-04-30 12:12:19 -07002109
2110mod_ty
2111_PyPegen_make_module(Parser *p, asdl_seq *a) {
2112 asdl_seq *type_ignores = NULL;
2113 Py_ssize_t num = p->type_ignore_comments.num_items;
2114 if (num > 0) {
2115 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2116 type_ignores = _Py_asdl_seq_new(num, p->arena);
2117 if (type_ignores == NULL) {
2118 return NULL;
2119 }
2120 for (int i = 0; i < num; i++) {
2121 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2122 if (tag == NULL) {
2123 return NULL;
2124 }
2125 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2126 if (ti == NULL) {
2127 return NULL;
2128 }
2129 asdl_seq_SET(type_ignores, i, ti);
2130 }
2131 }
2132 return Module(a, type_ignores, p->arena);
2133}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002134
2135// Error reporting helpers
2136
2137expr_ty
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002138_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002139{
2140 if (e == NULL) {
2141 return NULL;
2142 }
2143
2144#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2145 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2146 for (Py_ssize_t i = 0; i < len; i++) {\
2147 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002148 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002149 if (child != NULL) {\
2150 return child;\
2151 }\
2152 }\
2153 } while (0)
2154
2155 // We only need to visit List and Tuple nodes recursively as those
2156 // are the only ones that can contain valid names in targets when
2157 // they are parsed as expressions. Any other kind of expression
2158 // that is a container (like Sets or Dicts) is directly invalid and
2159 // we don't need to visit it recursively.
2160
2161 switch (e->kind) {
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002162 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002163 VISIT_CONTAINER(e, List);
2164 return NULL;
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002165 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002166 VISIT_CONTAINER(e, Tuple);
2167 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002168 case Starred_kind:
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002169 if (targets_type == DEL_TARGETS) {
2170 return e;
2171 }
2172 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2173 case Compare_kind:
2174 // This is needed, because the `a in b` in `for a in b` gets parsed
2175 // as a comparison, and so we need to search the left side of the comparison
2176 // for invalid targets.
2177 if (targets_type == FOR_TARGETS) {
2178 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2179 if (cmpop == In) {
2180 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2181 }
2182 return NULL;
2183 }
2184 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002185 case Name_kind:
2186 case Subscript_kind:
2187 case Attribute_kind:
2188 return NULL;
2189 default:
2190 return e;
2191 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002192}
2193
2194void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2195 int kwarg_unpacking = 0;
2196 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2197 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2198 if (!keyword->arg) {
2199 kwarg_unpacking = 1;
2200 }
2201 }
2202
2203 const char *msg = NULL;
2204 if (kwarg_unpacking) {
2205 msg = "positional argument follows keyword argument unpacking";
2206 } else {
2207 msg = "positional argument follows keyword argument";
2208 }
2209
2210 return RAISE_SYNTAX_ERROR(msg);
2211}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002212
2213void *
2214_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2215{
2216 /* The rule that calls this function is 'args for_if_clauses'.
2217 For the input f(L, x for x in y), L and x are in args and
2218 the for is parsed as a for_if_clause. We have to check if
2219 len <= 1, so that input like dict((a, b) for a, b in x)
2220 gets successfully parsed and then we pass the last
2221 argument (x in the above example) as the location of the
2222 error */
2223 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2224 if (len <= 1) {
2225 return NULL;
2226 }
2227
2228 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2229 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2230 "Generator expression must be parenthesized"
2231 );
2232}
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002233
2234
Pablo Galindobe172952020-09-03 16:35:17 +01002235expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_seq *a, asdl_seq *b,
2236 int lineno, int col_offset, int end_lineno,
2237 int end_col_offset, PyArena *arena) {
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002238 Py_ssize_t args_len = asdl_seq_LEN(a);
2239 Py_ssize_t total_len = args_len;
2240
2241 if (b == NULL) {
Pablo Galindobe172952020-09-03 16:35:17 +01002242 return _Py_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2243 end_lineno, end_col_offset, arena);
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002244
2245 }
2246
2247 asdl_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2248 asdl_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
2249
2250 if (starreds) {
2251 total_len += asdl_seq_LEN(starreds);
2252 }
2253
Pablo Galindobe172952020-09-03 16:35:17 +01002254 asdl_seq *args = _Py_asdl_seq_new(total_len, arena);
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002255
2256 Py_ssize_t i = 0;
2257 for (i = 0; i < args_len; i++) {
2258 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2259 }
2260 for (; i < total_len; i++) {
2261 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2262 }
2263
Pablo Galindobe172952020-09-03 16:35:17 +01002264 return _Py_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2265 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002266
Pablo Galindobe172952020-09-03 16:35:17 +01002267
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002268}