blob: e6518198eca0758ce20cfaf42a7b85afe2d71eb6 [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002#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 Galindoc5fc1562020-04-22 23:29:27 +01008
Guido van Rossumc001c092020-04-30 12:12:19 -07009PyObject *
10_PyPegen_new_type_comment(Parser *p, char *s)
11{
12 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
13 if (res == NULL) {
14 return NULL;
15 }
Victor Stinner8370e072021-03-24 02:23:01 +010016 if (_PyArena_AddPyObject(p->arena, res) < 0) {
Guido van Rossumc001c092020-04-30 12:12:19 -070017 Py_DECREF(res);
18 return NULL;
19 }
20 return res;
21}
22
23arg_ty
24_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
25{
26 if (tc == NULL) {
27 return a;
28 }
29 char *bytes = PyBytes_AsString(tc->bytes);
30 if (bytes == NULL) {
31 return NULL;
32 }
33 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
34 if (tco == NULL) {
35 return NULL;
36 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +020037 return _PyAST_arg(a->arg, a->annotation, tco,
38 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
39 p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -070040}
41
Pablo Galindoc5fc1562020-04-22 23:29:27 +010042static int
43init_normalization(Parser *p)
44{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030045 if (p->normalize) {
46 return 1;
47 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010048 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
49 if (!m)
50 {
51 return 0;
52 }
53 p->normalize = PyObject_GetAttrString(m, "normalize");
54 Py_DECREF(m);
55 if (!p->normalize)
56 {
57 return 0;
58 }
59 return 1;
60}
61
Pablo Galindo2b74c832020-04-27 18:02:07 +010062/* Checks if the NOTEQUAL token is valid given the current parser flags
630 indicates success and nonzero indicates failure (an exception may be set) */
64int
Pablo Galindo06f8c332020-10-30 23:48:42 +000065_PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010066 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindofb61c422020-06-15 14:23:43 +010070 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010071 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
Pablo Galindofb61c422020-06-15 14:23:43 +010073 }
74 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010075 return strcmp(tok_str, "!=");
76 }
77 return 0;
78}
79
Pablo Galindoc5fc1562020-04-22 23:29:27 +010080PyObject *
81_PyPegen_new_identifier(Parser *p, char *n)
82{
83 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
84 if (!id) {
85 goto error;
86 }
87 /* PyUnicode_DecodeUTF8 should always return a ready string. */
88 assert(PyUnicode_IS_READY(id));
89 /* Check whether there are non-ASCII characters in the
90 identifier; if so, normalize to NFKC. */
91 if (!PyUnicode_IS_ASCII(id))
92 {
93 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030094 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010095 {
96 Py_DECREF(id);
97 goto error;
98 }
99 PyObject *form = PyUnicode_InternFromString("NFKC");
100 if (form == NULL)
101 {
102 Py_DECREF(id);
103 goto error;
104 }
105 PyObject *args[2] = {form, id};
106 id2 = _PyObject_FastCall(p->normalize, args, 2);
107 Py_DECREF(id);
108 Py_DECREF(form);
109 if (!id2) {
110 goto error;
111 }
112 if (!PyUnicode_Check(id2))
113 {
114 PyErr_Format(PyExc_TypeError,
115 "unicodedata.normalize() must return a string, not "
116 "%.200s",
117 _PyType_Name(Py_TYPE(id2)));
118 Py_DECREF(id2);
119 goto error;
120 }
121 id = id2;
122 }
123 PyUnicode_InternInPlace(&id);
Victor Stinner8370e072021-03-24 02:23:01 +0100124 if (_PyArena_AddPyObject(p->arena, id) < 0)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100125 {
126 Py_DECREF(id);
127 goto error;
128 }
129 return id;
130
131error:
132 p->error_indicator = 1;
133 return NULL;
134}
135
136static PyObject *
137_create_dummy_identifier(Parser *p)
138{
139 return _PyPegen_new_identifier(p, "");
140}
141
142static inline Py_ssize_t
Pablo Galindo51c58962020-06-16 16:49:43 +0100143byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100144{
145 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300146 if (!str) {
147 return 0;
148 }
Pablo Galindo123ff262021-03-22 16:24:39 +0000149 Py_ssize_t len = strlen(str);
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100150 if (col_offset > len + 1) {
151 col_offset = len + 1;
Pablo Galindo123ff262021-03-22 16:24:39 +0000152 }
153 assert(col_offset >= 0);
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300154 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100155 if (!text) {
156 return 0;
157 }
158 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
159 Py_DECREF(text);
160 return size;
161}
162
163const char *
164_PyPegen_get_expr_name(expr_ty e)
165{
Pablo Galindo9f495902020-06-08 02:57:00 +0100166 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100167 switch (e->kind) {
168 case Attribute_kind:
169 return "attribute";
170 case Subscript_kind:
171 return "subscript";
172 case Starred_kind:
173 return "starred";
174 case Name_kind:
175 return "name";
176 case List_kind:
177 return "list";
178 case Tuple_kind:
179 return "tuple";
180 case Lambda_kind:
181 return "lambda";
182 case Call_kind:
183 return "function call";
184 case BoolOp_kind:
185 case BinOp_kind:
186 case UnaryOp_kind:
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100187 return "expression";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100188 case GeneratorExp_kind:
189 return "generator expression";
190 case Yield_kind:
191 case YieldFrom_kind:
192 return "yield expression";
193 case Await_kind:
194 return "await expression";
195 case ListComp_kind:
196 return "list comprehension";
197 case SetComp_kind:
198 return "set comprehension";
199 case DictComp_kind:
200 return "dict comprehension";
201 case Dict_kind:
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100202 return "dict literal";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100203 case Set_kind:
204 return "set display";
205 case JoinedStr_kind:
206 case FormattedValue_kind:
207 return "f-string expression";
208 case Constant_kind: {
209 PyObject *value = e->v.Constant.value;
210 if (value == Py_None) {
211 return "None";
212 }
213 if (value == Py_False) {
214 return "False";
215 }
216 if (value == Py_True) {
217 return "True";
218 }
219 if (value == Py_Ellipsis) {
Pablo Galindo3283bf42021-06-03 22:22:28 +0100220 return "ellipsis";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100221 }
222 return "literal";
223 }
224 case Compare_kind:
225 return "comparison";
226 case IfExp_kind:
227 return "conditional expression";
228 case NamedExpr_kind:
229 return "named expression";
230 default:
231 PyErr_Format(PyExc_SystemError,
232 "unexpected expression in assignment %d (line %d)",
233 e->kind, e->lineno);
234 return NULL;
235 }
236}
237
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300238static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100239raise_decode_error(Parser *p)
240{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300241 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100242 const char *errtype = NULL;
243 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
244 errtype = "unicode error";
245 }
246 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
247 errtype = "value error";
248 }
249 if (errtype) {
Pablo Galindofb61c422020-06-15 14:23:43 +0100250 PyObject *type;
251 PyObject *value;
252 PyObject *tback;
253 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100254 PyErr_Fetch(&type, &value, &tback);
255 errstr = PyObject_Str(value);
256 if (errstr) {
257 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
258 Py_DECREF(errstr);
259 }
260 else {
261 PyErr_Clear();
262 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
263 }
264 Py_XDECREF(type);
265 Py_XDECREF(value);
266 Py_XDECREF(tback);
267 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300268
269 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100270}
271
Pablo Galindod6d63712021-01-19 23:59:33 +0000272static inline void
273raise_unclosed_parentheses_error(Parser *p) {
274 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
275 int error_col = p->tok->parencolstack[p->tok->level-1];
276 RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100277 error_lineno, error_col, error_lineno, -1,
Pablo Galindod6d63712021-01-19 23:59:33 +0000278 "'%c' was never closed",
279 p->tok->parenstack[p->tok->level-1]);
280}
281
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100282static void
283raise_tokenizer_init_error(PyObject *filename)
284{
285 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
286 || PyErr_ExceptionMatches(PyExc_ValueError)
287 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
288 return;
289 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300290 PyObject *errstr = NULL;
291 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100292 PyObject *type;
293 PyObject *value;
294 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100295 PyErr_Fetch(&type, &value, &tback);
296 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300297 if (!errstr) {
298 goto error;
299 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100300
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300301 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100302 if (!tmp) {
303 goto error;
304 }
305
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300306 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100307 Py_DECREF(tmp);
308 if (!value) {
309 goto error;
310 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300311 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100312
313error:
314 Py_XDECREF(type);
315 Py_XDECREF(value);
316 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300317 Py_XDECREF(errstr);
318 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100319}
320
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100321static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100322tokenizer_error(Parser *p)
323{
324 if (PyErr_Occurred()) {
325 return -1;
326 }
327
328 const char *msg = NULL;
329 PyObject* errtype = PyExc_SyntaxError;
Pablo Galindo96eeff52021-03-22 17:28:11 +0000330 Py_ssize_t col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100331 switch (p->tok->done) {
332 case E_TOKEN:
333 msg = "invalid token";
334 break;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300335 case E_EOF:
Pablo Galindod6d63712021-01-19 23:59:33 +0000336 if (p->tok->level) {
337 raise_unclosed_parentheses_error(p);
338 } else {
339 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
340 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300341 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100342 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300343 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
344 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100345 case E_INTR:
346 if (!PyErr_Occurred()) {
347 PyErr_SetNone(PyExc_KeyboardInterrupt);
348 }
349 return -1;
350 case E_NOMEM:
351 PyErr_NoMemory();
352 return -1;
353 case E_TABSPACE:
354 errtype = PyExc_TabError;
355 msg = "inconsistent use of tabs and spaces in indentation";
356 break;
357 case E_TOODEEP:
358 errtype = PyExc_IndentationError;
359 msg = "too many levels of indentation";
360 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100361 case E_LINECONT:
Pablo Galindo96eeff52021-03-22 17:28:11 +0000362 col_offset = strlen(strtok(p->tok->buf, "\n")) - 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100363 msg = "unexpected character after line continuation character";
364 break;
365 default:
366 msg = "unknown parsing error";
367 }
368
Pablo Galindoa77aac42021-04-23 14:27:05 +0100369 RAISE_ERROR_KNOWN_LOCATION(p, errtype, p->tok->lineno, col_offset, p->tok->lineno, -1, msg);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100370 return -1;
371}
372
373void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300374_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
375{
376 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100377 Py_ssize_t col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100378 Py_ssize_t end_col_offset = -1;
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
Pablo Galindoa77aac42021-04-23 14:27:05 +0100386 if (t->end_col_offset != -1) {
387 end_col_offset = t->end_col_offset + 1;
388 }
389
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300390 va_list va;
391 va_start(va, errmsg);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100392 _PyPegen_raise_error_known_location(p, errtype, t->lineno, col_offset, t->end_lineno, end_col_offset, errmsg, va);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300393 va_end(va);
394
395 return NULL;
396}
397
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200398static PyObject *
399get_error_line(Parser *p, Py_ssize_t lineno)
400{
Pablo Galindo123ff262021-03-22 16:24:39 +0000401 /* If the file descriptor is interactive, the source lines of the current
402 * (multi-line) statement are stored in p->tok->interactive_src_start.
403 * If not, we're parsing from a string, which means that the whole source
404 * is stored in p->tok->str. */
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200405 assert(p->tok->fp == NULL || p->tok->fp == stdin);
406
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100407 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
408
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200409 for (int i = 0; i < lineno - 1; i++) {
410 cur_line = strchr(cur_line, '\n') + 1;
411 }
412
413 char *next_newline;
414 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
415 next_newline = cur_line + strlen(cur_line);
416 }
417 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
418}
419
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300420void *
421_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100422 Py_ssize_t lineno, Py_ssize_t col_offset,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100423 Py_ssize_t end_lineno, Py_ssize_t end_col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300424 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100425{
426 PyObject *value = NULL;
427 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300428 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100429 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300430 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100431
Pablo Galindoa77aac42021-04-23 14:27:05 +0100432 if (end_lineno == CURRENT_POS) {
433 end_lineno = p->tok->lineno;
434 }
435 if (end_col_offset == CURRENT_POS) {
436 end_col_offset = p->tok->cur - p->tok->line_start;
437 }
438
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300439 if (p->start_rule == Py_fstring_input) {
440 const char *fstring_msg = "f-string: ";
441 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
442
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300443 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300444 if (!new_errmsg) {
445 return (void *) PyErr_NoMemory();
446 }
447
448 // Copy both strings into new buffer
449 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
450 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
451 new_errmsg[len] = 0;
452 errmsg = new_errmsg;
453 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100454 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100455 if (!errstr) {
456 goto error;
457 }
458
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700459 // PyErr_ProgramTextObject assumes that the text is utf-8 so we cannot call it with a file
460 // with an arbitrary encoding or otherwise we could get some badly decoded text.
461 int uses_utf8_codec = (!p->tok->encoding || strcmp(p->tok->encoding, "utf-8") == 0);
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100462 if (p->tok->fp_interactive) {
463 error_line = get_error_line(p, lineno);
464 }
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700465 else if (uses_utf8_codec && p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300466 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100467 }
468
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300469 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200470 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
471 then we need to find the error line from some other source, because
472 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
473 failed or we're parsing from a string or the REPL. There's a third edge case where
474 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
475 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
476 does not physically exist */
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700477 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF || !uses_utf8_codec);
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200478
Pablo Galindo40901512021-01-31 22:48:23 +0000479 if (p->tok->lineno <= lineno) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200480 Py_ssize_t size = p->tok->inp - p->tok->buf;
481 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
482 }
483 else {
484 error_line = get_error_line(p, lineno);
485 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300486 if (!error_line) {
487 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300488 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100489 }
490
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300491 if (p->start_rule == Py_fstring_input) {
492 col_offset -= p->starting_col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100493 end_col_offset -= p->starting_col_offset;
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300494 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100495
Pablo Galindo51c58962020-06-16 16:49:43 +0100496 Py_ssize_t col_number = col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100497 Py_ssize_t end_col_number = end_col_offset;
Pablo Galindo51c58962020-06-16 16:49:43 +0100498
499 if (p->tok->encoding != NULL) {
500 col_number = byte_offset_to_character_offset(error_line, col_offset);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100501 end_col_number = end_col_number > 0 ?
502 byte_offset_to_character_offset(error_line, end_col_offset) :
503 end_col_number;
Pablo Galindo51c58962020-06-16 16:49:43 +0100504 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100505 tmp = Py_BuildValue("(OiiNii)", p->tok->filename, lineno, col_number, error_line, end_lineno, end_col_number);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100506 if (!tmp) {
507 goto error;
508 }
509 value = PyTuple_Pack(2, errstr, tmp);
510 Py_DECREF(tmp);
511 if (!value) {
512 goto error;
513 }
514 PyErr_SetObject(errtype, value);
515
516 Py_DECREF(errstr);
517 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300518 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300519 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300520 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100521 return NULL;
522
523error:
524 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300525 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300526 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300527 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300528 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100529 return NULL;
530}
531
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100532#if 0
533static const char *
534token_name(int type)
535{
536 if (0 <= type && type <= N_TOKENS) {
537 return _PyParser_TokenNames[type];
538 }
539 return "<Huh?>";
540}
541#endif
542
543// Here, mark is the start of the node, while p->mark is the end.
544// If node==NULL, they should be the same.
545int
546_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
547{
548 // Insert in front
Victor Stinner8370e072021-03-24 02:23:01 +0100549 Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100550 if (m == NULL) {
551 return -1;
552 }
553 m->type = type;
554 m->node = node;
555 m->mark = p->mark;
556 m->next = p->tokens[mark]->memo;
557 p->tokens[mark]->memo = m;
558 return 0;
559}
560
561// Like _PyPegen_insert_memo(), but updates an existing node if found.
562int
563_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
564{
565 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
566 if (m->type == type) {
567 // Update existing node.
568 m->node = node;
569 m->mark = p->mark;
570 return 0;
571 }
572 }
573 // Insert new node.
574 return _PyPegen_insert_memo(p, mark, type, node);
575}
576
577// Return dummy NAME.
578void *
579_PyPegen_dummy_name(Parser *p, ...)
580{
581 static void *cache = NULL;
582
583 if (cache != NULL) {
584 return cache;
585 }
586
587 PyObject *id = _create_dummy_identifier(p);
588 if (!id) {
589 return NULL;
590 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200591 cache = _PyAST_Name(id, Load, 1, 0, 1, 0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100592 return cache;
593}
594
595static int
596_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
597{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300598 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100599 if (name_len >= p->n_keyword_lists ||
600 p->keywords[name_len] == NULL ||
601 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100602 return NAME;
603 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100604 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100605 if (strncmp(k->str, name, name_len) == 0) {
606 return k->type;
607 }
608 }
609 return NAME;
610}
611
Guido van Rossumc001c092020-04-30 12:12:19 -0700612static int
613growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
614 assert(initial_size > 0);
615 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
616 arr->size = initial_size;
617 arr->num_items = 0;
618
619 return arr->items != NULL;
620}
621
622static int
623growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
624 if (arr->num_items >= arr->size) {
625 size_t new_size = arr->size * 2;
626 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
627 if (!new_items_array) {
628 return 0;
629 }
630 arr->items = new_items_array;
631 arr->size = new_size;
632 }
633
634 arr->items[arr->num_items].lineno = lineno;
635 arr->items[arr->num_items].comment = comment; // Take ownership
636 arr->num_items++;
637 return 1;
638}
639
640static void
641growable_comment_array_deallocate(growable_comment_array *arr) {
642 for (unsigned i = 0; i < arr->num_items; i++) {
643 PyMem_Free(arr->items[i].comment);
644 }
645 PyMem_Free(arr->items);
646}
647
Pablo Galindod00a4492021-04-09 01:32:25 +0100648static int
649initialize_token(Parser *p, Token *token, const char *start, const char *end, int token_type) {
650 assert(token != NULL);
651
652 token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : token_type;
653 token->bytes = PyBytes_FromStringAndSize(start, end - start);
654 if (token->bytes == NULL) {
655 return -1;
656 }
657
658 if (_PyArena_AddPyObject(p->arena, token->bytes) < 0) {
659 Py_DECREF(token->bytes);
660 return -1;
661 }
662
663 const char *line_start = token_type == STRING ? p->tok->multi_line_start : p->tok->line_start;
664 int lineno = token_type == STRING ? p->tok->first_lineno : p->tok->lineno;
665 int end_lineno = p->tok->lineno;
666
667 int col_offset = (start != NULL && start >= line_start) ? (int)(start - line_start) : -1;
668 int end_col_offset = (end != NULL && end >= p->tok->line_start) ? (int)(end - p->tok->line_start) : -1;
669
670 token->lineno = p->starting_lineno + lineno;
671 token->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
672 token->end_lineno = p->starting_lineno + end_lineno;
673 token->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
674
675 p->fill += 1;
676
677 if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
678 return raise_decode_error(p);
679 }
680
681 return (token_type == ERRORTOKEN ? tokenizer_error(p) : 0);
682}
683
684static int
685_resize_tokens_array(Parser *p) {
686 int newsize = p->size * 2;
687 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
688 if (new_tokens == NULL) {
689 PyErr_NoMemory();
690 return -1;
691 }
692 p->tokens = new_tokens;
693
694 for (int i = p->size; i < newsize; i++) {
695 p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
696 if (p->tokens[i] == NULL) {
697 p->size = i; // Needed, in order to cleanup correctly after parser fails
698 PyErr_NoMemory();
699 return -1;
700 }
701 }
702 p->size = newsize;
703 return 0;
704}
705
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100706int
707_PyPegen_fill_token(Parser *p)
708{
Pablo Galindofb61c422020-06-15 14:23:43 +0100709 const char *start;
710 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100711 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700712
713 // Record and skip '# type: ignore' comments
714 while (type == TYPE_IGNORE) {
715 Py_ssize_t len = end - start;
716 char *tag = PyMem_Malloc(len + 1);
717 if (tag == NULL) {
718 PyErr_NoMemory();
719 return -1;
720 }
721 strncpy(tag, start, len);
722 tag[len] = '\0';
723 // Ownership of tag passes to the growable array
724 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
725 PyErr_NoMemory();
726 return -1;
727 }
728 type = PyTokenizer_Get(p->tok, &start, &end);
729 }
730
Pablo Galindod00a4492021-04-09 01:32:25 +0100731 // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
732 if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100733 type = NEWLINE; /* Add an extra newline */
734 p->parsing_started = 0;
735
Pablo Galindob94dbd72020-04-27 18:35:58 +0100736 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100737 p->tok->pendin = -p->tok->indent;
738 p->tok->indent = 0;
739 }
740 }
741 else {
742 p->parsing_started = 1;
743 }
744
Pablo Galindod00a4492021-04-09 01:32:25 +0100745 // Check if we are at the limit of the token array capacity and resize if needed
746 if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
747 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100748 }
749
750 Token *t = p->tokens[p->fill];
Pablo Galindod00a4492021-04-09 01:32:25 +0100751 return initialize_token(p, t, start, end, type);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100752}
753
Pablo Galindo58bafe42021-04-09 01:17:31 +0100754
755#if defined(Py_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100756// Instrumentation to count the effectiveness of memoization.
757// The array counts the number of tokens skipped by memoization,
758// indexed by type.
759
760#define NSTATISTICS 2000
761static long memo_statistics[NSTATISTICS];
762
763void
764_PyPegen_clear_memo_statistics()
765{
766 for (int i = 0; i < NSTATISTICS; i++) {
767 memo_statistics[i] = 0;
768 }
769}
770
771PyObject *
772_PyPegen_get_memo_statistics()
773{
774 PyObject *ret = PyList_New(NSTATISTICS);
775 if (ret == NULL) {
776 return NULL;
777 }
778 for (int i = 0; i < NSTATISTICS; i++) {
779 PyObject *value = PyLong_FromLong(memo_statistics[i]);
780 if (value == NULL) {
781 Py_DECREF(ret);
782 return NULL;
783 }
784 // PyList_SetItem borrows a reference to value.
785 if (PyList_SetItem(ret, i, value) < 0) {
786 Py_DECREF(ret);
787 return NULL;
788 }
789 }
790 return ret;
791}
Pablo Galindo58bafe42021-04-09 01:17:31 +0100792#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100793
794int // bool
795_PyPegen_is_memoized(Parser *p, int type, void *pres)
796{
797 if (p->mark == p->fill) {
798 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300799 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100800 return -1;
801 }
802 }
803
804 Token *t = p->tokens[p->mark];
805
806 for (Memo *m = t->memo; m != NULL; m = m->next) {
807 if (m->type == type) {
Pablo Galindo58bafe42021-04-09 01:17:31 +0100808#if defined(PY_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100809 if (0 <= type && type < NSTATISTICS) {
810 long count = m->mark - p->mark;
811 // A memoized negative result counts for one.
812 if (count <= 0) {
813 count = 1;
814 }
815 memo_statistics[type] += count;
816 }
Pablo Galindo58bafe42021-04-09 01:17:31 +0100817#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100818 p->mark = m->mark;
819 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100820 return 1;
821 }
822 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100823 return 0;
824}
825
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100826int
827_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
828{
829 int mark = p->mark;
830 void *res = func(p);
831 p->mark = mark;
832 return (res != NULL) == positive;
833}
834
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100835int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100836_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
837{
838 int mark = p->mark;
839 void *res = func(p, arg);
840 p->mark = mark;
841 return (res != NULL) == positive;
842}
843
844int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100845_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
846{
847 int mark = p->mark;
848 void *res = func(p, arg);
849 p->mark = mark;
850 return (res != NULL) == positive;
851}
852
853int
854_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
855{
856 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100857 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100858 p->mark = mark;
859 return (res != NULL) == positive;
860}
861
862Token *
863_PyPegen_expect_token(Parser *p, int type)
864{
865 if (p->mark == p->fill) {
866 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300867 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100868 return NULL;
869 }
870 }
871 Token *t = p->tokens[p->mark];
872 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100873 return NULL;
874 }
875 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100876 return t;
877}
878
Pablo Galindo58fb1562021-02-02 19:54:22 +0000879Token *
880_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
881
882 if (p->error_indicator == 1) {
883 return NULL;
884 }
885
886 if (p->mark == p->fill) {
887 if (_PyPegen_fill_token(p) < 0) {
888 p->error_indicator = 1;
889 return NULL;
890 }
891 }
892 Token *t = p->tokens[p->mark];
893 if (t->type != type) {
894 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
895 return NULL;
896 }
897 p->mark += 1;
898 return t;
899}
900
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700901expr_ty
902_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
903{
904 if (p->mark == p->fill) {
905 if (_PyPegen_fill_token(p) < 0) {
906 p->error_indicator = 1;
907 return NULL;
908 }
909 }
910 Token *t = p->tokens[p->mark];
911 if (t->type != NAME) {
912 return NULL;
913 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300914 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700915 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300916 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700917 return NULL;
918 }
919 if (strcmp(s, keyword) != 0) {
920 return NULL;
921 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300922 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700923}
924
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100925Token *
926_PyPegen_get_last_nonnwhitespace_token(Parser *p)
927{
928 assert(p->mark >= 0);
929 Token *token = NULL;
930 for (int m = p->mark - 1; m >= 0; m--) {
931 token = p->tokens[m];
932 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
933 break;
934 }
935 }
936 return token;
937}
938
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100939expr_ty
940_PyPegen_name_token(Parser *p)
941{
942 Token *t = _PyPegen_expect_token(p, NAME);
943 if (t == NULL) {
944 return NULL;
945 }
946 char* s = PyBytes_AsString(t->bytes);
947 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300948 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100949 return NULL;
950 }
951 PyObject *id = _PyPegen_new_identifier(p, s);
952 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300953 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100954 return NULL;
955 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200956 return _PyAST_Name(id, Load, t->lineno, t->col_offset, t->end_lineno,
957 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100958}
959
960void *
961_PyPegen_string_token(Parser *p)
962{
963 return _PyPegen_expect_token(p, STRING);
964}
965
Pablo Galindob2802482021-04-15 21:38:45 +0100966
967expr_ty _PyPegen_soft_keyword_token(Parser *p) {
968 Token *t = _PyPegen_expect_token(p, NAME);
969 if (t == NULL) {
970 return NULL;
971 }
972 char *the_token;
973 Py_ssize_t size;
974 PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
975 for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
976 if (strncmp(*keyword, the_token, size) == 0) {
977 return _PyPegen_name_token(p);
978 }
979 }
980 return NULL;
981}
982
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100983static PyObject *
984parsenumber_raw(const char *s)
985{
986 const char *end;
987 long x;
988 double dx;
989 Py_complex compl;
990 int imflag;
991
992 assert(s != NULL);
993 errno = 0;
994 end = s + strlen(s) - 1;
995 imflag = *end == 'j' || *end == 'J';
996 if (s[0] == '0') {
997 x = (long)PyOS_strtoul(s, (char **)&end, 0);
998 if (x < 0 && errno == 0) {
999 return PyLong_FromString(s, (char **)0, 0);
1000 }
1001 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001002 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001003 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001004 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001005 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +01001006 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001007 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001008 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001009 return PyLong_FromLong(x);
1010 }
1011 /* XXX Huge floats may silently fail */
1012 if (imflag) {
1013 compl.real = 0.;
1014 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +01001015 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001016 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +01001017 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001018 return PyComplex_FromCComplex(compl);
1019 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001020 dx = PyOS_string_to_double(s, NULL, NULL);
1021 if (dx == -1.0 && PyErr_Occurred()) {
1022 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001023 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001024 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001025}
1026
1027static PyObject *
1028parsenumber(const char *s)
1029{
Pablo Galindofb61c422020-06-15 14:23:43 +01001030 char *dup;
1031 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001032 PyObject *res = NULL;
1033
1034 assert(s != NULL);
1035
1036 if (strchr(s, '_') == NULL) {
1037 return parsenumber_raw(s);
1038 }
1039 /* Create a duplicate without underscores. */
1040 dup = PyMem_Malloc(strlen(s) + 1);
1041 if (dup == NULL) {
1042 return PyErr_NoMemory();
1043 }
1044 end = dup;
1045 for (; *s; s++) {
1046 if (*s != '_') {
1047 *end++ = *s;
1048 }
1049 }
1050 *end = '\0';
1051 res = parsenumber_raw(dup);
1052 PyMem_Free(dup);
1053 return res;
1054}
1055
1056expr_ty
1057_PyPegen_number_token(Parser *p)
1058{
1059 Token *t = _PyPegen_expect_token(p, NUMBER);
1060 if (t == NULL) {
1061 return NULL;
1062 }
1063
1064 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001065 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001066 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001067 return NULL;
1068 }
1069
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001070 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1071 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -07001072 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001073 "in Python 3.6 and greater");
1074 }
1075
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001076 PyObject *c = parsenumber(num_raw);
1077
1078 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001079 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001080 return NULL;
1081 }
1082
Victor Stinner8370e072021-03-24 02:23:01 +01001083 if (_PyArena_AddPyObject(p->arena, c) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001084 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001085 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001086 return NULL;
1087 }
1088
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001089 return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
1090 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001091}
1092
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001093static int // bool
1094newline_in_string(Parser *p, const char *cur)
1095{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001096 for (const char *c = cur; c >= p->tok->buf; c--) {
1097 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001098 return 1;
1099 }
1100 }
1101 return 0;
1102}
1103
1104/* Check that the source for a single input statement really is a single
1105 statement by looking at what is left in the buffer after parsing.
1106 Trailing whitespace and comments are OK. */
1107static int // bool
1108bad_single_statement(Parser *p)
1109{
1110 const char *cur = strchr(p->tok->buf, '\n');
1111
1112 /* Newlines are allowed if preceded by a line continuation character
1113 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001114 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1115 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001116 return 0;
1117 }
1118 char c = *cur;
1119
1120 for (;;) {
1121 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1122 c = *++cur;
1123 }
1124
1125 if (!c) {
1126 return 0;
1127 }
1128
1129 if (c != '#') {
1130 return 1;
1131 }
1132
1133 /* Suck up comment. */
1134 while (c && c != '\n') {
1135 c = *++cur;
1136 }
1137 }
1138}
1139
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001140void
1141_PyPegen_Parser_Free(Parser *p)
1142{
1143 Py_XDECREF(p->normalize);
1144 for (int i = 0; i < p->size; i++) {
1145 PyMem_Free(p->tokens[i]);
1146 }
1147 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001148 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001149 PyMem_Free(p);
1150}
1151
Pablo Galindo2b74c832020-04-27 18:02:07 +01001152static int
1153compute_parser_flags(PyCompilerFlags *flags)
1154{
1155 int parser_flags = 0;
1156 if (!flags) {
1157 return 0;
1158 }
1159 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1160 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1161 }
1162 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1163 parser_flags |= PyPARSE_IGNORE_COOKIE;
1164 }
1165 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1166 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1167 }
1168 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1169 parser_flags |= PyPARSE_TYPE_COMMENTS;
1170 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001171 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001172 parser_flags |= PyPARSE_ASYNC_HACKS;
1173 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001174 return parser_flags;
1175}
1176
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001177Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001178_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001179 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001180{
1181 Parser *p = PyMem_Malloc(sizeof(Parser));
1182 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001183 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001184 }
1185 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001186 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1187 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001188 p->tok = tok;
1189 p->keywords = NULL;
1190 p->n_keyword_lists = -1;
Pablo Galindob2802482021-04-15 21:38:45 +01001191 p->soft_keywords = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001192 p->tokens = PyMem_Malloc(sizeof(Token *));
1193 if (!p->tokens) {
1194 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001195 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001196 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001197 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001198 if (!p->tokens) {
1199 PyMem_Free(p->tokens);
1200 PyMem_Free(p);
1201 return (Parser *) PyErr_NoMemory();
1202 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001203 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1204 PyMem_Free(p->tokens[0]);
1205 PyMem_Free(p->tokens);
1206 PyMem_Free(p);
1207 return (Parser *) PyErr_NoMemory();
1208 }
1209
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001210 p->mark = 0;
1211 p->fill = 0;
1212 p->size = 1;
1213
1214 p->errcode = errcode;
1215 p->arena = arena;
1216 p->start_rule = start_rule;
1217 p->parsing_started = 0;
1218 p->normalize = NULL;
1219 p->error_indicator = 0;
1220
1221 p->starting_lineno = 0;
1222 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001223 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001224 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001225 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001226 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001227 p->call_invalid_rules = 0;
Miss Islington (bot)ae1732d2021-05-21 11:20:43 -07001228 p->in_raw_rule = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001229 return p;
1230}
1231
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001232static void
1233reset_parser_state(Parser *p)
1234{
1235 for (int i = 0; i < p->fill; i++) {
1236 p->tokens[i]->memo = NULL;
1237 }
1238 p->mark = 0;
1239 p->call_invalid_rules = 1;
Miss Islington (bot)1fb6b9e2021-05-22 15:23:26 -07001240 // Don't try to get extra tokens in interactive mode when trying to
1241 // raise specialized errors in the second pass.
1242 p->tok->interactive_underflow = IUNDERFLOW_STOP;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001243}
1244
Pablo Galindod6d63712021-01-19 23:59:33 +00001245static int
1246_PyPegen_check_tokenizer_errors(Parser *p) {
1247 // Tokenize the whole input to see if there are any tokenization
1248 // errors such as mistmatching parentheses. These will get priority
1249 // over generic syntax errors only if the line number of the error is
1250 // before the one that we had for the generic error.
1251
1252 // We don't want to tokenize to the end for interactive input
1253 if (p->tok->prompt != NULL) {
1254 return 0;
1255 }
1256
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001257 PyObject *type, *value, *traceback;
1258 PyErr_Fetch(&type, &value, &traceback);
1259
Pablo Galindod6d63712021-01-19 23:59:33 +00001260 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1261 Py_ssize_t current_err_line = current_token->lineno;
1262
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001263 int ret = 0;
1264
Pablo Galindod6d63712021-01-19 23:59:33 +00001265 for (;;) {
1266 const char *start;
1267 const char *end;
1268 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1269 case ERRORTOKEN:
1270 if (p->tok->level != 0) {
1271 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1272 if (current_err_line > error_lineno) {
1273 raise_unclosed_parentheses_error(p);
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001274 ret = -1;
1275 goto exit;
Pablo Galindod6d63712021-01-19 23:59:33 +00001276 }
1277 }
1278 break;
1279 case ENDMARKER:
1280 break;
1281 default:
1282 continue;
1283 }
1284 break;
1285 }
1286
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001287
1288exit:
1289 if (PyErr_Occurred()) {
1290 Py_XDECREF(value);
1291 Py_XDECREF(type);
1292 Py_XDECREF(traceback);
1293 } else {
1294 PyErr_Restore(type, value, traceback);
1295 }
1296 return ret;
Pablo Galindod6d63712021-01-19 23:59:33 +00001297}
1298
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001299void *
1300_PyPegen_run_parser(Parser *p)
1301{
1302 void *res = _PyPegen_parse(p);
1303 if (res == NULL) {
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001304 Token *last_token = p->tokens[p->fill - 1];
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001305 reset_parser_state(p);
1306 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001307 if (PyErr_Occurred()) {
Miss Islington (bot)933b5b62021-06-08 04:46:56 -07001308 // Prioritize tokenizer errors to custom syntax errors raised
1309 // on the second phase only if the errors come from the parser.
1310 if (p->tok->done != E_ERROR && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
Miss Islington (bot)756b7b92021-05-03 18:06:45 -07001311 _PyPegen_check_tokenizer_errors(p);
1312 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001313 return NULL;
1314 }
1315 if (p->fill == 0) {
1316 RAISE_SYNTAX_ERROR("error at start before reading any input");
1317 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001318 else if (p->tok->done == E_EOF) {
Pablo Galindod6d63712021-01-19 23:59:33 +00001319 if (p->tok->level) {
1320 raise_unclosed_parentheses_error(p);
1321 } else {
1322 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1323 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001324 }
1325 else {
1326 if (p->tokens[p->fill-1]->type == INDENT) {
1327 RAISE_INDENTATION_ERROR("unexpected indent");
1328 }
1329 else if (p->tokens[p->fill-1]->type == DEDENT) {
1330 RAISE_INDENTATION_ERROR("unexpected unindent");
1331 }
1332 else {
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001333 // Use the last token we found on the first pass to avoid reporting
1334 // incorrect locations for generic syntax errors just because we reached
1335 // further away when trying to find specific syntax errors in the second
1336 // pass.
1337 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(last_token, "invalid syntax");
Pablo Galindoc3f167d2021-01-20 19:11:56 +00001338 // _PyPegen_check_tokenizer_errors will override the existing
1339 // generic SyntaxError we just raised if errors are found.
1340 _PyPegen_check_tokenizer_errors(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001341 }
1342 }
1343 return NULL;
1344 }
1345
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001346 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1347 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1348 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1349 }
1350
Victor Stinnere0bf70d2021-03-18 02:46:06 +01001351 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1352#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
Pablo Galindo13322262020-07-27 23:46:59 +01001353 if (p->start_rule == Py_single_input ||
1354 p->start_rule == Py_file_input ||
1355 p->start_rule == Py_eval_input)
1356 {
Victor Stinnereec8e612021-03-18 14:57:49 +01001357 if (!_PyAST_Validate(res)) {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001358 return NULL;
1359 }
Pablo Galindo13322262020-07-27 23:46:59 +01001360 }
1361#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001362 return res;
1363}
1364
1365mod_ty
1366_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1367 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001368 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001369{
1370 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1371 if (tok == NULL) {
1372 if (PyErr_Occurred()) {
1373 raise_tokenizer_init_error(filename_ob);
1374 return NULL;
1375 }
1376 return NULL;
1377 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001378 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1379 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1380 tok->fp_interactive = 1;
1381 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001382 // This transfers the ownership to the tokenizer
1383 tok->filename = filename_ob;
1384 Py_INCREF(filename_ob);
1385
1386 // From here on we need to clean up even if there's an error
1387 mod_ty result = NULL;
1388
Pablo Galindo2b74c832020-04-27 18:02:07 +01001389 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001390 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1391 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001392 if (p == NULL) {
1393 goto error;
1394 }
1395
1396 result = _PyPegen_run_parser(p);
1397 _PyPegen_Parser_Free(p);
1398
1399error:
1400 PyTokenizer_Free(tok);
1401 return result;
1402}
1403
1404mod_ty
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001405_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001406 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001407{
1408 int exec_input = start_rule == Py_file_input;
1409
1410 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001411 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001412 tok = PyTokenizer_FromUTF8(str, exec_input);
1413 } else {
1414 tok = PyTokenizer_FromString(str, exec_input);
1415 }
1416 if (tok == NULL) {
1417 if (PyErr_Occurred()) {
1418 raise_tokenizer_init_error(filename_ob);
1419 }
1420 return NULL;
1421 }
1422 // This transfers the ownership to the tokenizer
1423 tok->filename = filename_ob;
1424 Py_INCREF(filename_ob);
1425
1426 // We need to clear up from here on
1427 mod_ty result = NULL;
1428
Pablo Galindo2b74c832020-04-27 18:02:07 +01001429 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001430 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1431 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001432 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1433 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001434 if (p == NULL) {
1435 goto error;
1436 }
1437
1438 result = _PyPegen_run_parser(p);
1439 _PyPegen_Parser_Free(p);
1440
1441error:
1442 PyTokenizer_Free(tok);
1443 return result;
1444}
1445
Pablo Galindoa5634c42020-09-16 19:42:00 +01001446asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001447_PyPegen_interactive_exit(Parser *p)
1448{
1449 if (p->errcode) {
1450 *(p->errcode) = E_EOF;
1451 }
1452 return NULL;
1453}
1454
1455/* Creates a single-element asdl_seq* that contains a */
1456asdl_seq *
1457_PyPegen_singleton_seq(Parser *p, void *a)
1458{
1459 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001460 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001461 if (!seq) {
1462 return NULL;
1463 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001464 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001465 return seq;
1466}
1467
1468/* Creates a copy of seq and prepends a to it */
1469asdl_seq *
1470_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1471{
1472 assert(a != NULL);
1473 if (!seq) {
1474 return _PyPegen_singleton_seq(p, a);
1475 }
1476
Pablo Galindoa5634c42020-09-16 19:42:00 +01001477 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 +01001478 if (!new_seq) {
1479 return NULL;
1480 }
1481
Pablo Galindoa5634c42020-09-16 19:42:00 +01001482 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001483 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001484 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001485 }
1486 return new_seq;
1487}
1488
Guido van Rossumc001c092020-04-30 12:12:19 -07001489/* Creates a copy of seq and appends a to it */
1490asdl_seq *
1491_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1492{
1493 assert(a != NULL);
1494 if (!seq) {
1495 return _PyPegen_singleton_seq(p, a);
1496 }
1497
Pablo Galindoa5634c42020-09-16 19:42:00 +01001498 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 -07001499 if (!new_seq) {
1500 return NULL;
1501 }
1502
1503 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001504 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001505 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001506 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001507 return new_seq;
1508}
1509
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001510static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001511_get_flattened_seq_size(asdl_seq *seqs)
1512{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001513 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001514 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001515 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001516 size += asdl_seq_LEN(inner_seq);
1517 }
1518 return size;
1519}
1520
1521/* Flattens an asdl_seq* of asdl_seq*s */
1522asdl_seq *
1523_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1524{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001525 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001526 assert(flattened_seq_size > 0);
1527
Pablo Galindoa5634c42020-09-16 19:42:00 +01001528 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001529 if (!flattened_seq) {
1530 return NULL;
1531 }
1532
1533 int flattened_seq_idx = 0;
1534 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001535 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001536 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001537 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001538 }
1539 }
1540 assert(flattened_seq_idx == flattened_seq_size);
1541
1542 return flattened_seq;
1543}
1544
Pablo Galindoa77aac42021-04-23 14:27:05 +01001545void *
1546_PyPegen_seq_last_item(asdl_seq *seq)
1547{
1548 Py_ssize_t len = asdl_seq_LEN(seq);
1549 return asdl_seq_GET_UNTYPED(seq, len - 1);
1550}
1551
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001552/* Creates a new name of the form <first_name>.<second_name> */
1553expr_ty
1554_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1555{
1556 assert(first_name != NULL && second_name != NULL);
1557 PyObject *first_identifier = first_name->v.Name.id;
1558 PyObject *second_identifier = second_name->v.Name.id;
1559
1560 if (PyUnicode_READY(first_identifier) == -1) {
1561 return NULL;
1562 }
1563 if (PyUnicode_READY(second_identifier) == -1) {
1564 return NULL;
1565 }
1566 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1567 if (!first_str) {
1568 return NULL;
1569 }
1570 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1571 if (!second_str) {
1572 return NULL;
1573 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001574 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001575
1576 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1577 if (!str) {
1578 return NULL;
1579 }
1580
1581 char *s = PyBytes_AS_STRING(str);
1582 if (!s) {
1583 return NULL;
1584 }
1585
1586 strcpy(s, first_str);
1587 s += strlen(first_str);
1588 *s++ = '.';
1589 strcpy(s, second_str);
1590 s += strlen(second_str);
1591 *s = '\0';
1592
1593 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1594 Py_DECREF(str);
1595 if (!uni) {
1596 return NULL;
1597 }
1598 PyUnicode_InternInPlace(&uni);
Victor Stinner8370e072021-03-24 02:23:01 +01001599 if (_PyArena_AddPyObject(p->arena, uni) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001600 Py_DECREF(uni);
1601 return NULL;
1602 }
1603
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001604 return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001605}
1606
1607/* Counts the total number of dots in seq's tokens */
1608int
1609_PyPegen_seq_count_dots(asdl_seq *seq)
1610{
1611 int number_of_dots = 0;
1612 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001613 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001614 switch (current_expr->type) {
1615 case ELLIPSIS:
1616 number_of_dots += 3;
1617 break;
1618 case DOT:
1619 number_of_dots += 1;
1620 break;
1621 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001622 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001623 }
1624 }
1625
1626 return number_of_dots;
1627}
1628
1629/* Creates an alias with '*' as the identifier name */
1630alias_ty
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001631_PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
1632 int end_col_offset, PyArena *arena) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001633 PyObject *str = PyUnicode_InternFromString("*");
1634 if (!str) {
1635 return NULL;
1636 }
Victor Stinner8370e072021-03-24 02:23:01 +01001637 if (_PyArena_AddPyObject(p->arena, str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001638 Py_DECREF(str);
1639 return NULL;
1640 }
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001641 return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001642}
1643
1644/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001645asdl_identifier_seq *
1646_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001647{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001648 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001649 assert(len > 0);
1650
Pablo Galindoa5634c42020-09-16 19:42:00 +01001651 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001652 if (!new_seq) {
1653 return NULL;
1654 }
1655 for (Py_ssize_t i = 0; i < len; i++) {
1656 expr_ty e = asdl_seq_GET(seq, i);
1657 asdl_seq_SET(new_seq, i, e->v.Name.id);
1658 }
1659 return new_seq;
1660}
1661
1662/* Constructs a CmpopExprPair */
1663CmpopExprPair *
1664_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1665{
1666 assert(expr != NULL);
Victor Stinner8370e072021-03-24 02:23:01 +01001667 CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001668 if (!a) {
1669 return NULL;
1670 }
1671 a->cmpop = cmpop;
1672 a->expr = expr;
1673 return a;
1674}
1675
1676asdl_int_seq *
1677_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1678{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001679 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001680 assert(len > 0);
1681
1682 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1683 if (!new_seq) {
1684 return NULL;
1685 }
1686 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001687 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001688 asdl_seq_SET(new_seq, i, pair->cmpop);
1689 }
1690 return new_seq;
1691}
1692
Pablo Galindoa5634c42020-09-16 19:42:00 +01001693asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001694_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1695{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001696 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001697 assert(len > 0);
1698
Pablo Galindoa5634c42020-09-16 19:42:00 +01001699 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001700 if (!new_seq) {
1701 return NULL;
1702 }
1703 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001704 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001705 asdl_seq_SET(new_seq, i, pair->expr);
1706 }
1707 return new_seq;
1708}
1709
1710/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001711static asdl_expr_seq *
1712_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001713{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001714 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001715 if (len == 0) {
1716 return NULL;
1717 }
1718
Pablo Galindoa5634c42020-09-16 19:42:00 +01001719 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001720 if (!new_seq) {
1721 return NULL;
1722 }
1723 for (Py_ssize_t i = 0; i < len; i++) {
1724 expr_ty e = asdl_seq_GET(seq, i);
1725 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1726 }
1727 return new_seq;
1728}
1729
1730static expr_ty
1731_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1732{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001733 return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001734}
1735
1736static expr_ty
1737_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1738{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001739 return _PyAST_Tuple(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001740 _set_seq_context(p, e->v.Tuple.elts, ctx),
1741 ctx,
1742 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001743}
1744
1745static expr_ty
1746_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1747{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001748 return _PyAST_List(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001749 _set_seq_context(p, e->v.List.elts, ctx),
1750 ctx,
1751 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001752}
1753
1754static expr_ty
1755_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1756{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001757 return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
1758 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001759}
1760
1761static expr_ty
1762_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1763{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001764 return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
1765 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001766}
1767
1768static expr_ty
1769_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1770{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001771 return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
1772 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001773}
1774
1775/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1776expr_ty
1777_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1778{
1779 assert(expr != NULL);
1780
1781 expr_ty new = NULL;
1782 switch (expr->kind) {
1783 case Name_kind:
1784 new = _set_name_context(p, expr, ctx);
1785 break;
1786 case Tuple_kind:
1787 new = _set_tuple_context(p, expr, ctx);
1788 break;
1789 case List_kind:
1790 new = _set_list_context(p, expr, ctx);
1791 break;
1792 case Subscript_kind:
1793 new = _set_subscript_context(p, expr, ctx);
1794 break;
1795 case Attribute_kind:
1796 new = _set_attribute_context(p, expr, ctx);
1797 break;
1798 case Starred_kind:
1799 new = _set_starred_context(p, expr, ctx);
1800 break;
1801 default:
1802 new = expr;
1803 }
1804 return new;
1805}
1806
1807/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1808KeyValuePair *
1809_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1810{
Victor Stinner8370e072021-03-24 02:23:01 +01001811 KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001812 if (!a) {
1813 return NULL;
1814 }
1815 a->key = key;
1816 a->value = value;
1817 return a;
1818}
1819
1820/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001821asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001822_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1823{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001824 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001825 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001826 if (!new_seq) {
1827 return NULL;
1828 }
1829 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001830 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001831 asdl_seq_SET(new_seq, i, pair->key);
1832 }
1833 return new_seq;
1834}
1835
1836/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001837asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001838_PyPegen_get_values(Parser *p, asdl_seq *seq)
1839{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001840 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001841 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001842 if (!new_seq) {
1843 return NULL;
1844 }
1845 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001846 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001847 asdl_seq_SET(new_seq, i, pair->value);
1848 }
1849 return new_seq;
1850}
1851
Nick Coghlan1e7b8582021-04-29 15:58:44 +10001852/* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
1853KeyPatternPair *
1854_PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
1855{
1856 KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
1857 if (!a) {
1858 return NULL;
1859 }
1860 a->key = key;
1861 a->pattern = pattern;
1862 return a;
1863}
1864
1865/* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
1866asdl_expr_seq *
1867_PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
1868{
1869 Py_ssize_t len = asdl_seq_LEN(seq);
1870 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1871 if (!new_seq) {
1872 return NULL;
1873 }
1874 for (Py_ssize_t i = 0; i < len; i++) {
1875 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1876 asdl_seq_SET(new_seq, i, pair->key);
1877 }
1878 return new_seq;
1879}
1880
1881/* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
1882asdl_pattern_seq *
1883_PyPegen_get_patterns(Parser *p, asdl_seq *seq)
1884{
1885 Py_ssize_t len = asdl_seq_LEN(seq);
1886 asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
1887 if (!new_seq) {
1888 return NULL;
1889 }
1890 for (Py_ssize_t i = 0; i < len; i++) {
1891 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1892 asdl_seq_SET(new_seq, i, pair->pattern);
1893 }
1894 return new_seq;
1895}
1896
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001897/* Constructs a NameDefaultPair */
1898NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001899_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001900{
Victor Stinner8370e072021-03-24 02:23:01 +01001901 NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001902 if (!a) {
1903 return NULL;
1904 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001905 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001906 a->value = value;
1907 return a;
1908}
1909
1910/* Constructs a SlashWithDefault */
1911SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001912_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001913{
Victor Stinner8370e072021-03-24 02:23:01 +01001914 SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001915 if (!a) {
1916 return NULL;
1917 }
1918 a->plain_names = plain_names;
1919 a->names_with_defaults = names_with_defaults;
1920 return a;
1921}
1922
1923/* Constructs a StarEtc */
1924StarEtc *
1925_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1926{
Victor Stinner8370e072021-03-24 02:23:01 +01001927 StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001928 if (!a) {
1929 return NULL;
1930 }
1931 a->vararg = vararg;
1932 a->kwonlyargs = kwonlyargs;
1933 a->kwarg = kwarg;
1934 return a;
1935}
1936
1937asdl_seq *
1938_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1939{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001940 Py_ssize_t first_len = asdl_seq_LEN(a);
1941 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001942 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001943 if (!new_seq) {
1944 return NULL;
1945 }
1946
1947 int k = 0;
1948 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001949 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001950 }
1951 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001952 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001953 }
1954
1955 return new_seq;
1956}
1957
Pablo Galindoa5634c42020-09-16 19:42:00 +01001958static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001959_get_names(Parser *p, asdl_seq *names_with_defaults)
1960{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001961 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001962 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001963 if (!seq) {
1964 return NULL;
1965 }
1966 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001967 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001968 asdl_seq_SET(seq, i, pair->arg);
1969 }
1970 return seq;
1971}
1972
Pablo Galindoa5634c42020-09-16 19:42:00 +01001973static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001974_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1975{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001976 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001977 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001978 if (!seq) {
1979 return NULL;
1980 }
1981 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001982 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001983 asdl_seq_SET(seq, i, pair->value);
1984 }
1985 return seq;
1986}
1987
Pablo Galindo4f642da2021-04-09 00:48:53 +01001988static int
1989_make_posonlyargs(Parser *p,
1990 asdl_arg_seq *slash_without_default,
1991 SlashWithDefault *slash_with_default,
1992 asdl_arg_seq **posonlyargs) {
1993 if (slash_without_default != NULL) {
1994 *posonlyargs = slash_without_default;
1995 }
1996 else if (slash_with_default != NULL) {
1997 asdl_arg_seq *slash_with_default_names =
1998 _get_names(p, slash_with_default->names_with_defaults);
1999 if (!slash_with_default_names) {
2000 return -1;
2001 }
2002 *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2003 p,
2004 (asdl_seq*)slash_with_default->plain_names,
2005 (asdl_seq*)slash_with_default_names);
2006 }
2007 else {
2008 *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2009 }
2010 return *posonlyargs == NULL ? -1 : 0;
2011}
2012
2013static int
2014_make_posargs(Parser *p,
2015 asdl_arg_seq *plain_names,
2016 asdl_seq *names_with_default,
2017 asdl_arg_seq **posargs) {
2018 if (plain_names != NULL && names_with_default != NULL) {
2019 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
2020 if (!names_with_default_names) {
2021 return -1;
2022 }
2023 *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2024 p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
2025 }
2026 else if (plain_names == NULL && names_with_default != NULL) {
2027 *posargs = _get_names(p, names_with_default);
2028 }
2029 else if (plain_names != NULL && names_with_default == NULL) {
2030 *posargs = plain_names;
2031 }
2032 else {
2033 *posargs = _Py_asdl_arg_seq_new(0, p->arena);
2034 }
2035 return *posargs == NULL ? -1 : 0;
2036}
2037
2038static int
2039_make_posdefaults(Parser *p,
2040 SlashWithDefault *slash_with_default,
2041 asdl_seq *names_with_default,
2042 asdl_expr_seq **posdefaults) {
2043 if (slash_with_default != NULL && names_with_default != NULL) {
2044 asdl_expr_seq *slash_with_default_values =
2045 _get_defaults(p, slash_with_default->names_with_defaults);
2046 if (!slash_with_default_values) {
2047 return -1;
2048 }
2049 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
2050 if (!names_with_default_values) {
2051 return -1;
2052 }
2053 *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
2054 p,
2055 (asdl_seq*)slash_with_default_values,
2056 (asdl_seq*)names_with_default_values);
2057 }
2058 else if (slash_with_default == NULL && names_with_default != NULL) {
2059 *posdefaults = _get_defaults(p, names_with_default);
2060 }
2061 else if (slash_with_default != NULL && names_with_default == NULL) {
2062 *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
2063 }
2064 else {
2065 *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2066 }
2067 return *posdefaults == NULL ? -1 : 0;
2068}
2069
2070static int
2071_make_kwargs(Parser *p, StarEtc *star_etc,
2072 asdl_arg_seq **kwonlyargs,
2073 asdl_expr_seq **kwdefaults) {
2074 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2075 *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
2076 }
2077 else {
2078 *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2079 }
2080
2081 if (*kwonlyargs == NULL) {
2082 return -1;
2083 }
2084
2085 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2086 *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
2087 }
2088 else {
2089 *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2090 }
2091
2092 if (*kwdefaults == NULL) {
2093 return -1;
2094 }
2095
2096 return 0;
2097}
2098
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002099/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
2100arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002101_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
2102 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002103 asdl_seq *names_with_default, StarEtc *star_etc)
2104{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002105 asdl_arg_seq *posonlyargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002106 if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
2107 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002108 }
2109
Pablo Galindoa5634c42020-09-16 19:42:00 +01002110 asdl_arg_seq *posargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002111 if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
2112 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002113 }
2114
Pablo Galindoa5634c42020-09-16 19:42:00 +01002115 asdl_expr_seq *posdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002116 if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
2117 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002118 }
2119
2120 arg_ty vararg = NULL;
2121 if (star_etc != NULL && star_etc->vararg != NULL) {
2122 vararg = star_etc->vararg;
2123 }
2124
Pablo Galindoa5634c42020-09-16 19:42:00 +01002125 asdl_arg_seq *kwonlyargs;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002126 asdl_expr_seq *kwdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002127 if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
2128 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002129 }
2130
2131 arg_ty kwarg = NULL;
2132 if (star_etc != NULL && star_etc->kwarg != NULL) {
2133 kwarg = star_etc->kwarg;
2134 }
2135
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002136 return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
2137 kwdefaults, kwarg, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002138}
2139
Pablo Galindo4f642da2021-04-09 00:48:53 +01002140
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002141/* Constructs an empty arguments_ty object, that gets used when a function accepts no
2142 * arguments. */
2143arguments_ty
2144_PyPegen_empty_arguments(Parser *p)
2145{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002146 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002147 if (!posonlyargs) {
2148 return NULL;
2149 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002150 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002151 if (!posargs) {
2152 return NULL;
2153 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002154 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002155 if (!posdefaults) {
2156 return NULL;
2157 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002158 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002159 if (!kwonlyargs) {
2160 return NULL;
2161 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002162 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002163 if (!kwdefaults) {
2164 return NULL;
2165 }
2166
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002167 return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
2168 kwdefaults, NULL, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002169}
2170
2171/* Encapsulates the value of an operator_ty into an AugOperator struct */
2172AugOperator *
2173_PyPegen_augoperator(Parser *p, operator_ty kind)
2174{
Victor Stinner8370e072021-03-24 02:23:01 +01002175 AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002176 if (!a) {
2177 return NULL;
2178 }
2179 a->kind = kind;
2180 return a;
2181}
2182
2183/* Construct a FunctionDef equivalent to function_def, but with decorators */
2184stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002185_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002186{
2187 assert(function_def != NULL);
2188 if (function_def->kind == AsyncFunctionDef_kind) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002189 return _PyAST_AsyncFunctionDef(
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002190 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2191 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2192 function_def->v.FunctionDef.type_comment, function_def->lineno,
2193 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2194 p->arena);
2195 }
2196
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002197 return _PyAST_FunctionDef(
2198 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2199 function_def->v.FunctionDef.body, decorators,
2200 function_def->v.FunctionDef.returns,
2201 function_def->v.FunctionDef.type_comment, function_def->lineno,
2202 function_def->col_offset, function_def->end_lineno,
2203 function_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002204}
2205
2206/* Construct a ClassDef equivalent to class_def, but with decorators */
2207stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002208_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002209{
2210 assert(class_def != NULL);
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002211 return _PyAST_ClassDef(
2212 class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2213 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2214 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2215 class_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002216}
2217
2218/* Construct a KeywordOrStarred */
2219KeywordOrStarred *
2220_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2221{
Victor Stinner8370e072021-03-24 02:23:01 +01002222 KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002223 if (!a) {
2224 return NULL;
2225 }
2226 a->element = element;
2227 a->is_keyword = is_keyword;
2228 return a;
2229}
2230
2231/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2232static int
2233_seq_number_of_starred_exprs(asdl_seq *seq)
2234{
2235 int n = 0;
2236 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002237 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002238 if (!k->is_keyword) {
2239 n++;
2240 }
2241 }
2242 return n;
2243}
2244
2245/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002246asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002247_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2248{
2249 int new_len = _seq_number_of_starred_exprs(kwargs);
2250 if (new_len == 0) {
2251 return NULL;
2252 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002253 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002254 if (!new_seq) {
2255 return NULL;
2256 }
2257
2258 int idx = 0;
2259 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002260 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002261 if (!k->is_keyword) {
2262 asdl_seq_SET(new_seq, idx++, k->element);
2263 }
2264 }
2265 return new_seq;
2266}
2267
2268/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002269asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002270_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2271{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002272 Py_ssize_t len = asdl_seq_LEN(kwargs);
2273 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002274 if (new_len == 0) {
2275 return NULL;
2276 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002277 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002278 if (!new_seq) {
2279 return NULL;
2280 }
2281
2282 int idx = 0;
2283 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002284 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002285 if (k->is_keyword) {
2286 asdl_seq_SET(new_seq, idx++, k->element);
2287 }
2288 }
2289 return new_seq;
2290}
2291
2292expr_ty
2293_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2294{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002295 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002296 assert(len > 0);
2297
Pablo Galindoa5634c42020-09-16 19:42:00 +01002298 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2299 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002300
2301 int bytesmode = 0;
2302 PyObject *bytes_str = NULL;
2303
2304 FstringParser state;
2305 _PyPegen_FstringParser_Init(&state);
2306
2307 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002308 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002309
2310 int this_bytesmode;
2311 int this_rawmode;
2312 PyObject *s;
2313 const char *fstr;
2314 Py_ssize_t fstrlen = -1;
2315
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002316 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002317 goto error;
2318 }
2319
2320 /* Check that we are not mixing bytes with unicode. */
2321 if (i != 0 && bytesmode != this_bytesmode) {
2322 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2323 Py_XDECREF(s);
2324 goto error;
2325 }
2326 bytesmode = this_bytesmode;
2327
2328 if (fstr != NULL) {
2329 assert(s == NULL && !bytesmode);
2330
2331 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2332 this_rawmode, 0, first, t, last);
2333 if (result < 0) {
2334 goto error;
2335 }
2336 }
2337 else {
2338 /* String or byte string. */
2339 assert(s != NULL && fstr == NULL);
2340 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2341
2342 if (bytesmode) {
2343 if (i == 0) {
2344 bytes_str = s;
2345 }
2346 else {
2347 PyBytes_ConcatAndDel(&bytes_str, s);
2348 if (!bytes_str) {
2349 goto error;
2350 }
2351 }
2352 }
2353 else {
2354 /* This is a regular string. Concatenate it. */
2355 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2356 goto error;
2357 }
2358 }
2359 }
2360 }
2361
2362 if (bytesmode) {
Victor Stinner8370e072021-03-24 02:23:01 +01002363 if (_PyArena_AddPyObject(p->arena, bytes_str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002364 goto error;
2365 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002366 return _PyAST_Constant(bytes_str, NULL, first->lineno,
2367 first->col_offset, last->end_lineno,
2368 last->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002369 }
2370
2371 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2372
2373error:
2374 Py_XDECREF(bytes_str);
2375 _PyPegen_FstringParser_Dealloc(&state);
2376 if (PyErr_Occurred()) {
2377 raise_decode_error(p);
2378 }
2379 return NULL;
2380}
Guido van Rossumc001c092020-04-30 12:12:19 -07002381
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002382expr_ty
2383_PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
2384{
2385 if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07002386 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
2387 return NULL;
2388 }
2389 return exp;
2390}
2391
2392expr_ty
2393_PyPegen_ensure_real(Parser *p, expr_ty exp)
2394{
2395 if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
2396 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002397 return NULL;
2398 }
2399 return exp;
2400}
2401
Guido van Rossumc001c092020-04-30 12:12:19 -07002402mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002403_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2404 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002405 Py_ssize_t num = p->type_ignore_comments.num_items;
2406 if (num > 0) {
2407 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002408 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002409 if (type_ignores == NULL) {
2410 return NULL;
2411 }
2412 for (int i = 0; i < num; i++) {
2413 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2414 if (tag == NULL) {
2415 return NULL;
2416 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002417 type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
2418 tag, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002419 if (ti == NULL) {
2420 return NULL;
2421 }
2422 asdl_seq_SET(type_ignores, i, ti);
2423 }
2424 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002425 return _PyAST_Module(a, type_ignores, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002426}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002427
2428// Error reporting helpers
2429
2430expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002431_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002432{
2433 if (e == NULL) {
2434 return NULL;
2435 }
2436
2437#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
Pablo Galindo58bafe42021-04-09 01:17:31 +01002438 Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002439 for (Py_ssize_t i = 0; i < len; i++) {\
Pablo Galindo58bafe42021-04-09 01:17:31 +01002440 expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002441 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002442 if (child != NULL) {\
2443 return child;\
2444 }\
2445 }\
2446 } while (0)
2447
2448 // We only need to visit List and Tuple nodes recursively as those
2449 // are the only ones that can contain valid names in targets when
2450 // they are parsed as expressions. Any other kind of expression
2451 // that is a container (like Sets or Dicts) is directly invalid and
2452 // we don't need to visit it recursively.
2453
2454 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002455 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002456 VISIT_CONTAINER(e, List);
2457 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002458 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002459 VISIT_CONTAINER(e, Tuple);
2460 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002461 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002462 if (targets_type == DEL_TARGETS) {
2463 return e;
2464 }
2465 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2466 case Compare_kind:
2467 // This is needed, because the `a in b` in `for a in b` gets parsed
2468 // as a comparison, and so we need to search the left side of the comparison
2469 // for invalid targets.
2470 if (targets_type == FOR_TARGETS) {
2471 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2472 if (cmpop == In) {
2473 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2474 }
2475 return NULL;
2476 }
2477 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002478 case Name_kind:
2479 case Subscript_kind:
2480 case Attribute_kind:
2481 return NULL;
2482 default:
2483 return e;
2484 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002485}
2486
2487void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2488 int kwarg_unpacking = 0;
2489 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2490 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2491 if (!keyword->arg) {
2492 kwarg_unpacking = 1;
2493 }
2494 }
2495
2496 const char *msg = NULL;
2497 if (kwarg_unpacking) {
2498 msg = "positional argument follows keyword argument unpacking";
2499 } else {
2500 msg = "positional argument follows keyword argument";
2501 }
2502
2503 return RAISE_SYNTAX_ERROR(msg);
2504}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002505
2506void *
2507_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2508{
2509 /* The rule that calls this function is 'args for_if_clauses'.
2510 For the input f(L, x for x in y), L and x are in args and
2511 the for is parsed as a for_if_clause. We have to check if
2512 len <= 1, so that input like dict((a, b) for a, b in x)
2513 gets successfully parsed and then we pass the last
2514 argument (x in the above example) as the location of the
2515 error */
2516 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2517 if (len <= 1) {
2518 return NULL;
2519 }
2520
Pablo Galindoa77aac42021-04-23 14:27:05 +01002521 return RAISE_SYNTAX_ERROR_STARTING_FROM(
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002522 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2523 "Generator expression must be parenthesized"
2524 );
2525}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002526
2527
Pablo Galindoa5634c42020-09-16 19:42:00 +01002528expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002529 int lineno, int col_offset, int end_lineno,
2530 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002531 Py_ssize_t args_len = asdl_seq_LEN(a);
2532 Py_ssize_t total_len = args_len;
2533
2534 if (b == NULL) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002535 return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002536 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002537
2538 }
2539
Pablo Galindoa5634c42020-09-16 19:42:00 +01002540 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2541 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002542
2543 if (starreds) {
2544 total_len += asdl_seq_LEN(starreds);
2545 }
2546
Pablo Galindoa5634c42020-09-16 19:42:00 +01002547 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002548
2549 Py_ssize_t i = 0;
2550 for (i = 0; i < args_len; i++) {
2551 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2552 }
2553 for (; i < total_len; i++) {
2554 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2555 }
2556
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002557 return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2558 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002559}