blob: d2b7ec44eb1557aef93ed40741a74330eae3439d [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
Victor Stinnereec8e612021-03-18 14:57:49 +01002#include "pycore_ast.h" // _PyAST_Validate()
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003#include <errcode.h>
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01004#include "tokenizer.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005
6#include "pegen.h"
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01007#include "string_parser.h"
Pablo Galindo13322262020-07-27 23:46:59 +01008#include "ast.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01009
Guido van Rossumc001c092020-04-30 12:12:19 -070010PyObject *
11_PyPegen_new_type_comment(Parser *p, char *s)
12{
13 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
14 if (res == NULL) {
15 return NULL;
16 }
17 if (PyArena_AddPyObject(p->arena, res) < 0) {
18 Py_DECREF(res);
19 return NULL;
20 }
21 return res;
22}
23
24arg_ty
25_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
26{
27 if (tc == NULL) {
28 return a;
29 }
30 char *bytes = PyBytes_AsString(tc->bytes);
31 if (bytes == NULL) {
32 return NULL;
33 }
34 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
35 if (tco == NULL) {
36 return NULL;
37 }
38 return arg(a->arg, a->annotation, tco,
39 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
40 p->arena);
41}
42
Pablo Galindoc5fc1562020-04-22 23:29:27 +010043static int
44init_normalization(Parser *p)
45{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030046 if (p->normalize) {
47 return 1;
48 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010049 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
50 if (!m)
51 {
52 return 0;
53 }
54 p->normalize = PyObject_GetAttrString(m, "normalize");
55 Py_DECREF(m);
56 if (!p->normalize)
57 {
58 return 0;
59 }
60 return 1;
61}
62
Pablo Galindo2b74c832020-04-27 18:02:07 +010063/* Checks if the NOTEQUAL token is valid given the current parser flags
640 indicates success and nonzero indicates failure (an exception may be set) */
65int
Pablo Galindo06f8c332020-10-30 23:48:42 +000066_PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010067 assert(t->bytes != NULL);
68 assert(t->type == NOTEQUAL);
69
70 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindofb61c422020-06-15 14:23:43 +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 Galindofb61c422020-06-15 14:23:43 +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
Pablo Galindo51c58962020-06-16 16:49:43 +0100144byte_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 }
Pablo Galindo123ff262021-03-22 16:24:39 +0000150 Py_ssize_t len = strlen(str);
151 if (col_offset > len) {
152 col_offset = len;
153 }
154 assert(col_offset >= 0);
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300155 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100156 if (!text) {
157 return 0;
158 }
159 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
160 Py_DECREF(text);
161 return size;
162}
163
164const char *
165_PyPegen_get_expr_name(expr_ty e)
166{
Pablo Galindo9f495902020-06-08 02:57:00 +0100167 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100168 switch (e->kind) {
169 case Attribute_kind:
170 return "attribute";
171 case Subscript_kind:
172 return "subscript";
173 case Starred_kind:
174 return "starred";
175 case Name_kind:
176 return "name";
177 case List_kind:
178 return "list";
179 case Tuple_kind:
180 return "tuple";
181 case Lambda_kind:
182 return "lambda";
183 case Call_kind:
184 return "function call";
185 case BoolOp_kind:
186 case BinOp_kind:
187 case UnaryOp_kind:
188 return "operator";
189 case GeneratorExp_kind:
190 return "generator expression";
191 case Yield_kind:
192 case YieldFrom_kind:
193 return "yield expression";
194 case Await_kind:
195 return "await expression";
196 case ListComp_kind:
197 return "list comprehension";
198 case SetComp_kind:
199 return "set comprehension";
200 case DictComp_kind:
201 return "dict comprehension";
202 case Dict_kind:
203 return "dict display";
204 case Set_kind:
205 return "set display";
206 case JoinedStr_kind:
207 case FormattedValue_kind:
208 return "f-string expression";
209 case Constant_kind: {
210 PyObject *value = e->v.Constant.value;
211 if (value == Py_None) {
212 return "None";
213 }
214 if (value == Py_False) {
215 return "False";
216 }
217 if (value == Py_True) {
218 return "True";
219 }
220 if (value == Py_Ellipsis) {
221 return "Ellipsis";
222 }
223 return "literal";
224 }
225 case Compare_kind:
226 return "comparison";
227 case IfExp_kind:
228 return "conditional expression";
229 case NamedExpr_kind:
230 return "named expression";
231 default:
232 PyErr_Format(PyExc_SystemError,
233 "unexpected expression in assignment %d (line %d)",
234 e->kind, e->lineno);
235 return NULL;
236 }
237}
238
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300239static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100240raise_decode_error(Parser *p)
241{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300242 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100243 const char *errtype = NULL;
244 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
245 errtype = "unicode error";
246 }
247 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
248 errtype = "value error";
249 }
250 if (errtype) {
Pablo Galindofb61c422020-06-15 14:23:43 +0100251 PyObject *type;
252 PyObject *value;
253 PyObject *tback;
254 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100255 PyErr_Fetch(&type, &value, &tback);
256 errstr = PyObject_Str(value);
257 if (errstr) {
258 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
259 Py_DECREF(errstr);
260 }
261 else {
262 PyErr_Clear();
263 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
264 }
265 Py_XDECREF(type);
266 Py_XDECREF(value);
267 Py_XDECREF(tback);
268 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300269
270 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100271}
272
Pablo Galindod6d63712021-01-19 23:59:33 +0000273static inline void
274raise_unclosed_parentheses_error(Parser *p) {
275 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
276 int error_col = p->tok->parencolstack[p->tok->level-1];
277 RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError,
278 error_lineno, error_col,
279 "'%c' was never closed",
280 p->tok->parenstack[p->tok->level-1]);
281}
282
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100283static void
284raise_tokenizer_init_error(PyObject *filename)
285{
286 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
287 || PyErr_ExceptionMatches(PyExc_ValueError)
288 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
289 return;
290 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300291 PyObject *errstr = NULL;
292 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100293 PyObject *type;
294 PyObject *value;
295 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100296 PyErr_Fetch(&type, &value, &tback);
297 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300298 if (!errstr) {
299 goto error;
300 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100301
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300302 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100303 if (!tmp) {
304 goto error;
305 }
306
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300307 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308 Py_DECREF(tmp);
309 if (!value) {
310 goto error;
311 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300312 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100313
314error:
315 Py_XDECREF(type);
316 Py_XDECREF(value);
317 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300318 Py_XDECREF(errstr);
319 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320}
321
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100322static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100323tokenizer_error(Parser *p)
324{
325 if (PyErr_Occurred()) {
326 return -1;
327 }
328
329 const char *msg = NULL;
330 PyObject* errtype = PyExc_SyntaxError;
Pablo Galindo96eeff52021-03-22 17:28:11 +0000331 Py_ssize_t col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332 switch (p->tok->done) {
333 case E_TOKEN:
334 msg = "invalid token";
335 break;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300336 case E_EOF:
Pablo Galindod6d63712021-01-19 23:59:33 +0000337 if (p->tok->level) {
338 raise_unclosed_parentheses_error(p);
339 } else {
340 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
341 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300342 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100343 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300344 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
345 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100346 case E_INTR:
347 if (!PyErr_Occurred()) {
348 PyErr_SetNone(PyExc_KeyboardInterrupt);
349 }
350 return -1;
351 case E_NOMEM:
352 PyErr_NoMemory();
353 return -1;
354 case E_TABSPACE:
355 errtype = PyExc_TabError;
356 msg = "inconsistent use of tabs and spaces in indentation";
357 break;
358 case E_TOODEEP:
359 errtype = PyExc_IndentationError;
360 msg = "too many levels of indentation";
361 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100362 case E_LINECONT:
Pablo Galindo96eeff52021-03-22 17:28:11 +0000363 col_offset = strlen(strtok(p->tok->buf, "\n")) - 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100364 msg = "unexpected character after line continuation character";
365 break;
366 default:
367 msg = "unknown parsing error";
368 }
369
Pablo Galindo96eeff52021-03-22 17:28:11 +0000370 RAISE_ERROR_KNOWN_LOCATION(p, errtype, p->tok->lineno, col_offset, msg);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100371 return -1;
372}
373
374void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300375_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
376{
377 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100378 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300379 if (t->col_offset == -1) {
380 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
381 intptr_t, int);
382 } else {
383 col_offset = t->col_offset + 1;
384 }
385
386 va_list va;
387 va_start(va, errmsg);
388 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
389 col_offset, errmsg, va);
390 va_end(va);
391
392 return NULL;
393}
394
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200395static PyObject *
396get_error_line(Parser *p, Py_ssize_t lineno)
397{
Pablo Galindo123ff262021-03-22 16:24:39 +0000398 /* If the file descriptor is interactive, the source lines of the current
399 * (multi-line) statement are stored in p->tok->interactive_src_start.
400 * If not, we're parsing from a string, which means that the whole source
401 * is stored in p->tok->str. */
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200402 assert(p->tok->fp == NULL || p->tok->fp == stdin);
403
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100404 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
405
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200406 for (int i = 0; i < lineno - 1; i++) {
407 cur_line = strchr(cur_line, '\n') + 1;
408 }
409
410 char *next_newline;
411 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
412 next_newline = cur_line + strlen(cur_line);
413 }
414 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
415}
416
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300417void *
418_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100419 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300420 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100421{
422 PyObject *value = NULL;
423 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300424 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100425 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300426 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100427
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300428 if (p->start_rule == Py_fstring_input) {
429 const char *fstring_msg = "f-string: ";
430 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
431
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300432 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300433 if (!new_errmsg) {
434 return (void *) PyErr_NoMemory();
435 }
436
437 // Copy both strings into new buffer
438 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
439 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
440 new_errmsg[len] = 0;
441 errmsg = new_errmsg;
442 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100443 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100444 if (!errstr) {
445 goto error;
446 }
447
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100448 if (p->tok->fp_interactive) {
449 error_line = get_error_line(p, lineno);
450 }
451 else if (p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300452 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100453 }
454
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300455 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200456 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
457 then we need to find the error line from some other source, because
458 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
459 failed or we're parsing from a string or the REPL. There's a third edge case where
460 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
461 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
462 does not physically exist */
463 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
464
Pablo Galindo40901512021-01-31 22:48:23 +0000465 if (p->tok->lineno <= lineno) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200466 Py_ssize_t size = p->tok->inp - p->tok->buf;
467 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
468 }
469 else {
470 error_line = get_error_line(p, lineno);
471 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300472 if (!error_line) {
473 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300474 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100475 }
476
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300477 if (p->start_rule == Py_fstring_input) {
478 col_offset -= p->starting_col_offset;
479 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100480 Py_ssize_t col_number = col_offset;
481
482 if (p->tok->encoding != NULL) {
483 col_number = byte_offset_to_character_offset(error_line, col_offset);
484 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300485
486 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100487 if (!tmp) {
488 goto error;
489 }
490 value = PyTuple_Pack(2, errstr, tmp);
491 Py_DECREF(tmp);
492 if (!value) {
493 goto error;
494 }
495 PyErr_SetObject(errtype, value);
496
497 Py_DECREF(errstr);
498 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300499 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300500 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300501 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100502 return NULL;
503
504error:
505 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300506 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300507 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300508 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300509 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100510 return NULL;
511}
512
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100513#if 0
514static const char *
515token_name(int type)
516{
517 if (0 <= type && type <= N_TOKENS) {
518 return _PyParser_TokenNames[type];
519 }
520 return "<Huh?>";
521}
522#endif
523
524// Here, mark is the start of the node, while p->mark is the end.
525// If node==NULL, they should be the same.
526int
527_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
528{
529 // Insert in front
530 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
531 if (m == NULL) {
532 return -1;
533 }
534 m->type = type;
535 m->node = node;
536 m->mark = p->mark;
537 m->next = p->tokens[mark]->memo;
538 p->tokens[mark]->memo = m;
539 return 0;
540}
541
542// Like _PyPegen_insert_memo(), but updates an existing node if found.
543int
544_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
545{
546 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
547 if (m->type == type) {
548 // Update existing node.
549 m->node = node;
550 m->mark = p->mark;
551 return 0;
552 }
553 }
554 // Insert new node.
555 return _PyPegen_insert_memo(p, mark, type, node);
556}
557
558// Return dummy NAME.
559void *
560_PyPegen_dummy_name(Parser *p, ...)
561{
562 static void *cache = NULL;
563
564 if (cache != NULL) {
565 return cache;
566 }
567
568 PyObject *id = _create_dummy_identifier(p);
569 if (!id) {
570 return NULL;
571 }
572 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
573 return cache;
574}
575
576static int
577_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
578{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300579 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100580 if (name_len >= p->n_keyword_lists ||
581 p->keywords[name_len] == NULL ||
582 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100583 return NAME;
584 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100585 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100586 if (strncmp(k->str, name, name_len) == 0) {
587 return k->type;
588 }
589 }
590 return NAME;
591}
592
Guido van Rossumc001c092020-04-30 12:12:19 -0700593static int
594growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
595 assert(initial_size > 0);
596 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
597 arr->size = initial_size;
598 arr->num_items = 0;
599
600 return arr->items != NULL;
601}
602
603static int
604growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
605 if (arr->num_items >= arr->size) {
606 size_t new_size = arr->size * 2;
607 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
608 if (!new_items_array) {
609 return 0;
610 }
611 arr->items = new_items_array;
612 arr->size = new_size;
613 }
614
615 arr->items[arr->num_items].lineno = lineno;
616 arr->items[arr->num_items].comment = comment; // Take ownership
617 arr->num_items++;
618 return 1;
619}
620
621static void
622growable_comment_array_deallocate(growable_comment_array *arr) {
623 for (unsigned i = 0; i < arr->num_items; i++) {
624 PyMem_Free(arr->items[i].comment);
625 }
626 PyMem_Free(arr->items);
627}
628
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100629int
630_PyPegen_fill_token(Parser *p)
631{
Pablo Galindofb61c422020-06-15 14:23:43 +0100632 const char *start;
633 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100634 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700635
636 // Record and skip '# type: ignore' comments
637 while (type == TYPE_IGNORE) {
638 Py_ssize_t len = end - start;
639 char *tag = PyMem_Malloc(len + 1);
640 if (tag == NULL) {
641 PyErr_NoMemory();
642 return -1;
643 }
644 strncpy(tag, start, len);
645 tag[len] = '\0';
646 // Ownership of tag passes to the growable array
647 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
648 PyErr_NoMemory();
649 return -1;
650 }
651 type = PyTokenizer_Get(p->tok, &start, &end);
652 }
653
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100654 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
655 type = NEWLINE; /* Add an extra newline */
656 p->parsing_started = 0;
657
Pablo Galindob94dbd72020-04-27 18:35:58 +0100658 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100659 p->tok->pendin = -p->tok->indent;
660 p->tok->indent = 0;
661 }
662 }
663 else {
664 p->parsing_started = 1;
665 }
666
667 if (p->fill == p->size) {
668 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300669 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
670 if (new_tokens == NULL) {
671 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100672 return -1;
673 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100674 p->tokens = new_tokens;
675
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100676 for (int i = p->size; i < newsize; i++) {
677 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300678 if (p->tokens[i] == NULL) {
679 p->size = i; // Needed, in order to cleanup correctly after parser fails
680 PyErr_NoMemory();
681 return -1;
682 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100683 memset(p->tokens[i], '\0', sizeof(Token));
684 }
685 p->size = newsize;
686 }
687
688 Token *t = p->tokens[p->fill];
689 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
690 t->bytes = PyBytes_FromStringAndSize(start, end - start);
691 if (t->bytes == NULL) {
692 return -1;
693 }
694 PyArena_AddPyObject(p->arena, t->bytes);
695
696 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
697 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100698 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100699 int col_offset = -1;
700 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100701 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100702 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100703 }
704 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100705 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100706 }
707
708 t->lineno = p->starting_lineno + lineno;
709 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
710 t->end_lineno = p->starting_lineno + end_lineno;
711 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
712
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100713 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300714
715 if (type == ERRORTOKEN) {
716 if (p->tok->done == E_DECODE) {
717 return raise_decode_error(p);
718 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100719 return tokenizer_error(p);
720
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300721 }
722
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100723 return 0;
724}
725
726// Instrumentation to count the effectiveness of memoization.
727// The array counts the number of tokens skipped by memoization,
728// indexed by type.
729
730#define NSTATISTICS 2000
731static long memo_statistics[NSTATISTICS];
732
733void
734_PyPegen_clear_memo_statistics()
735{
736 for (int i = 0; i < NSTATISTICS; i++) {
737 memo_statistics[i] = 0;
738 }
739}
740
741PyObject *
742_PyPegen_get_memo_statistics()
743{
744 PyObject *ret = PyList_New(NSTATISTICS);
745 if (ret == NULL) {
746 return NULL;
747 }
748 for (int i = 0; i < NSTATISTICS; i++) {
749 PyObject *value = PyLong_FromLong(memo_statistics[i]);
750 if (value == NULL) {
751 Py_DECREF(ret);
752 return NULL;
753 }
754 // PyList_SetItem borrows a reference to value.
755 if (PyList_SetItem(ret, i, value) < 0) {
756 Py_DECREF(ret);
757 return NULL;
758 }
759 }
760 return ret;
761}
762
763int // bool
764_PyPegen_is_memoized(Parser *p, int type, void *pres)
765{
766 if (p->mark == p->fill) {
767 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300768 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100769 return -1;
770 }
771 }
772
773 Token *t = p->tokens[p->mark];
774
775 for (Memo *m = t->memo; m != NULL; m = m->next) {
776 if (m->type == type) {
777 if (0 <= type && type < NSTATISTICS) {
778 long count = m->mark - p->mark;
779 // A memoized negative result counts for one.
780 if (count <= 0) {
781 count = 1;
782 }
783 memo_statistics[type] += count;
784 }
785 p->mark = m->mark;
786 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100787 return 1;
788 }
789 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100790 return 0;
791}
792
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100793int
794_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
795{
796 int mark = p->mark;
797 void *res = func(p);
798 p->mark = mark;
799 return (res != NULL) == positive;
800}
801
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100802int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100803_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
804{
805 int mark = p->mark;
806 void *res = func(p, arg);
807 p->mark = mark;
808 return (res != NULL) == positive;
809}
810
811int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100812_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
813{
814 int mark = p->mark;
815 void *res = func(p, arg);
816 p->mark = mark;
817 return (res != NULL) == positive;
818}
819
820int
821_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
822{
823 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100824 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100825 p->mark = mark;
826 return (res != NULL) == positive;
827}
828
829Token *
830_PyPegen_expect_token(Parser *p, int type)
831{
832 if (p->mark == p->fill) {
833 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300834 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100835 return NULL;
836 }
837 }
838 Token *t = p->tokens[p->mark];
839 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100840 return NULL;
841 }
842 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100843 return t;
844}
845
Pablo Galindo58fb1562021-02-02 19:54:22 +0000846Token *
847_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
848
849 if (p->error_indicator == 1) {
850 return NULL;
851 }
852
853 if (p->mark == p->fill) {
854 if (_PyPegen_fill_token(p) < 0) {
855 p->error_indicator = 1;
856 return NULL;
857 }
858 }
859 Token *t = p->tokens[p->mark];
860 if (t->type != type) {
861 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
862 return NULL;
863 }
864 p->mark += 1;
865 return t;
866}
867
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700868expr_ty
869_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
870{
871 if (p->mark == p->fill) {
872 if (_PyPegen_fill_token(p) < 0) {
873 p->error_indicator = 1;
874 return NULL;
875 }
876 }
877 Token *t = p->tokens[p->mark];
878 if (t->type != NAME) {
879 return NULL;
880 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300881 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700882 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300883 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700884 return NULL;
885 }
886 if (strcmp(s, keyword) != 0) {
887 return NULL;
888 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300889 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700890}
891
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100892Token *
893_PyPegen_get_last_nonnwhitespace_token(Parser *p)
894{
895 assert(p->mark >= 0);
896 Token *token = NULL;
897 for (int m = p->mark - 1; m >= 0; m--) {
898 token = p->tokens[m];
899 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
900 break;
901 }
902 }
903 return token;
904}
905
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100906expr_ty
907_PyPegen_name_token(Parser *p)
908{
909 Token *t = _PyPegen_expect_token(p, NAME);
910 if (t == NULL) {
911 return NULL;
912 }
913 char* s = PyBytes_AsString(t->bytes);
914 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300915 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100916 return NULL;
917 }
918 PyObject *id = _PyPegen_new_identifier(p, s);
919 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300920 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100921 return NULL;
922 }
923 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
924 p->arena);
925}
926
927void *
928_PyPegen_string_token(Parser *p)
929{
930 return _PyPegen_expect_token(p, STRING);
931}
932
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100933static PyObject *
934parsenumber_raw(const char *s)
935{
936 const char *end;
937 long x;
938 double dx;
939 Py_complex compl;
940 int imflag;
941
942 assert(s != NULL);
943 errno = 0;
944 end = s + strlen(s) - 1;
945 imflag = *end == 'j' || *end == 'J';
946 if (s[0] == '0') {
947 x = (long)PyOS_strtoul(s, (char **)&end, 0);
948 if (x < 0 && errno == 0) {
949 return PyLong_FromString(s, (char **)0, 0);
950 }
951 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100952 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100953 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100954 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100955 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100956 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100957 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100958 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100959 return PyLong_FromLong(x);
960 }
961 /* XXX Huge floats may silently fail */
962 if (imflag) {
963 compl.real = 0.;
964 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100965 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100966 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100967 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100968 return PyComplex_FromCComplex(compl);
969 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100970 dx = PyOS_string_to_double(s, NULL, NULL);
971 if (dx == -1.0 && PyErr_Occurred()) {
972 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100973 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100974 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100975}
976
977static PyObject *
978parsenumber(const char *s)
979{
Pablo Galindofb61c422020-06-15 14:23:43 +0100980 char *dup;
981 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100982 PyObject *res = NULL;
983
984 assert(s != NULL);
985
986 if (strchr(s, '_') == NULL) {
987 return parsenumber_raw(s);
988 }
989 /* Create a duplicate without underscores. */
990 dup = PyMem_Malloc(strlen(s) + 1);
991 if (dup == NULL) {
992 return PyErr_NoMemory();
993 }
994 end = dup;
995 for (; *s; s++) {
996 if (*s != '_') {
997 *end++ = *s;
998 }
999 }
1000 *end = '\0';
1001 res = parsenumber_raw(dup);
1002 PyMem_Free(dup);
1003 return res;
1004}
1005
1006expr_ty
1007_PyPegen_number_token(Parser *p)
1008{
1009 Token *t = _PyPegen_expect_token(p, NUMBER);
1010 if (t == NULL) {
1011 return NULL;
1012 }
1013
1014 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001015 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001016 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001017 return NULL;
1018 }
1019
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001020 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1021 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -07001022 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001023 "in Python 3.6 and greater");
1024 }
1025
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001026 PyObject *c = parsenumber(num_raw);
1027
1028 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001029 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001030 return NULL;
1031 }
1032
1033 if (PyArena_AddPyObject(p->arena, c) < 0) {
1034 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001035 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001036 return NULL;
1037 }
1038
1039 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
1040 p->arena);
1041}
1042
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001043static int // bool
1044newline_in_string(Parser *p, const char *cur)
1045{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001046 for (const char *c = cur; c >= p->tok->buf; c--) {
1047 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001048 return 1;
1049 }
1050 }
1051 return 0;
1052}
1053
1054/* Check that the source for a single input statement really is a single
1055 statement by looking at what is left in the buffer after parsing.
1056 Trailing whitespace and comments are OK. */
1057static int // bool
1058bad_single_statement(Parser *p)
1059{
1060 const char *cur = strchr(p->tok->buf, '\n');
1061
1062 /* Newlines are allowed if preceded by a line continuation character
1063 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001064 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1065 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001066 return 0;
1067 }
1068 char c = *cur;
1069
1070 for (;;) {
1071 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1072 c = *++cur;
1073 }
1074
1075 if (!c) {
1076 return 0;
1077 }
1078
1079 if (c != '#') {
1080 return 1;
1081 }
1082
1083 /* Suck up comment. */
1084 while (c && c != '\n') {
1085 c = *++cur;
1086 }
1087 }
1088}
1089
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001090void
1091_PyPegen_Parser_Free(Parser *p)
1092{
1093 Py_XDECREF(p->normalize);
1094 for (int i = 0; i < p->size; i++) {
1095 PyMem_Free(p->tokens[i]);
1096 }
1097 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001098 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001099 PyMem_Free(p);
1100}
1101
Pablo Galindo2b74c832020-04-27 18:02:07 +01001102static int
1103compute_parser_flags(PyCompilerFlags *flags)
1104{
1105 int parser_flags = 0;
1106 if (!flags) {
1107 return 0;
1108 }
1109 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1110 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1111 }
1112 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1113 parser_flags |= PyPARSE_IGNORE_COOKIE;
1114 }
1115 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1116 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1117 }
1118 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1119 parser_flags |= PyPARSE_TYPE_COMMENTS;
1120 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001121 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001122 parser_flags |= PyPARSE_ASYNC_HACKS;
1123 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001124 return parser_flags;
1125}
1126
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001127Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001128_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001129 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001130{
1131 Parser *p = PyMem_Malloc(sizeof(Parser));
1132 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001133 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001134 }
1135 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001136 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1137 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001138 p->tok = tok;
1139 p->keywords = NULL;
1140 p->n_keyword_lists = -1;
1141 p->tokens = PyMem_Malloc(sizeof(Token *));
1142 if (!p->tokens) {
1143 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001144 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001145 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001146 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001147 if (!p->tokens) {
1148 PyMem_Free(p->tokens);
1149 PyMem_Free(p);
1150 return (Parser *) PyErr_NoMemory();
1151 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001152 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1153 PyMem_Free(p->tokens[0]);
1154 PyMem_Free(p->tokens);
1155 PyMem_Free(p);
1156 return (Parser *) PyErr_NoMemory();
1157 }
1158
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001159 p->mark = 0;
1160 p->fill = 0;
1161 p->size = 1;
1162
1163 p->errcode = errcode;
1164 p->arena = arena;
1165 p->start_rule = start_rule;
1166 p->parsing_started = 0;
1167 p->normalize = NULL;
1168 p->error_indicator = 0;
1169
1170 p->starting_lineno = 0;
1171 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001172 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001173 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001174 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001175 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001176 p->call_invalid_rules = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001177
1178 return p;
1179}
1180
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001181static void
1182reset_parser_state(Parser *p)
1183{
1184 for (int i = 0; i < p->fill; i++) {
1185 p->tokens[i]->memo = NULL;
1186 }
1187 p->mark = 0;
1188 p->call_invalid_rules = 1;
1189}
1190
Pablo Galindod6d63712021-01-19 23:59:33 +00001191static int
1192_PyPegen_check_tokenizer_errors(Parser *p) {
1193 // Tokenize the whole input to see if there are any tokenization
1194 // errors such as mistmatching parentheses. These will get priority
1195 // over generic syntax errors only if the line number of the error is
1196 // before the one that we had for the generic error.
1197
1198 // We don't want to tokenize to the end for interactive input
1199 if (p->tok->prompt != NULL) {
1200 return 0;
1201 }
1202
Pablo Galindod6d63712021-01-19 23:59:33 +00001203 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1204 Py_ssize_t current_err_line = current_token->lineno;
1205
Pablo Galindod6d63712021-01-19 23:59:33 +00001206 for (;;) {
1207 const char *start;
1208 const char *end;
1209 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1210 case ERRORTOKEN:
1211 if (p->tok->level != 0) {
1212 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1213 if (current_err_line > error_lineno) {
1214 raise_unclosed_parentheses_error(p);
1215 return -1;
1216 }
1217 }
1218 break;
1219 case ENDMARKER:
1220 break;
1221 default:
1222 continue;
1223 }
1224 break;
1225 }
1226
Pablo Galindod6d63712021-01-19 23:59:33 +00001227 return 0;
1228}
1229
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001230void *
1231_PyPegen_run_parser(Parser *p)
1232{
1233 void *res = _PyPegen_parse(p);
1234 if (res == NULL) {
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001235 reset_parser_state(p);
1236 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001237 if (PyErr_Occurred()) {
1238 return NULL;
1239 }
1240 if (p->fill == 0) {
1241 RAISE_SYNTAX_ERROR("error at start before reading any input");
1242 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001243 else if (p->tok->done == E_EOF) {
Pablo Galindod6d63712021-01-19 23:59:33 +00001244 if (p->tok->level) {
1245 raise_unclosed_parentheses_error(p);
1246 } else {
1247 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1248 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001249 }
1250 else {
1251 if (p->tokens[p->fill-1]->type == INDENT) {
1252 RAISE_INDENTATION_ERROR("unexpected indent");
1253 }
1254 else if (p->tokens[p->fill-1]->type == DEDENT) {
1255 RAISE_INDENTATION_ERROR("unexpected unindent");
1256 }
1257 else {
1258 RAISE_SYNTAX_ERROR("invalid syntax");
Pablo Galindoc3f167d2021-01-20 19:11:56 +00001259 // _PyPegen_check_tokenizer_errors will override the existing
1260 // generic SyntaxError we just raised if errors are found.
1261 _PyPegen_check_tokenizer_errors(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001262 }
1263 }
1264 return NULL;
1265 }
1266
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001267 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1268 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1269 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1270 }
1271
Victor Stinnere0bf70d2021-03-18 02:46:06 +01001272 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1273#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
Pablo Galindo13322262020-07-27 23:46:59 +01001274 if (p->start_rule == Py_single_input ||
1275 p->start_rule == Py_file_input ||
1276 p->start_rule == Py_eval_input)
1277 {
Victor Stinnereec8e612021-03-18 14:57:49 +01001278 if (!_PyAST_Validate(res)) {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001279 return NULL;
1280 }
Pablo Galindo13322262020-07-27 23:46:59 +01001281 }
1282#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001283 return res;
1284}
1285
1286mod_ty
1287_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1288 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001289 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001290{
1291 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1292 if (tok == NULL) {
1293 if (PyErr_Occurred()) {
1294 raise_tokenizer_init_error(filename_ob);
1295 return NULL;
1296 }
1297 return NULL;
1298 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001299 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1300 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1301 tok->fp_interactive = 1;
1302 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001303 // This transfers the ownership to the tokenizer
1304 tok->filename = filename_ob;
1305 Py_INCREF(filename_ob);
1306
1307 // From here on we need to clean up even if there's an error
1308 mod_ty result = NULL;
1309
Pablo Galindo2b74c832020-04-27 18:02:07 +01001310 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001311 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1312 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001313 if (p == NULL) {
1314 goto error;
1315 }
1316
1317 result = _PyPegen_run_parser(p);
1318 _PyPegen_Parser_Free(p);
1319
1320error:
1321 PyTokenizer_Free(tok);
1322 return result;
1323}
1324
1325mod_ty
1326_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001327 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001328{
1329 FILE *fp = fopen(filename, "rb");
1330 if (fp == NULL) {
1331 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1332 return NULL;
1333 }
1334
1335 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001336 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001337
1338 fclose(fp);
1339 return result;
1340}
1341
1342mod_ty
1343_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001344 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001345{
1346 int exec_input = start_rule == Py_file_input;
1347
1348 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001349 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001350 tok = PyTokenizer_FromUTF8(str, exec_input);
1351 } else {
1352 tok = PyTokenizer_FromString(str, exec_input);
1353 }
1354 if (tok == NULL) {
1355 if (PyErr_Occurred()) {
1356 raise_tokenizer_init_error(filename_ob);
1357 }
1358 return NULL;
1359 }
1360 // This transfers the ownership to the tokenizer
1361 tok->filename = filename_ob;
1362 Py_INCREF(filename_ob);
1363
1364 // We need to clear up from here on
1365 mod_ty result = NULL;
1366
Pablo Galindo2b74c832020-04-27 18:02:07 +01001367 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001368 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1369 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001370 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1371 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001372 if (p == NULL) {
1373 goto error;
1374 }
1375
1376 result = _PyPegen_run_parser(p);
1377 _PyPegen_Parser_Free(p);
1378
1379error:
1380 PyTokenizer_Free(tok);
1381 return result;
1382}
1383
Pablo Galindoa5634c42020-09-16 19:42:00 +01001384asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001385_PyPegen_interactive_exit(Parser *p)
1386{
1387 if (p->errcode) {
1388 *(p->errcode) = E_EOF;
1389 }
1390 return NULL;
1391}
1392
1393/* Creates a single-element asdl_seq* that contains a */
1394asdl_seq *
1395_PyPegen_singleton_seq(Parser *p, void *a)
1396{
1397 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001398 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001399 if (!seq) {
1400 return NULL;
1401 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001402 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001403 return seq;
1404}
1405
1406/* Creates a copy of seq and prepends a to it */
1407asdl_seq *
1408_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1409{
1410 assert(a != NULL);
1411 if (!seq) {
1412 return _PyPegen_singleton_seq(p, a);
1413 }
1414
Pablo Galindoa5634c42020-09-16 19:42:00 +01001415 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001416 if (!new_seq) {
1417 return NULL;
1418 }
1419
Pablo Galindoa5634c42020-09-16 19:42:00 +01001420 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001421 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001422 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001423 }
1424 return new_seq;
1425}
1426
Guido van Rossumc001c092020-04-30 12:12:19 -07001427/* Creates a copy of seq and appends a to it */
1428asdl_seq *
1429_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1430{
1431 assert(a != NULL);
1432 if (!seq) {
1433 return _PyPegen_singleton_seq(p, a);
1434 }
1435
Pablo Galindoa5634c42020-09-16 19:42:00 +01001436 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07001437 if (!new_seq) {
1438 return NULL;
1439 }
1440
1441 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001442 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001443 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001444 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001445 return new_seq;
1446}
1447
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001448static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001449_get_flattened_seq_size(asdl_seq *seqs)
1450{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001451 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001452 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001453 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001454 size += asdl_seq_LEN(inner_seq);
1455 }
1456 return size;
1457}
1458
1459/* Flattens an asdl_seq* of asdl_seq*s */
1460asdl_seq *
1461_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1462{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001463 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001464 assert(flattened_seq_size > 0);
1465
Pablo Galindoa5634c42020-09-16 19:42:00 +01001466 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001467 if (!flattened_seq) {
1468 return NULL;
1469 }
1470
1471 int flattened_seq_idx = 0;
1472 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001473 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001474 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001475 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001476 }
1477 }
1478 assert(flattened_seq_idx == flattened_seq_size);
1479
1480 return flattened_seq;
1481}
1482
1483/* Creates a new name of the form <first_name>.<second_name> */
1484expr_ty
1485_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1486{
1487 assert(first_name != NULL && second_name != NULL);
1488 PyObject *first_identifier = first_name->v.Name.id;
1489 PyObject *second_identifier = second_name->v.Name.id;
1490
1491 if (PyUnicode_READY(first_identifier) == -1) {
1492 return NULL;
1493 }
1494 if (PyUnicode_READY(second_identifier) == -1) {
1495 return NULL;
1496 }
1497 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1498 if (!first_str) {
1499 return NULL;
1500 }
1501 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1502 if (!second_str) {
1503 return NULL;
1504 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001505 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001506
1507 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1508 if (!str) {
1509 return NULL;
1510 }
1511
1512 char *s = PyBytes_AS_STRING(str);
1513 if (!s) {
1514 return NULL;
1515 }
1516
1517 strcpy(s, first_str);
1518 s += strlen(first_str);
1519 *s++ = '.';
1520 strcpy(s, second_str);
1521 s += strlen(second_str);
1522 *s = '\0';
1523
1524 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1525 Py_DECREF(str);
1526 if (!uni) {
1527 return NULL;
1528 }
1529 PyUnicode_InternInPlace(&uni);
1530 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1531 Py_DECREF(uni);
1532 return NULL;
1533 }
1534
1535 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1536}
1537
1538/* Counts the total number of dots in seq's tokens */
1539int
1540_PyPegen_seq_count_dots(asdl_seq *seq)
1541{
1542 int number_of_dots = 0;
1543 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001544 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001545 switch (current_expr->type) {
1546 case ELLIPSIS:
1547 number_of_dots += 3;
1548 break;
1549 case DOT:
1550 number_of_dots += 1;
1551 break;
1552 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001553 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001554 }
1555 }
1556
1557 return number_of_dots;
1558}
1559
1560/* Creates an alias with '*' as the identifier name */
1561alias_ty
1562_PyPegen_alias_for_star(Parser *p)
1563{
1564 PyObject *str = PyUnicode_InternFromString("*");
1565 if (!str) {
1566 return NULL;
1567 }
1568 if (PyArena_AddPyObject(p->arena, str) < 0) {
1569 Py_DECREF(str);
1570 return NULL;
1571 }
1572 return alias(str, NULL, p->arena);
1573}
1574
1575/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001576asdl_identifier_seq *
1577_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001578{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001579 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001580 assert(len > 0);
1581
Pablo Galindoa5634c42020-09-16 19:42:00 +01001582 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001583 if (!new_seq) {
1584 return NULL;
1585 }
1586 for (Py_ssize_t i = 0; i < len; i++) {
1587 expr_ty e = asdl_seq_GET(seq, i);
1588 asdl_seq_SET(new_seq, i, e->v.Name.id);
1589 }
1590 return new_seq;
1591}
1592
1593/* Constructs a CmpopExprPair */
1594CmpopExprPair *
1595_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1596{
1597 assert(expr != NULL);
1598 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1599 if (!a) {
1600 return NULL;
1601 }
1602 a->cmpop = cmpop;
1603 a->expr = expr;
1604 return a;
1605}
1606
1607asdl_int_seq *
1608_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1609{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001610 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001611 assert(len > 0);
1612
1613 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1614 if (!new_seq) {
1615 return NULL;
1616 }
1617 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001618 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001619 asdl_seq_SET(new_seq, i, pair->cmpop);
1620 }
1621 return new_seq;
1622}
1623
Pablo Galindoa5634c42020-09-16 19:42:00 +01001624asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001625_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1626{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001627 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001628 assert(len > 0);
1629
Pablo Galindoa5634c42020-09-16 19:42:00 +01001630 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001631 if (!new_seq) {
1632 return NULL;
1633 }
1634 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001635 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001636 asdl_seq_SET(new_seq, i, pair->expr);
1637 }
1638 return new_seq;
1639}
1640
1641/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001642static asdl_expr_seq *
1643_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001644{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001645 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001646 if (len == 0) {
1647 return NULL;
1648 }
1649
Pablo Galindoa5634c42020-09-16 19:42:00 +01001650 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001651 if (!new_seq) {
1652 return NULL;
1653 }
1654 for (Py_ssize_t i = 0; i < len; i++) {
1655 expr_ty e = asdl_seq_GET(seq, i);
1656 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1657 }
1658 return new_seq;
1659}
1660
1661static expr_ty
1662_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1663{
1664 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1665}
1666
1667static expr_ty
1668_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1669{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001670 return _Py_Tuple(
1671 _set_seq_context(p, e->v.Tuple.elts, ctx),
1672 ctx,
1673 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001674}
1675
1676static expr_ty
1677_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1678{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001679 return _Py_List(
1680 _set_seq_context(p, e->v.List.elts, ctx),
1681 ctx,
1682 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001683}
1684
1685static expr_ty
1686_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1687{
1688 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1689}
1690
1691static expr_ty
1692_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1693{
1694 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1695}
1696
1697static expr_ty
1698_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1699{
1700 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1701}
1702
1703/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1704expr_ty
1705_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1706{
1707 assert(expr != NULL);
1708
1709 expr_ty new = NULL;
1710 switch (expr->kind) {
1711 case Name_kind:
1712 new = _set_name_context(p, expr, ctx);
1713 break;
1714 case Tuple_kind:
1715 new = _set_tuple_context(p, expr, ctx);
1716 break;
1717 case List_kind:
1718 new = _set_list_context(p, expr, ctx);
1719 break;
1720 case Subscript_kind:
1721 new = _set_subscript_context(p, expr, ctx);
1722 break;
1723 case Attribute_kind:
1724 new = _set_attribute_context(p, expr, ctx);
1725 break;
1726 case Starred_kind:
1727 new = _set_starred_context(p, expr, ctx);
1728 break;
1729 default:
1730 new = expr;
1731 }
1732 return new;
1733}
1734
1735/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1736KeyValuePair *
1737_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1738{
1739 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1740 if (!a) {
1741 return NULL;
1742 }
1743 a->key = key;
1744 a->value = value;
1745 return a;
1746}
1747
1748/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001749asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001750_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1751{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001752 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001753 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001754 if (!new_seq) {
1755 return NULL;
1756 }
1757 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001758 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001759 asdl_seq_SET(new_seq, i, pair->key);
1760 }
1761 return new_seq;
1762}
1763
1764/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001765asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001766_PyPegen_get_values(Parser *p, asdl_seq *seq)
1767{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001768 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001769 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001770 if (!new_seq) {
1771 return NULL;
1772 }
1773 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001774 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001775 asdl_seq_SET(new_seq, i, pair->value);
1776 }
1777 return new_seq;
1778}
1779
1780/* Constructs a NameDefaultPair */
1781NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001782_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001783{
1784 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1785 if (!a) {
1786 return NULL;
1787 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001788 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001789 a->value = value;
1790 return a;
1791}
1792
1793/* Constructs a SlashWithDefault */
1794SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001795_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001796{
1797 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1798 if (!a) {
1799 return NULL;
1800 }
1801 a->plain_names = plain_names;
1802 a->names_with_defaults = names_with_defaults;
1803 return a;
1804}
1805
1806/* Constructs a StarEtc */
1807StarEtc *
1808_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1809{
1810 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1811 if (!a) {
1812 return NULL;
1813 }
1814 a->vararg = vararg;
1815 a->kwonlyargs = kwonlyargs;
1816 a->kwarg = kwarg;
1817 return a;
1818}
1819
1820asdl_seq *
1821_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1822{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001823 Py_ssize_t first_len = asdl_seq_LEN(a);
1824 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001825 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001826 if (!new_seq) {
1827 return NULL;
1828 }
1829
1830 int k = 0;
1831 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001832 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001833 }
1834 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001835 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001836 }
1837
1838 return new_seq;
1839}
1840
Pablo Galindoa5634c42020-09-16 19:42:00 +01001841static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001842_get_names(Parser *p, asdl_seq *names_with_defaults)
1843{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001844 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001845 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001846 if (!seq) {
1847 return NULL;
1848 }
1849 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001850 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001851 asdl_seq_SET(seq, i, pair->arg);
1852 }
1853 return seq;
1854}
1855
Pablo Galindoa5634c42020-09-16 19:42:00 +01001856static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001857_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1858{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001859 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001860 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001861 if (!seq) {
1862 return NULL;
1863 }
1864 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001865 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001866 asdl_seq_SET(seq, i, pair->value);
1867 }
1868 return seq;
1869}
1870
1871/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1872arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001873_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
1874 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001875 asdl_seq *names_with_default, StarEtc *star_etc)
1876{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001877 asdl_arg_seq *posonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001878 if (slash_without_default != NULL) {
1879 posonlyargs = slash_without_default;
1880 }
1881 else if (slash_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001882 asdl_arg_seq *slash_with_default_names =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001883 _get_names(p, slash_with_default->names_with_defaults);
1884 if (!slash_with_default_names) {
1885 return NULL;
1886 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001887 posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1888 p,
1889 (asdl_seq*)slash_with_default->plain_names,
1890 (asdl_seq*)slash_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001891 if (!posonlyargs) {
1892 return NULL;
1893 }
1894 }
1895 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001896 posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001897 if (!posonlyargs) {
1898 return NULL;
1899 }
1900 }
1901
Pablo Galindoa5634c42020-09-16 19:42:00 +01001902 asdl_arg_seq *posargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001903 if (plain_names != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001904 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001905 if (!names_with_default_names) {
1906 return NULL;
1907 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001908 posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1909 p,
1910 (asdl_seq*)plain_names,
1911 (asdl_seq*)names_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001912 if (!posargs) {
1913 return NULL;
1914 }
1915 }
1916 else if (plain_names == NULL && names_with_default != NULL) {
1917 posargs = _get_names(p, names_with_default);
1918 if (!posargs) {
1919 return NULL;
1920 }
1921 }
1922 else if (plain_names != NULL && names_with_default == NULL) {
1923 posargs = plain_names;
1924 }
1925 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001926 posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001927 if (!posargs) {
1928 return NULL;
1929 }
1930 }
1931
Pablo Galindoa5634c42020-09-16 19:42:00 +01001932 asdl_expr_seq *posdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001933 if (slash_with_default != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001934 asdl_expr_seq *slash_with_default_values =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001935 _get_defaults(p, slash_with_default->names_with_defaults);
1936 if (!slash_with_default_values) {
1937 return NULL;
1938 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001939 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001940 if (!names_with_default_values) {
1941 return NULL;
1942 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001943 posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
1944 p,
1945 (asdl_seq*)slash_with_default_values,
1946 (asdl_seq*)names_with_default_values);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001947 if (!posdefaults) {
1948 return NULL;
1949 }
1950 }
1951 else if (slash_with_default == NULL && names_with_default != NULL) {
1952 posdefaults = _get_defaults(p, names_with_default);
1953 if (!posdefaults) {
1954 return NULL;
1955 }
1956 }
1957 else if (slash_with_default != NULL && names_with_default == NULL) {
1958 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1959 if (!posdefaults) {
1960 return NULL;
1961 }
1962 }
1963 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001964 posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001965 if (!posdefaults) {
1966 return NULL;
1967 }
1968 }
1969
1970 arg_ty vararg = NULL;
1971 if (star_etc != NULL && star_etc->vararg != NULL) {
1972 vararg = star_etc->vararg;
1973 }
1974
Pablo Galindoa5634c42020-09-16 19:42:00 +01001975 asdl_arg_seq *kwonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001976 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1977 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1978 if (!kwonlyargs) {
1979 return NULL;
1980 }
1981 }
1982 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001983 kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001984 if (!kwonlyargs) {
1985 return NULL;
1986 }
1987 }
1988
Pablo Galindoa5634c42020-09-16 19:42:00 +01001989 asdl_expr_seq *kwdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001990 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1991 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1992 if (!kwdefaults) {
1993 return NULL;
1994 }
1995 }
1996 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001997 kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001998 if (!kwdefaults) {
1999 return NULL;
2000 }
2001 }
2002
2003 arg_ty kwarg = NULL;
2004 if (star_etc != NULL && star_etc->kwarg != NULL) {
2005 kwarg = star_etc->kwarg;
2006 }
2007
2008 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
2009 posdefaults, p->arena);
2010}
2011
2012/* Constructs an empty arguments_ty object, that gets used when a function accepts no
2013 * arguments. */
2014arguments_ty
2015_PyPegen_empty_arguments(Parser *p)
2016{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002017 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002018 if (!posonlyargs) {
2019 return NULL;
2020 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002021 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002022 if (!posargs) {
2023 return NULL;
2024 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002025 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002026 if (!posdefaults) {
2027 return NULL;
2028 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002029 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002030 if (!kwonlyargs) {
2031 return NULL;
2032 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002033 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002034 if (!kwdefaults) {
2035 return NULL;
2036 }
2037
Batuhan Taskaya02a16032020-10-10 20:14:59 +03002038 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, posdefaults,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002039 p->arena);
2040}
2041
2042/* Encapsulates the value of an operator_ty into an AugOperator struct */
2043AugOperator *
2044_PyPegen_augoperator(Parser *p, operator_ty kind)
2045{
2046 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
2047 if (!a) {
2048 return NULL;
2049 }
2050 a->kind = kind;
2051 return a;
2052}
2053
2054/* Construct a FunctionDef equivalent to function_def, but with decorators */
2055stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002056_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002057{
2058 assert(function_def != NULL);
2059 if (function_def->kind == AsyncFunctionDef_kind) {
2060 return _Py_AsyncFunctionDef(
2061 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2062 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2063 function_def->v.FunctionDef.type_comment, function_def->lineno,
2064 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2065 p->arena);
2066 }
2067
2068 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2069 function_def->v.FunctionDef.body, decorators,
2070 function_def->v.FunctionDef.returns,
2071 function_def->v.FunctionDef.type_comment, function_def->lineno,
2072 function_def->col_offset, function_def->end_lineno,
2073 function_def->end_col_offset, p->arena);
2074}
2075
2076/* Construct a ClassDef equivalent to class_def, but with decorators */
2077stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002078_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002079{
2080 assert(class_def != NULL);
2081 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2082 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2083 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2084 class_def->end_col_offset, p->arena);
2085}
2086
2087/* Construct a KeywordOrStarred */
2088KeywordOrStarred *
2089_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2090{
2091 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
2092 if (!a) {
2093 return NULL;
2094 }
2095 a->element = element;
2096 a->is_keyword = is_keyword;
2097 return a;
2098}
2099
2100/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2101static int
2102_seq_number_of_starred_exprs(asdl_seq *seq)
2103{
2104 int n = 0;
2105 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002106 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002107 if (!k->is_keyword) {
2108 n++;
2109 }
2110 }
2111 return n;
2112}
2113
2114/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002115asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002116_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2117{
2118 int new_len = _seq_number_of_starred_exprs(kwargs);
2119 if (new_len == 0) {
2120 return NULL;
2121 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002122 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002123 if (!new_seq) {
2124 return NULL;
2125 }
2126
2127 int idx = 0;
2128 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002129 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002130 if (!k->is_keyword) {
2131 asdl_seq_SET(new_seq, idx++, k->element);
2132 }
2133 }
2134 return new_seq;
2135}
2136
2137/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002138asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002139_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2140{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002141 Py_ssize_t len = asdl_seq_LEN(kwargs);
2142 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002143 if (new_len == 0) {
2144 return NULL;
2145 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002146 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002147 if (!new_seq) {
2148 return NULL;
2149 }
2150
2151 int idx = 0;
2152 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002153 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002154 if (k->is_keyword) {
2155 asdl_seq_SET(new_seq, idx++, k->element);
2156 }
2157 }
2158 return new_seq;
2159}
2160
2161expr_ty
2162_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2163{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002164 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002165 assert(len > 0);
2166
Pablo Galindoa5634c42020-09-16 19:42:00 +01002167 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2168 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002169
2170 int bytesmode = 0;
2171 PyObject *bytes_str = NULL;
2172
2173 FstringParser state;
2174 _PyPegen_FstringParser_Init(&state);
2175
2176 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002177 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002178
2179 int this_bytesmode;
2180 int this_rawmode;
2181 PyObject *s;
2182 const char *fstr;
2183 Py_ssize_t fstrlen = -1;
2184
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002185 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002186 goto error;
2187 }
2188
2189 /* Check that we are not mixing bytes with unicode. */
2190 if (i != 0 && bytesmode != this_bytesmode) {
2191 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2192 Py_XDECREF(s);
2193 goto error;
2194 }
2195 bytesmode = this_bytesmode;
2196
2197 if (fstr != NULL) {
2198 assert(s == NULL && !bytesmode);
2199
2200 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2201 this_rawmode, 0, first, t, last);
2202 if (result < 0) {
2203 goto error;
2204 }
2205 }
2206 else {
2207 /* String or byte string. */
2208 assert(s != NULL && fstr == NULL);
2209 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2210
2211 if (bytesmode) {
2212 if (i == 0) {
2213 bytes_str = s;
2214 }
2215 else {
2216 PyBytes_ConcatAndDel(&bytes_str, s);
2217 if (!bytes_str) {
2218 goto error;
2219 }
2220 }
2221 }
2222 else {
2223 /* This is a regular string. Concatenate it. */
2224 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2225 goto error;
2226 }
2227 }
2228 }
2229 }
2230
2231 if (bytesmode) {
2232 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2233 goto error;
2234 }
2235 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2236 last->end_col_offset, p->arena);
2237 }
2238
2239 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2240
2241error:
2242 Py_XDECREF(bytes_str);
2243 _PyPegen_FstringParser_Dealloc(&state);
2244 if (PyErr_Occurred()) {
2245 raise_decode_error(p);
2246 }
2247 return NULL;
2248}
Guido van Rossumc001c092020-04-30 12:12:19 -07002249
2250mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002251_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2252 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002253 Py_ssize_t num = p->type_ignore_comments.num_items;
2254 if (num > 0) {
2255 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002256 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002257 if (type_ignores == NULL) {
2258 return NULL;
2259 }
2260 for (int i = 0; i < num; i++) {
2261 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2262 if (tag == NULL) {
2263 return NULL;
2264 }
2265 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2266 if (ti == NULL) {
2267 return NULL;
2268 }
2269 asdl_seq_SET(type_ignores, i, ti);
2270 }
2271 }
2272 return Module(a, type_ignores, p->arena);
2273}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002274
2275// Error reporting helpers
2276
2277expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002278_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002279{
2280 if (e == NULL) {
2281 return NULL;
2282 }
2283
2284#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2285 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2286 for (Py_ssize_t i = 0; i < len; i++) {\
2287 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002288 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002289 if (child != NULL) {\
2290 return child;\
2291 }\
2292 }\
2293 } while (0)
2294
2295 // We only need to visit List and Tuple nodes recursively as those
2296 // are the only ones that can contain valid names in targets when
2297 // they are parsed as expressions. Any other kind of expression
2298 // that is a container (like Sets or Dicts) is directly invalid and
2299 // we don't need to visit it recursively.
2300
2301 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002302 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002303 VISIT_CONTAINER(e, List);
2304 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002305 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002306 VISIT_CONTAINER(e, Tuple);
2307 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002308 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002309 if (targets_type == DEL_TARGETS) {
2310 return e;
2311 }
2312 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2313 case Compare_kind:
2314 // This is needed, because the `a in b` in `for a in b` gets parsed
2315 // as a comparison, and so we need to search the left side of the comparison
2316 // for invalid targets.
2317 if (targets_type == FOR_TARGETS) {
2318 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2319 if (cmpop == In) {
2320 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2321 }
2322 return NULL;
2323 }
2324 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002325 case Name_kind:
2326 case Subscript_kind:
2327 case Attribute_kind:
2328 return NULL;
2329 default:
2330 return e;
2331 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002332}
2333
2334void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2335 int kwarg_unpacking = 0;
2336 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2337 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2338 if (!keyword->arg) {
2339 kwarg_unpacking = 1;
2340 }
2341 }
2342
2343 const char *msg = NULL;
2344 if (kwarg_unpacking) {
2345 msg = "positional argument follows keyword argument unpacking";
2346 } else {
2347 msg = "positional argument follows keyword argument";
2348 }
2349
2350 return RAISE_SYNTAX_ERROR(msg);
2351}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002352
2353void *
2354_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2355{
2356 /* The rule that calls this function is 'args for_if_clauses'.
2357 For the input f(L, x for x in y), L and x are in args and
2358 the for is parsed as a for_if_clause. We have to check if
2359 len <= 1, so that input like dict((a, b) for a, b in x)
2360 gets successfully parsed and then we pass the last
2361 argument (x in the above example) as the location of the
2362 error */
2363 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2364 if (len <= 1) {
2365 return NULL;
2366 }
2367
2368 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2369 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2370 "Generator expression must be parenthesized"
2371 );
2372}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002373
2374
Pablo Galindoa5634c42020-09-16 19:42:00 +01002375expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002376 int lineno, int col_offset, int end_lineno,
2377 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002378 Py_ssize_t args_len = asdl_seq_LEN(a);
2379 Py_ssize_t total_len = args_len;
2380
2381 if (b == NULL) {
Pablo Galindo315a61f2020-09-03 15:29:32 +01002382 return _Py_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2383 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002384
2385 }
2386
Pablo Galindoa5634c42020-09-16 19:42:00 +01002387 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2388 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002389
2390 if (starreds) {
2391 total_len += asdl_seq_LEN(starreds);
2392 }
2393
Pablo Galindoa5634c42020-09-16 19:42:00 +01002394 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002395
2396 Py_ssize_t i = 0;
2397 for (i = 0; i < args_len; i++) {
2398 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2399 }
2400 for (; i < total_len; i++) {
2401 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2402 }
2403
Pablo Galindo315a61f2020-09-03 15:29:32 +01002404 return _Py_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2405 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002406}