blob: 24aa3af336c34747b0d4aea1895bf3dbc9474aac [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 Galindo51c58962020-06-16 16:49:43 +0100150 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{
Pablo Galindo9f495902020-06-08 02:57:00 +0100163 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 Galindofb61c422020-06-15 14:23:43 +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
Pablo Galindod6d63712021-01-19 23:59:33 +0000269static inline void
270raise_unclosed_parentheses_error(Parser *p) {
271 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
272 int error_col = p->tok->parencolstack[p->tok->level-1];
273 RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError,
274 error_lineno, error_col,
275 "'%c' was never closed",
276 p->tok->parenstack[p->tok->level-1]);
277}
278
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100279static void
280raise_tokenizer_init_error(PyObject *filename)
281{
282 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
283 || PyErr_ExceptionMatches(PyExc_ValueError)
284 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
285 return;
286 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300287 PyObject *errstr = NULL;
288 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100289 PyObject *type;
290 PyObject *value;
291 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100292 PyErr_Fetch(&type, &value, &tback);
293 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300294 if (!errstr) {
295 goto error;
296 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100297
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300298 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100299 if (!tmp) {
300 goto error;
301 }
302
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300303 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100304 Py_DECREF(tmp);
305 if (!value) {
306 goto error;
307 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300308 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100309
310error:
311 Py_XDECREF(type);
312 Py_XDECREF(value);
313 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300314 Py_XDECREF(errstr);
315 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100316}
317
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100318static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100319tokenizer_error(Parser *p)
320{
321 if (PyErr_Occurred()) {
322 return -1;
323 }
324
325 const char *msg = NULL;
326 PyObject* errtype = PyExc_SyntaxError;
327 switch (p->tok->done) {
328 case E_TOKEN:
329 msg = "invalid token";
330 break;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300331 case E_EOF:
Pablo Galindod6d63712021-01-19 23:59:33 +0000332 if (p->tok->level) {
333 raise_unclosed_parentheses_error(p);
334 } else {
335 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
336 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300337 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100338 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300339 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
340 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100341 case E_INTR:
342 if (!PyErr_Occurred()) {
343 PyErr_SetNone(PyExc_KeyboardInterrupt);
344 }
345 return -1;
346 case E_NOMEM:
347 PyErr_NoMemory();
348 return -1;
349 case E_TABSPACE:
350 errtype = PyExc_TabError;
351 msg = "inconsistent use of tabs and spaces in indentation";
352 break;
353 case E_TOODEEP:
354 errtype = PyExc_IndentationError;
355 msg = "too many levels of indentation";
356 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100357 case E_LINECONT:
358 msg = "unexpected character after line continuation character";
359 break;
360 default:
361 msg = "unknown parsing error";
362 }
363
364 PyErr_Format(errtype, msg);
365 // There is no reliable column information for this error
366 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
367
368 return -1;
369}
370
371void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300372_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
373{
374 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100375 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300376 if (t->col_offset == -1) {
377 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
378 intptr_t, int);
379 } else {
380 col_offset = t->col_offset + 1;
381 }
382
383 va_list va;
384 va_start(va, errmsg);
385 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
386 col_offset, errmsg, va);
387 va_end(va);
388
389 return NULL;
390}
391
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200392static PyObject *
393get_error_line(Parser *p, Py_ssize_t lineno)
394{
395 /* If p->tok->fp == NULL, then we're parsing from a string, which means that
396 the whole source is stored in p->tok->str. If not, then we're parsing
397 from the REPL, so the source lines of the current (multi-line) statement
398 are stored in p->tok->stdin_content */
399 assert(p->tok->fp == NULL || p->tok->fp == stdin);
400
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100401 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
402
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200403 for (int i = 0; i < lineno - 1; i++) {
404 cur_line = strchr(cur_line, '\n') + 1;
405 }
406
407 char *next_newline;
408 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
409 next_newline = cur_line + strlen(cur_line);
410 }
411 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
412}
413
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300414void *
415_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100416 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300417 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100418{
419 PyObject *value = NULL;
420 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300421 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100422 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300423 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100424
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300425 if (p->start_rule == Py_fstring_input) {
426 const char *fstring_msg = "f-string: ";
427 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
428
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300429 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300430 if (!new_errmsg) {
431 return (void *) PyErr_NoMemory();
432 }
433
434 // Copy both strings into new buffer
435 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
436 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
437 new_errmsg[len] = 0;
438 errmsg = new_errmsg;
439 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100440 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100441 if (!errstr) {
442 goto error;
443 }
444
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100445 if (p->tok->fp_interactive) {
446 error_line = get_error_line(p, lineno);
447 }
448 else if (p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300449 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100450 }
451
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300452 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200453 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
454 then we need to find the error line from some other source, because
455 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
456 failed or we're parsing from a string or the REPL. There's a third edge case where
457 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
458 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
459 does not physically exist */
460 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
461
Pablo Galindo40901512021-01-31 22:48:23 +0000462 if (p->tok->lineno <= lineno) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200463 Py_ssize_t size = p->tok->inp - p->tok->buf;
464 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
465 }
466 else {
467 error_line = get_error_line(p, lineno);
468 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300469 if (!error_line) {
470 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300471 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100472 }
473
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300474 if (p->start_rule == Py_fstring_input) {
475 col_offset -= p->starting_col_offset;
476 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100477 Py_ssize_t col_number = col_offset;
478
479 if (p->tok->encoding != NULL) {
480 col_number = byte_offset_to_character_offset(error_line, col_offset);
481 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300482
483 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100484 if (!tmp) {
485 goto error;
486 }
487 value = PyTuple_Pack(2, errstr, tmp);
488 Py_DECREF(tmp);
489 if (!value) {
490 goto error;
491 }
492 PyErr_SetObject(errtype, value);
493
494 Py_DECREF(errstr);
495 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300496 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300497 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300498 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100499 return NULL;
500
501error:
502 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300503 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300504 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300505 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300506 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100507 return NULL;
508}
509
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100510#if 0
511static const char *
512token_name(int type)
513{
514 if (0 <= type && type <= N_TOKENS) {
515 return _PyParser_TokenNames[type];
516 }
517 return "<Huh?>";
518}
519#endif
520
521// Here, mark is the start of the node, while p->mark is the end.
522// If node==NULL, they should be the same.
523int
524_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
525{
526 // Insert in front
527 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
528 if (m == NULL) {
529 return -1;
530 }
531 m->type = type;
532 m->node = node;
533 m->mark = p->mark;
534 m->next = p->tokens[mark]->memo;
535 p->tokens[mark]->memo = m;
536 return 0;
537}
538
539// Like _PyPegen_insert_memo(), but updates an existing node if found.
540int
541_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
542{
543 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
544 if (m->type == type) {
545 // Update existing node.
546 m->node = node;
547 m->mark = p->mark;
548 return 0;
549 }
550 }
551 // Insert new node.
552 return _PyPegen_insert_memo(p, mark, type, node);
553}
554
555// Return dummy NAME.
556void *
557_PyPegen_dummy_name(Parser *p, ...)
558{
559 static void *cache = NULL;
560
561 if (cache != NULL) {
562 return cache;
563 }
564
565 PyObject *id = _create_dummy_identifier(p);
566 if (!id) {
567 return NULL;
568 }
569 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
570 return cache;
571}
572
573static int
574_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
575{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300576 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100577 if (name_len >= p->n_keyword_lists ||
578 p->keywords[name_len] == NULL ||
579 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100580 return NAME;
581 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100582 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100583 if (strncmp(k->str, name, name_len) == 0) {
584 return k->type;
585 }
586 }
587 return NAME;
588}
589
Guido van Rossumc001c092020-04-30 12:12:19 -0700590static int
591growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
592 assert(initial_size > 0);
593 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
594 arr->size = initial_size;
595 arr->num_items = 0;
596
597 return arr->items != NULL;
598}
599
600static int
601growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
602 if (arr->num_items >= arr->size) {
603 size_t new_size = arr->size * 2;
604 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
605 if (!new_items_array) {
606 return 0;
607 }
608 arr->items = new_items_array;
609 arr->size = new_size;
610 }
611
612 arr->items[arr->num_items].lineno = lineno;
613 arr->items[arr->num_items].comment = comment; // Take ownership
614 arr->num_items++;
615 return 1;
616}
617
618static void
619growable_comment_array_deallocate(growable_comment_array *arr) {
620 for (unsigned i = 0; i < arr->num_items; i++) {
621 PyMem_Free(arr->items[i].comment);
622 }
623 PyMem_Free(arr->items);
624}
625
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100626int
627_PyPegen_fill_token(Parser *p)
628{
Pablo Galindofb61c422020-06-15 14:23:43 +0100629 const char *start;
630 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100631 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700632
633 // Record and skip '# type: ignore' comments
634 while (type == TYPE_IGNORE) {
635 Py_ssize_t len = end - start;
636 char *tag = PyMem_Malloc(len + 1);
637 if (tag == NULL) {
638 PyErr_NoMemory();
639 return -1;
640 }
641 strncpy(tag, start, len);
642 tag[len] = '\0';
643 // Ownership of tag passes to the growable array
644 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
645 PyErr_NoMemory();
646 return -1;
647 }
648 type = PyTokenizer_Get(p->tok, &start, &end);
649 }
650
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100651 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
652 type = NEWLINE; /* Add an extra newline */
653 p->parsing_started = 0;
654
Pablo Galindob94dbd72020-04-27 18:35:58 +0100655 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100656 p->tok->pendin = -p->tok->indent;
657 p->tok->indent = 0;
658 }
659 }
660 else {
661 p->parsing_started = 1;
662 }
663
664 if (p->fill == p->size) {
665 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300666 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
667 if (new_tokens == NULL) {
668 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100669 return -1;
670 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100671 p->tokens = new_tokens;
672
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100673 for (int i = p->size; i < newsize; i++) {
674 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300675 if (p->tokens[i] == NULL) {
676 p->size = i; // Needed, in order to cleanup correctly after parser fails
677 PyErr_NoMemory();
678 return -1;
679 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100680 memset(p->tokens[i], '\0', sizeof(Token));
681 }
682 p->size = newsize;
683 }
684
685 Token *t = p->tokens[p->fill];
686 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
687 t->bytes = PyBytes_FromStringAndSize(start, end - start);
688 if (t->bytes == NULL) {
689 return -1;
690 }
691 PyArena_AddPyObject(p->arena, t->bytes);
692
693 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
694 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100695 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100696 int col_offset = -1;
697 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100698 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100699 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100700 }
701 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100702 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100703 }
704
705 t->lineno = p->starting_lineno + lineno;
706 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
707 t->end_lineno = p->starting_lineno + end_lineno;
708 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
709
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100710 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300711
712 if (type == ERRORTOKEN) {
713 if (p->tok->done == E_DECODE) {
714 return raise_decode_error(p);
715 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100716 return tokenizer_error(p);
717
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300718 }
719
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100720 return 0;
721}
722
723// Instrumentation to count the effectiveness of memoization.
724// The array counts the number of tokens skipped by memoization,
725// indexed by type.
726
727#define NSTATISTICS 2000
728static long memo_statistics[NSTATISTICS];
729
730void
731_PyPegen_clear_memo_statistics()
732{
733 for (int i = 0; i < NSTATISTICS; i++) {
734 memo_statistics[i] = 0;
735 }
736}
737
738PyObject *
739_PyPegen_get_memo_statistics()
740{
741 PyObject *ret = PyList_New(NSTATISTICS);
742 if (ret == NULL) {
743 return NULL;
744 }
745 for (int i = 0; i < NSTATISTICS; i++) {
746 PyObject *value = PyLong_FromLong(memo_statistics[i]);
747 if (value == NULL) {
748 Py_DECREF(ret);
749 return NULL;
750 }
751 // PyList_SetItem borrows a reference to value.
752 if (PyList_SetItem(ret, i, value) < 0) {
753 Py_DECREF(ret);
754 return NULL;
755 }
756 }
757 return ret;
758}
759
760int // bool
761_PyPegen_is_memoized(Parser *p, int type, void *pres)
762{
763 if (p->mark == p->fill) {
764 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300765 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100766 return -1;
767 }
768 }
769
770 Token *t = p->tokens[p->mark];
771
772 for (Memo *m = t->memo; m != NULL; m = m->next) {
773 if (m->type == type) {
774 if (0 <= type && type < NSTATISTICS) {
775 long count = m->mark - p->mark;
776 // A memoized negative result counts for one.
777 if (count <= 0) {
778 count = 1;
779 }
780 memo_statistics[type] += count;
781 }
782 p->mark = m->mark;
783 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100784 return 1;
785 }
786 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100787 return 0;
788}
789
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100790int
791_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
792{
793 int mark = p->mark;
794 void *res = func(p);
795 p->mark = mark;
796 return (res != NULL) == positive;
797}
798
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100799int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100800_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
801{
802 int mark = p->mark;
803 void *res = func(p, arg);
804 p->mark = mark;
805 return (res != NULL) == positive;
806}
807
808int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100809_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
810{
811 int mark = p->mark;
812 void *res = func(p, arg);
813 p->mark = mark;
814 return (res != NULL) == positive;
815}
816
817int
818_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
819{
820 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100821 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100822 p->mark = mark;
823 return (res != NULL) == positive;
824}
825
826Token *
827_PyPegen_expect_token(Parser *p, int type)
828{
829 if (p->mark == p->fill) {
830 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300831 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100832 return NULL;
833 }
834 }
835 Token *t = p->tokens[p->mark];
836 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100837 return NULL;
838 }
839 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100840 return t;
841}
842
Pablo Galindo58fb1562021-02-02 19:54:22 +0000843Token *
844_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
845
846 if (p->error_indicator == 1) {
847 return NULL;
848 }
849
850 if (p->mark == p->fill) {
851 if (_PyPegen_fill_token(p) < 0) {
852 p->error_indicator = 1;
853 return NULL;
854 }
855 }
856 Token *t = p->tokens[p->mark];
857 if (t->type != type) {
858 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
859 return NULL;
860 }
861 p->mark += 1;
862 return t;
863}
864
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700865expr_ty
866_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
867{
868 if (p->mark == p->fill) {
869 if (_PyPegen_fill_token(p) < 0) {
870 p->error_indicator = 1;
871 return NULL;
872 }
873 }
874 Token *t = p->tokens[p->mark];
875 if (t->type != NAME) {
876 return NULL;
877 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300878 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700879 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300880 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700881 return NULL;
882 }
883 if (strcmp(s, keyword) != 0) {
884 return NULL;
885 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300886 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700887}
888
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100889Token *
890_PyPegen_get_last_nonnwhitespace_token(Parser *p)
891{
892 assert(p->mark >= 0);
893 Token *token = NULL;
894 for (int m = p->mark - 1; m >= 0; m--) {
895 token = p->tokens[m];
896 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
897 break;
898 }
899 }
900 return token;
901}
902
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100903expr_ty
904_PyPegen_name_token(Parser *p)
905{
906 Token *t = _PyPegen_expect_token(p, NAME);
907 if (t == NULL) {
908 return NULL;
909 }
910 char* s = PyBytes_AsString(t->bytes);
911 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300912 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100913 return NULL;
914 }
915 PyObject *id = _PyPegen_new_identifier(p, s);
916 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300917 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100918 return NULL;
919 }
920 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
921 p->arena);
922}
923
924void *
925_PyPegen_string_token(Parser *p)
926{
927 return _PyPegen_expect_token(p, STRING);
928}
929
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100930static PyObject *
931parsenumber_raw(const char *s)
932{
933 const char *end;
934 long x;
935 double dx;
936 Py_complex compl;
937 int imflag;
938
939 assert(s != NULL);
940 errno = 0;
941 end = s + strlen(s) - 1;
942 imflag = *end == 'j' || *end == 'J';
943 if (s[0] == '0') {
944 x = (long)PyOS_strtoul(s, (char **)&end, 0);
945 if (x < 0 && errno == 0) {
946 return PyLong_FromString(s, (char **)0, 0);
947 }
948 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100949 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100950 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100951 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100952 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100953 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100954 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100955 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100956 return PyLong_FromLong(x);
957 }
958 /* XXX Huge floats may silently fail */
959 if (imflag) {
960 compl.real = 0.;
961 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100962 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100963 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100964 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100965 return PyComplex_FromCComplex(compl);
966 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100967 dx = PyOS_string_to_double(s, NULL, NULL);
968 if (dx == -1.0 && PyErr_Occurred()) {
969 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100970 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100971 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100972}
973
974static PyObject *
975parsenumber(const char *s)
976{
Pablo Galindofb61c422020-06-15 14:23:43 +0100977 char *dup;
978 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100979 PyObject *res = NULL;
980
981 assert(s != NULL);
982
983 if (strchr(s, '_') == NULL) {
984 return parsenumber_raw(s);
985 }
986 /* Create a duplicate without underscores. */
987 dup = PyMem_Malloc(strlen(s) + 1);
988 if (dup == NULL) {
989 return PyErr_NoMemory();
990 }
991 end = dup;
992 for (; *s; s++) {
993 if (*s != '_') {
994 *end++ = *s;
995 }
996 }
997 *end = '\0';
998 res = parsenumber_raw(dup);
999 PyMem_Free(dup);
1000 return res;
1001}
1002
1003expr_ty
1004_PyPegen_number_token(Parser *p)
1005{
1006 Token *t = _PyPegen_expect_token(p, NUMBER);
1007 if (t == NULL) {
1008 return NULL;
1009 }
1010
1011 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001012 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001013 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001014 return NULL;
1015 }
1016
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001017 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1018 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -07001019 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001020 "in Python 3.6 and greater");
1021 }
1022
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001023 PyObject *c = parsenumber(num_raw);
1024
1025 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001026 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001027 return NULL;
1028 }
1029
1030 if (PyArena_AddPyObject(p->arena, c) < 0) {
1031 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001032 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001033 return NULL;
1034 }
1035
1036 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
1037 p->arena);
1038}
1039
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001040static int // bool
1041newline_in_string(Parser *p, const char *cur)
1042{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001043 for (const char *c = cur; c >= p->tok->buf; c--) {
1044 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001045 return 1;
1046 }
1047 }
1048 return 0;
1049}
1050
1051/* Check that the source for a single input statement really is a single
1052 statement by looking at what is left in the buffer after parsing.
1053 Trailing whitespace and comments are OK. */
1054static int // bool
1055bad_single_statement(Parser *p)
1056{
1057 const char *cur = strchr(p->tok->buf, '\n');
1058
1059 /* Newlines are allowed if preceded by a line continuation character
1060 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001061 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1062 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001063 return 0;
1064 }
1065 char c = *cur;
1066
1067 for (;;) {
1068 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1069 c = *++cur;
1070 }
1071
1072 if (!c) {
1073 return 0;
1074 }
1075
1076 if (c != '#') {
1077 return 1;
1078 }
1079
1080 /* Suck up comment. */
1081 while (c && c != '\n') {
1082 c = *++cur;
1083 }
1084 }
1085}
1086
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001087void
1088_PyPegen_Parser_Free(Parser *p)
1089{
1090 Py_XDECREF(p->normalize);
1091 for (int i = 0; i < p->size; i++) {
1092 PyMem_Free(p->tokens[i]);
1093 }
1094 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001095 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001096 PyMem_Free(p);
1097}
1098
Pablo Galindo2b74c832020-04-27 18:02:07 +01001099static int
1100compute_parser_flags(PyCompilerFlags *flags)
1101{
1102 int parser_flags = 0;
1103 if (!flags) {
1104 return 0;
1105 }
1106 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1107 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1108 }
1109 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1110 parser_flags |= PyPARSE_IGNORE_COOKIE;
1111 }
1112 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1113 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1114 }
1115 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1116 parser_flags |= PyPARSE_TYPE_COMMENTS;
1117 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001118 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001119 parser_flags |= PyPARSE_ASYNC_HACKS;
1120 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001121 return parser_flags;
1122}
1123
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001124Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001125_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001126 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001127{
1128 Parser *p = PyMem_Malloc(sizeof(Parser));
1129 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001130 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001131 }
1132 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001133 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1134 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001135 p->tok = tok;
1136 p->keywords = NULL;
1137 p->n_keyword_lists = -1;
1138 p->tokens = PyMem_Malloc(sizeof(Token *));
1139 if (!p->tokens) {
1140 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001141 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001142 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001143 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001144 if (!p->tokens) {
1145 PyMem_Free(p->tokens);
1146 PyMem_Free(p);
1147 return (Parser *) PyErr_NoMemory();
1148 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001149 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1150 PyMem_Free(p->tokens[0]);
1151 PyMem_Free(p->tokens);
1152 PyMem_Free(p);
1153 return (Parser *) PyErr_NoMemory();
1154 }
1155
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001156 p->mark = 0;
1157 p->fill = 0;
1158 p->size = 1;
1159
1160 p->errcode = errcode;
1161 p->arena = arena;
1162 p->start_rule = start_rule;
1163 p->parsing_started = 0;
1164 p->normalize = NULL;
1165 p->error_indicator = 0;
1166
1167 p->starting_lineno = 0;
1168 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001169 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001170 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001171 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001172 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001173 p->call_invalid_rules = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001174
1175 return p;
1176}
1177
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001178static void
1179reset_parser_state(Parser *p)
1180{
1181 for (int i = 0; i < p->fill; i++) {
1182 p->tokens[i]->memo = NULL;
1183 }
1184 p->mark = 0;
1185 p->call_invalid_rules = 1;
1186}
1187
Pablo Galindod6d63712021-01-19 23:59:33 +00001188static int
1189_PyPegen_check_tokenizer_errors(Parser *p) {
1190 // Tokenize the whole input to see if there are any tokenization
1191 // errors such as mistmatching parentheses. These will get priority
1192 // over generic syntax errors only if the line number of the error is
1193 // before the one that we had for the generic error.
1194
1195 // We don't want to tokenize to the end for interactive input
1196 if (p->tok->prompt != NULL) {
1197 return 0;
1198 }
1199
Pablo Galindod6d63712021-01-19 23:59:33 +00001200 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1201 Py_ssize_t current_err_line = current_token->lineno;
1202
Pablo Galindod6d63712021-01-19 23:59:33 +00001203 for (;;) {
1204 const char *start;
1205 const char *end;
1206 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1207 case ERRORTOKEN:
1208 if (p->tok->level != 0) {
1209 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1210 if (current_err_line > error_lineno) {
1211 raise_unclosed_parentheses_error(p);
1212 return -1;
1213 }
1214 }
1215 break;
1216 case ENDMARKER:
1217 break;
1218 default:
1219 continue;
1220 }
1221 break;
1222 }
1223
Pablo Galindod6d63712021-01-19 23:59:33 +00001224 return 0;
1225}
1226
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001227void *
1228_PyPegen_run_parser(Parser *p)
1229{
1230 void *res = _PyPegen_parse(p);
1231 if (res == NULL) {
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001232 reset_parser_state(p);
1233 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001234 if (PyErr_Occurred()) {
1235 return NULL;
1236 }
1237 if (p->fill == 0) {
1238 RAISE_SYNTAX_ERROR("error at start before reading any input");
1239 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001240 else if (p->tok->done == E_EOF) {
Pablo Galindod6d63712021-01-19 23:59:33 +00001241 if (p->tok->level) {
1242 raise_unclosed_parentheses_error(p);
1243 } else {
1244 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1245 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001246 }
1247 else {
1248 if (p->tokens[p->fill-1]->type == INDENT) {
1249 RAISE_INDENTATION_ERROR("unexpected indent");
1250 }
1251 else if (p->tokens[p->fill-1]->type == DEDENT) {
1252 RAISE_INDENTATION_ERROR("unexpected unindent");
1253 }
1254 else {
1255 RAISE_SYNTAX_ERROR("invalid syntax");
Pablo Galindoc3f167d2021-01-20 19:11:56 +00001256 // _PyPegen_check_tokenizer_errors will override the existing
1257 // generic SyntaxError we just raised if errors are found.
1258 _PyPegen_check_tokenizer_errors(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001259 }
1260 }
1261 return NULL;
1262 }
1263
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001264 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1265 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1266 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1267 }
1268
Victor Stinnere0bf70d2021-03-18 02:46:06 +01001269 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1270#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
Pablo Galindo13322262020-07-27 23:46:59 +01001271 if (p->start_rule == Py_single_input ||
1272 p->start_rule == Py_file_input ||
1273 p->start_rule == Py_eval_input)
1274 {
Victor Stinnereec8e612021-03-18 14:57:49 +01001275 if (!_PyAST_Validate(res)) {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001276 return NULL;
1277 }
Pablo Galindo13322262020-07-27 23:46:59 +01001278 }
1279#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001280 return res;
1281}
1282
1283mod_ty
1284_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1285 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001286 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001287{
1288 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1289 if (tok == NULL) {
1290 if (PyErr_Occurred()) {
1291 raise_tokenizer_init_error(filename_ob);
1292 return NULL;
1293 }
1294 return NULL;
1295 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001296 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1297 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1298 tok->fp_interactive = 1;
1299 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001300 // This transfers the ownership to the tokenizer
1301 tok->filename = filename_ob;
1302 Py_INCREF(filename_ob);
1303
1304 // From here on we need to clean up even if there's an error
1305 mod_ty result = NULL;
1306
Pablo Galindo2b74c832020-04-27 18:02:07 +01001307 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001308 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1309 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001310 if (p == NULL) {
1311 goto error;
1312 }
1313
1314 result = _PyPegen_run_parser(p);
1315 _PyPegen_Parser_Free(p);
1316
1317error:
1318 PyTokenizer_Free(tok);
1319 return result;
1320}
1321
1322mod_ty
1323_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001324 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001325{
1326 FILE *fp = fopen(filename, "rb");
1327 if (fp == NULL) {
1328 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1329 return NULL;
1330 }
1331
1332 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001333 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001334
1335 fclose(fp);
1336 return result;
1337}
1338
1339mod_ty
1340_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001341 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001342{
1343 int exec_input = start_rule == Py_file_input;
1344
1345 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001346 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001347 tok = PyTokenizer_FromUTF8(str, exec_input);
1348 } else {
1349 tok = PyTokenizer_FromString(str, exec_input);
1350 }
1351 if (tok == NULL) {
1352 if (PyErr_Occurred()) {
1353 raise_tokenizer_init_error(filename_ob);
1354 }
1355 return NULL;
1356 }
1357 // This transfers the ownership to the tokenizer
1358 tok->filename = filename_ob;
1359 Py_INCREF(filename_ob);
1360
1361 // We need to clear up from here on
1362 mod_ty result = NULL;
1363
Pablo Galindo2b74c832020-04-27 18:02:07 +01001364 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001365 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1366 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001367 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1368 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001369 if (p == NULL) {
1370 goto error;
1371 }
1372
1373 result = _PyPegen_run_parser(p);
1374 _PyPegen_Parser_Free(p);
1375
1376error:
1377 PyTokenizer_Free(tok);
1378 return result;
1379}
1380
Pablo Galindoa5634c42020-09-16 19:42:00 +01001381asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001382_PyPegen_interactive_exit(Parser *p)
1383{
1384 if (p->errcode) {
1385 *(p->errcode) = E_EOF;
1386 }
1387 return NULL;
1388}
1389
1390/* Creates a single-element asdl_seq* that contains a */
1391asdl_seq *
1392_PyPegen_singleton_seq(Parser *p, void *a)
1393{
1394 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001395 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001396 if (!seq) {
1397 return NULL;
1398 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001399 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001400 return seq;
1401}
1402
1403/* Creates a copy of seq and prepends a to it */
1404asdl_seq *
1405_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1406{
1407 assert(a != NULL);
1408 if (!seq) {
1409 return _PyPegen_singleton_seq(p, a);
1410 }
1411
Pablo Galindoa5634c42020-09-16 19:42:00 +01001412 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 +01001413 if (!new_seq) {
1414 return NULL;
1415 }
1416
Pablo Galindoa5634c42020-09-16 19:42:00 +01001417 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001418 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001419 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001420 }
1421 return new_seq;
1422}
1423
Guido van Rossumc001c092020-04-30 12:12:19 -07001424/* Creates a copy of seq and appends a to it */
1425asdl_seq *
1426_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1427{
1428 assert(a != NULL);
1429 if (!seq) {
1430 return _PyPegen_singleton_seq(p, a);
1431 }
1432
Pablo Galindoa5634c42020-09-16 19:42:00 +01001433 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 -07001434 if (!new_seq) {
1435 return NULL;
1436 }
1437
1438 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001439 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001440 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001441 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001442 return new_seq;
1443}
1444
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001445static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001446_get_flattened_seq_size(asdl_seq *seqs)
1447{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001448 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001449 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001450 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001451 size += asdl_seq_LEN(inner_seq);
1452 }
1453 return size;
1454}
1455
1456/* Flattens an asdl_seq* of asdl_seq*s */
1457asdl_seq *
1458_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1459{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001460 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001461 assert(flattened_seq_size > 0);
1462
Pablo Galindoa5634c42020-09-16 19:42:00 +01001463 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001464 if (!flattened_seq) {
1465 return NULL;
1466 }
1467
1468 int flattened_seq_idx = 0;
1469 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001470 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001471 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001472 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001473 }
1474 }
1475 assert(flattened_seq_idx == flattened_seq_size);
1476
1477 return flattened_seq;
1478}
1479
1480/* Creates a new name of the form <first_name>.<second_name> */
1481expr_ty
1482_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1483{
1484 assert(first_name != NULL && second_name != NULL);
1485 PyObject *first_identifier = first_name->v.Name.id;
1486 PyObject *second_identifier = second_name->v.Name.id;
1487
1488 if (PyUnicode_READY(first_identifier) == -1) {
1489 return NULL;
1490 }
1491 if (PyUnicode_READY(second_identifier) == -1) {
1492 return NULL;
1493 }
1494 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1495 if (!first_str) {
1496 return NULL;
1497 }
1498 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1499 if (!second_str) {
1500 return NULL;
1501 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001502 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001503
1504 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1505 if (!str) {
1506 return NULL;
1507 }
1508
1509 char *s = PyBytes_AS_STRING(str);
1510 if (!s) {
1511 return NULL;
1512 }
1513
1514 strcpy(s, first_str);
1515 s += strlen(first_str);
1516 *s++ = '.';
1517 strcpy(s, second_str);
1518 s += strlen(second_str);
1519 *s = '\0';
1520
1521 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1522 Py_DECREF(str);
1523 if (!uni) {
1524 return NULL;
1525 }
1526 PyUnicode_InternInPlace(&uni);
1527 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1528 Py_DECREF(uni);
1529 return NULL;
1530 }
1531
1532 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1533}
1534
1535/* Counts the total number of dots in seq's tokens */
1536int
1537_PyPegen_seq_count_dots(asdl_seq *seq)
1538{
1539 int number_of_dots = 0;
1540 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001541 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001542 switch (current_expr->type) {
1543 case ELLIPSIS:
1544 number_of_dots += 3;
1545 break;
1546 case DOT:
1547 number_of_dots += 1;
1548 break;
1549 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001550 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001551 }
1552 }
1553
1554 return number_of_dots;
1555}
1556
1557/* Creates an alias with '*' as the identifier name */
1558alias_ty
1559_PyPegen_alias_for_star(Parser *p)
1560{
1561 PyObject *str = PyUnicode_InternFromString("*");
1562 if (!str) {
1563 return NULL;
1564 }
1565 if (PyArena_AddPyObject(p->arena, str) < 0) {
1566 Py_DECREF(str);
1567 return NULL;
1568 }
1569 return alias(str, NULL, p->arena);
1570}
1571
1572/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001573asdl_identifier_seq *
1574_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001575{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001576 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001577 assert(len > 0);
1578
Pablo Galindoa5634c42020-09-16 19:42:00 +01001579 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001580 if (!new_seq) {
1581 return NULL;
1582 }
1583 for (Py_ssize_t i = 0; i < len; i++) {
1584 expr_ty e = asdl_seq_GET(seq, i);
1585 asdl_seq_SET(new_seq, i, e->v.Name.id);
1586 }
1587 return new_seq;
1588}
1589
1590/* Constructs a CmpopExprPair */
1591CmpopExprPair *
1592_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1593{
1594 assert(expr != NULL);
1595 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1596 if (!a) {
1597 return NULL;
1598 }
1599 a->cmpop = cmpop;
1600 a->expr = expr;
1601 return a;
1602}
1603
1604asdl_int_seq *
1605_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1606{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001607 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001608 assert(len > 0);
1609
1610 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1611 if (!new_seq) {
1612 return NULL;
1613 }
1614 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001615 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001616 asdl_seq_SET(new_seq, i, pair->cmpop);
1617 }
1618 return new_seq;
1619}
1620
Pablo Galindoa5634c42020-09-16 19:42:00 +01001621asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001622_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1623{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001624 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001625 assert(len > 0);
1626
Pablo Galindoa5634c42020-09-16 19:42:00 +01001627 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001628 if (!new_seq) {
1629 return NULL;
1630 }
1631 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001632 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001633 asdl_seq_SET(new_seq, i, pair->expr);
1634 }
1635 return new_seq;
1636}
1637
1638/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001639static asdl_expr_seq *
1640_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001641{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001642 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001643 if (len == 0) {
1644 return NULL;
1645 }
1646
Pablo Galindoa5634c42020-09-16 19:42:00 +01001647 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001648 if (!new_seq) {
1649 return NULL;
1650 }
1651 for (Py_ssize_t i = 0; i < len; i++) {
1652 expr_ty e = asdl_seq_GET(seq, i);
1653 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1654 }
1655 return new_seq;
1656}
1657
1658static expr_ty
1659_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1660{
1661 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1662}
1663
1664static expr_ty
1665_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1666{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001667 return _Py_Tuple(
1668 _set_seq_context(p, e->v.Tuple.elts, ctx),
1669 ctx,
1670 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001671}
1672
1673static expr_ty
1674_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1675{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001676 return _Py_List(
1677 _set_seq_context(p, e->v.List.elts, ctx),
1678 ctx,
1679 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001680}
1681
1682static expr_ty
1683_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1684{
1685 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1686}
1687
1688static expr_ty
1689_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1690{
1691 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1692}
1693
1694static expr_ty
1695_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1696{
1697 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1698}
1699
1700/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1701expr_ty
1702_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1703{
1704 assert(expr != NULL);
1705
1706 expr_ty new = NULL;
1707 switch (expr->kind) {
1708 case Name_kind:
1709 new = _set_name_context(p, expr, ctx);
1710 break;
1711 case Tuple_kind:
1712 new = _set_tuple_context(p, expr, ctx);
1713 break;
1714 case List_kind:
1715 new = _set_list_context(p, expr, ctx);
1716 break;
1717 case Subscript_kind:
1718 new = _set_subscript_context(p, expr, ctx);
1719 break;
1720 case Attribute_kind:
1721 new = _set_attribute_context(p, expr, ctx);
1722 break;
1723 case Starred_kind:
1724 new = _set_starred_context(p, expr, ctx);
1725 break;
1726 default:
1727 new = expr;
1728 }
1729 return new;
1730}
1731
1732/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1733KeyValuePair *
1734_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1735{
1736 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1737 if (!a) {
1738 return NULL;
1739 }
1740 a->key = key;
1741 a->value = value;
1742 return a;
1743}
1744
1745/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001746asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001747_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1748{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001749 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001750 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001751 if (!new_seq) {
1752 return NULL;
1753 }
1754 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001755 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001756 asdl_seq_SET(new_seq, i, pair->key);
1757 }
1758 return new_seq;
1759}
1760
1761/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001762asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001763_PyPegen_get_values(Parser *p, asdl_seq *seq)
1764{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001765 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001766 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001767 if (!new_seq) {
1768 return NULL;
1769 }
1770 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001771 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001772 asdl_seq_SET(new_seq, i, pair->value);
1773 }
1774 return new_seq;
1775}
1776
1777/* Constructs a NameDefaultPair */
1778NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001779_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001780{
1781 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1782 if (!a) {
1783 return NULL;
1784 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001785 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001786 a->value = value;
1787 return a;
1788}
1789
1790/* Constructs a SlashWithDefault */
1791SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001792_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001793{
1794 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1795 if (!a) {
1796 return NULL;
1797 }
1798 a->plain_names = plain_names;
1799 a->names_with_defaults = names_with_defaults;
1800 return a;
1801}
1802
1803/* Constructs a StarEtc */
1804StarEtc *
1805_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1806{
1807 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1808 if (!a) {
1809 return NULL;
1810 }
1811 a->vararg = vararg;
1812 a->kwonlyargs = kwonlyargs;
1813 a->kwarg = kwarg;
1814 return a;
1815}
1816
1817asdl_seq *
1818_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1819{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001820 Py_ssize_t first_len = asdl_seq_LEN(a);
1821 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001822 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001823 if (!new_seq) {
1824 return NULL;
1825 }
1826
1827 int k = 0;
1828 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001829 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001830 }
1831 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001832 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001833 }
1834
1835 return new_seq;
1836}
1837
Pablo Galindoa5634c42020-09-16 19:42:00 +01001838static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001839_get_names(Parser *p, asdl_seq *names_with_defaults)
1840{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001841 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001842 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001843 if (!seq) {
1844 return NULL;
1845 }
1846 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001847 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001848 asdl_seq_SET(seq, i, pair->arg);
1849 }
1850 return seq;
1851}
1852
Pablo Galindoa5634c42020-09-16 19:42:00 +01001853static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001854_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1855{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001856 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001857 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001858 if (!seq) {
1859 return NULL;
1860 }
1861 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001862 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001863 asdl_seq_SET(seq, i, pair->value);
1864 }
1865 return seq;
1866}
1867
1868/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1869arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001870_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
1871 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001872 asdl_seq *names_with_default, StarEtc *star_etc)
1873{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001874 asdl_arg_seq *posonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001875 if (slash_without_default != NULL) {
1876 posonlyargs = slash_without_default;
1877 }
1878 else if (slash_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001879 asdl_arg_seq *slash_with_default_names =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001880 _get_names(p, slash_with_default->names_with_defaults);
1881 if (!slash_with_default_names) {
1882 return NULL;
1883 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001884 posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1885 p,
1886 (asdl_seq*)slash_with_default->plain_names,
1887 (asdl_seq*)slash_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001888 if (!posonlyargs) {
1889 return NULL;
1890 }
1891 }
1892 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001893 posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001894 if (!posonlyargs) {
1895 return NULL;
1896 }
1897 }
1898
Pablo Galindoa5634c42020-09-16 19:42:00 +01001899 asdl_arg_seq *posargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001900 if (plain_names != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001901 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001902 if (!names_with_default_names) {
1903 return NULL;
1904 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001905 posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1906 p,
1907 (asdl_seq*)plain_names,
1908 (asdl_seq*)names_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001909 if (!posargs) {
1910 return NULL;
1911 }
1912 }
1913 else if (plain_names == NULL && names_with_default != NULL) {
1914 posargs = _get_names(p, names_with_default);
1915 if (!posargs) {
1916 return NULL;
1917 }
1918 }
1919 else if (plain_names != NULL && names_with_default == NULL) {
1920 posargs = plain_names;
1921 }
1922 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001923 posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001924 if (!posargs) {
1925 return NULL;
1926 }
1927 }
1928
Pablo Galindoa5634c42020-09-16 19:42:00 +01001929 asdl_expr_seq *posdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001930 if (slash_with_default != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001931 asdl_expr_seq *slash_with_default_values =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001932 _get_defaults(p, slash_with_default->names_with_defaults);
1933 if (!slash_with_default_values) {
1934 return NULL;
1935 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001936 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001937 if (!names_with_default_values) {
1938 return NULL;
1939 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001940 posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
1941 p,
1942 (asdl_seq*)slash_with_default_values,
1943 (asdl_seq*)names_with_default_values);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001944 if (!posdefaults) {
1945 return NULL;
1946 }
1947 }
1948 else if (slash_with_default == NULL && names_with_default != NULL) {
1949 posdefaults = _get_defaults(p, names_with_default);
1950 if (!posdefaults) {
1951 return NULL;
1952 }
1953 }
1954 else if (slash_with_default != NULL && names_with_default == NULL) {
1955 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1956 if (!posdefaults) {
1957 return NULL;
1958 }
1959 }
1960 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001961 posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001962 if (!posdefaults) {
1963 return NULL;
1964 }
1965 }
1966
1967 arg_ty vararg = NULL;
1968 if (star_etc != NULL && star_etc->vararg != NULL) {
1969 vararg = star_etc->vararg;
1970 }
1971
Pablo Galindoa5634c42020-09-16 19:42:00 +01001972 asdl_arg_seq *kwonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001973 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1974 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1975 if (!kwonlyargs) {
1976 return NULL;
1977 }
1978 }
1979 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001980 kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001981 if (!kwonlyargs) {
1982 return NULL;
1983 }
1984 }
1985
Pablo Galindoa5634c42020-09-16 19:42:00 +01001986 asdl_expr_seq *kwdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001987 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1988 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1989 if (!kwdefaults) {
1990 return NULL;
1991 }
1992 }
1993 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001994 kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001995 if (!kwdefaults) {
1996 return NULL;
1997 }
1998 }
1999
2000 arg_ty kwarg = NULL;
2001 if (star_etc != NULL && star_etc->kwarg != NULL) {
2002 kwarg = star_etc->kwarg;
2003 }
2004
2005 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
2006 posdefaults, p->arena);
2007}
2008
2009/* Constructs an empty arguments_ty object, that gets used when a function accepts no
2010 * arguments. */
2011arguments_ty
2012_PyPegen_empty_arguments(Parser *p)
2013{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002014 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002015 if (!posonlyargs) {
2016 return NULL;
2017 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002018 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002019 if (!posargs) {
2020 return NULL;
2021 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002022 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002023 if (!posdefaults) {
2024 return NULL;
2025 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002026 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002027 if (!kwonlyargs) {
2028 return NULL;
2029 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002030 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002031 if (!kwdefaults) {
2032 return NULL;
2033 }
2034
Batuhan Taskaya02a16032020-10-10 20:14:59 +03002035 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, posdefaults,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002036 p->arena);
2037}
2038
2039/* Encapsulates the value of an operator_ty into an AugOperator struct */
2040AugOperator *
2041_PyPegen_augoperator(Parser *p, operator_ty kind)
2042{
2043 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
2044 if (!a) {
2045 return NULL;
2046 }
2047 a->kind = kind;
2048 return a;
2049}
2050
2051/* Construct a FunctionDef equivalent to function_def, but with decorators */
2052stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002053_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002054{
2055 assert(function_def != NULL);
2056 if (function_def->kind == AsyncFunctionDef_kind) {
2057 return _Py_AsyncFunctionDef(
2058 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2059 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2060 function_def->v.FunctionDef.type_comment, function_def->lineno,
2061 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2062 p->arena);
2063 }
2064
2065 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2066 function_def->v.FunctionDef.body, decorators,
2067 function_def->v.FunctionDef.returns,
2068 function_def->v.FunctionDef.type_comment, function_def->lineno,
2069 function_def->col_offset, function_def->end_lineno,
2070 function_def->end_col_offset, p->arena);
2071}
2072
2073/* Construct a ClassDef equivalent to class_def, but with decorators */
2074stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002075_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002076{
2077 assert(class_def != NULL);
2078 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2079 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2080 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2081 class_def->end_col_offset, p->arena);
2082}
2083
2084/* Construct a KeywordOrStarred */
2085KeywordOrStarred *
2086_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2087{
2088 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
2089 if (!a) {
2090 return NULL;
2091 }
2092 a->element = element;
2093 a->is_keyword = is_keyword;
2094 return a;
2095}
2096
2097/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2098static int
2099_seq_number_of_starred_exprs(asdl_seq *seq)
2100{
2101 int n = 0;
2102 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002103 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002104 if (!k->is_keyword) {
2105 n++;
2106 }
2107 }
2108 return n;
2109}
2110
2111/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002112asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002113_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2114{
2115 int new_len = _seq_number_of_starred_exprs(kwargs);
2116 if (new_len == 0) {
2117 return NULL;
2118 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002119 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002120 if (!new_seq) {
2121 return NULL;
2122 }
2123
2124 int idx = 0;
2125 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002126 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002127 if (!k->is_keyword) {
2128 asdl_seq_SET(new_seq, idx++, k->element);
2129 }
2130 }
2131 return new_seq;
2132}
2133
2134/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002135asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002136_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2137{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002138 Py_ssize_t len = asdl_seq_LEN(kwargs);
2139 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002140 if (new_len == 0) {
2141 return NULL;
2142 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002143 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002144 if (!new_seq) {
2145 return NULL;
2146 }
2147
2148 int idx = 0;
2149 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002150 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002151 if (k->is_keyword) {
2152 asdl_seq_SET(new_seq, idx++, k->element);
2153 }
2154 }
2155 return new_seq;
2156}
2157
2158expr_ty
2159_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2160{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002161 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002162 assert(len > 0);
2163
Pablo Galindoa5634c42020-09-16 19:42:00 +01002164 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2165 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002166
2167 int bytesmode = 0;
2168 PyObject *bytes_str = NULL;
2169
2170 FstringParser state;
2171 _PyPegen_FstringParser_Init(&state);
2172
2173 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002174 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002175
2176 int this_bytesmode;
2177 int this_rawmode;
2178 PyObject *s;
2179 const char *fstr;
2180 Py_ssize_t fstrlen = -1;
2181
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002182 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002183 goto error;
2184 }
2185
2186 /* Check that we are not mixing bytes with unicode. */
2187 if (i != 0 && bytesmode != this_bytesmode) {
2188 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2189 Py_XDECREF(s);
2190 goto error;
2191 }
2192 bytesmode = this_bytesmode;
2193
2194 if (fstr != NULL) {
2195 assert(s == NULL && !bytesmode);
2196
2197 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2198 this_rawmode, 0, first, t, last);
2199 if (result < 0) {
2200 goto error;
2201 }
2202 }
2203 else {
2204 /* String or byte string. */
2205 assert(s != NULL && fstr == NULL);
2206 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2207
2208 if (bytesmode) {
2209 if (i == 0) {
2210 bytes_str = s;
2211 }
2212 else {
2213 PyBytes_ConcatAndDel(&bytes_str, s);
2214 if (!bytes_str) {
2215 goto error;
2216 }
2217 }
2218 }
2219 else {
2220 /* This is a regular string. Concatenate it. */
2221 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2222 goto error;
2223 }
2224 }
2225 }
2226 }
2227
2228 if (bytesmode) {
2229 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2230 goto error;
2231 }
2232 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2233 last->end_col_offset, p->arena);
2234 }
2235
2236 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2237
2238error:
2239 Py_XDECREF(bytes_str);
2240 _PyPegen_FstringParser_Dealloc(&state);
2241 if (PyErr_Occurred()) {
2242 raise_decode_error(p);
2243 }
2244 return NULL;
2245}
Guido van Rossumc001c092020-04-30 12:12:19 -07002246
2247mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002248_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2249 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002250 Py_ssize_t num = p->type_ignore_comments.num_items;
2251 if (num > 0) {
2252 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002253 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002254 if (type_ignores == NULL) {
2255 return NULL;
2256 }
2257 for (int i = 0; i < num; i++) {
2258 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2259 if (tag == NULL) {
2260 return NULL;
2261 }
2262 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2263 if (ti == NULL) {
2264 return NULL;
2265 }
2266 asdl_seq_SET(type_ignores, i, ti);
2267 }
2268 }
2269 return Module(a, type_ignores, p->arena);
2270}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002271
2272// Error reporting helpers
2273
2274expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002275_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002276{
2277 if (e == NULL) {
2278 return NULL;
2279 }
2280
2281#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2282 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2283 for (Py_ssize_t i = 0; i < len; i++) {\
2284 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002285 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002286 if (child != NULL) {\
2287 return child;\
2288 }\
2289 }\
2290 } while (0)
2291
2292 // We only need to visit List and Tuple nodes recursively as those
2293 // are the only ones that can contain valid names in targets when
2294 // they are parsed as expressions. Any other kind of expression
2295 // that is a container (like Sets or Dicts) is directly invalid and
2296 // we don't need to visit it recursively.
2297
2298 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002299 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002300 VISIT_CONTAINER(e, List);
2301 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002302 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002303 VISIT_CONTAINER(e, Tuple);
2304 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002305 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002306 if (targets_type == DEL_TARGETS) {
2307 return e;
2308 }
2309 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2310 case Compare_kind:
2311 // This is needed, because the `a in b` in `for a in b` gets parsed
2312 // as a comparison, and so we need to search the left side of the comparison
2313 // for invalid targets.
2314 if (targets_type == FOR_TARGETS) {
2315 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2316 if (cmpop == In) {
2317 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2318 }
2319 return NULL;
2320 }
2321 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002322 case Name_kind:
2323 case Subscript_kind:
2324 case Attribute_kind:
2325 return NULL;
2326 default:
2327 return e;
2328 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002329}
2330
2331void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2332 int kwarg_unpacking = 0;
2333 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2334 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2335 if (!keyword->arg) {
2336 kwarg_unpacking = 1;
2337 }
2338 }
2339
2340 const char *msg = NULL;
2341 if (kwarg_unpacking) {
2342 msg = "positional argument follows keyword argument unpacking";
2343 } else {
2344 msg = "positional argument follows keyword argument";
2345 }
2346
2347 return RAISE_SYNTAX_ERROR(msg);
2348}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002349
2350void *
2351_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2352{
2353 /* The rule that calls this function is 'args for_if_clauses'.
2354 For the input f(L, x for x in y), L and x are in args and
2355 the for is parsed as a for_if_clause. We have to check if
2356 len <= 1, so that input like dict((a, b) for a, b in x)
2357 gets successfully parsed and then we pass the last
2358 argument (x in the above example) as the location of the
2359 error */
2360 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2361 if (len <= 1) {
2362 return NULL;
2363 }
2364
2365 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2366 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2367 "Generator expression must be parenthesized"
2368 );
2369}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002370
2371
Pablo Galindoa5634c42020-09-16 19:42:00 +01002372expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002373 int lineno, int col_offset, int end_lineno,
2374 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002375 Py_ssize_t args_len = asdl_seq_LEN(a);
2376 Py_ssize_t total_len = args_len;
2377
2378 if (b == NULL) {
Pablo Galindo315a61f2020-09-03 15:29:32 +01002379 return _Py_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2380 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002381
2382 }
2383
Pablo Galindoa5634c42020-09-16 19:42:00 +01002384 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2385 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002386
2387 if (starreds) {
2388 total_len += asdl_seq_LEN(starreds);
2389 }
2390
Pablo Galindoa5634c42020-09-16 19:42:00 +01002391 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002392
2393 Py_ssize_t i = 0;
2394 for (i = 0; i < args_len; i++) {
2395 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2396 }
2397 for (; i < total_len; i++) {
2398 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2399 }
2400
Pablo Galindo315a61f2020-09-03 15:29:32 +01002401 return _Py_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2402 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002403}