blob: 615047c1b6a00731b756d0b5bbc49d9efad0e2a6 [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 *
Serhiy Storchakac43317d2021-06-12 20:44:32 +030010_PyPegen_new_type_comment(Parser *p, const char *s)
Guido van Rossumc001c092020-04-30 12:12:19 -070011{
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 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +030029 const char *bytes = PyBytes_AsString(tc->bytes);
Guido van Rossumc001c092020-04-30 12:12:19 -070030 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
Serhiy Storchakac43317d2021-06-12 20:44:32 +030069 const 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 *
Serhiy Storchakac43317d2021-06-12 20:44:32 +030081_PyPegen_new_identifier(Parser *p, const char *n)
Pablo Galindoc5fc1562020-04-22 23:29:27 +010082{
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)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700286 || PyErr_ExceptionMatches(PyExc_SyntaxError)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100287 || PyErr_ExceptionMatches(PyExc_ValueError)
288 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
289 return;
290 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300291 PyObject *errstr = NULL;
292 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100293 PyObject *type;
294 PyObject *value;
295 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100296 PyErr_Fetch(&type, &value, &tback);
297 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300298 if (!errstr) {
299 goto error;
300 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100301
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300302 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100303 if (!tmp) {
304 goto error;
305 }
306
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300307 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308 Py_DECREF(tmp);
309 if (!value) {
310 goto error;
311 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300312 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100313
314error:
315 Py_XDECREF(type);
316 Py_XDECREF(value);
317 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300318 Py_XDECREF(errstr);
319 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320}
321
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100322static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100323tokenizer_error(Parser *p)
324{
325 if (PyErr_Occurred()) {
326 return -1;
327 }
328
329 const char *msg = NULL;
330 PyObject* errtype = PyExc_SyntaxError;
Pablo Galindo96eeff52021-03-22 17:28:11 +0000331 Py_ssize_t col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332 switch (p->tok->done) {
333 case E_TOKEN:
334 msg = "invalid token";
335 break;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300336 case E_EOF:
Pablo Galindod6d63712021-01-19 23:59:33 +0000337 if (p->tok->level) {
338 raise_unclosed_parentheses_error(p);
339 } else {
340 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
341 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300342 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100343 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300344 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
345 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100346 case E_INTR:
347 if (!PyErr_Occurred()) {
348 PyErr_SetNone(PyExc_KeyboardInterrupt);
349 }
350 return -1;
351 case E_NOMEM:
352 PyErr_NoMemory();
353 return -1;
354 case E_TABSPACE:
355 errtype = PyExc_TabError;
356 msg = "inconsistent use of tabs and spaces in indentation";
357 break;
358 case E_TOODEEP:
359 errtype = PyExc_IndentationError;
360 msg = "too many levels of indentation";
361 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100362 case E_LINECONT:
Pablo Galindo96eeff52021-03-22 17:28:11 +0000363 col_offset = strlen(strtok(p->tok->buf, "\n")) - 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100364 msg = "unexpected character after line continuation character";
365 break;
366 default:
367 msg = "unknown parsing error";
368 }
369
Pablo Galindoa77aac42021-04-23 14:27:05 +0100370 RAISE_ERROR_KNOWN_LOCATION(p, errtype, p->tok->lineno, col_offset, p->tok->lineno, -1, msg);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100371 return -1;
372}
373
374void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300375_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
376{
377 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100378 Py_ssize_t col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100379 Py_ssize_t end_col_offset = -1;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300380 if (t->col_offset == -1) {
381 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
382 intptr_t, int);
383 } else {
384 col_offset = t->col_offset + 1;
385 }
386
Pablo Galindoa77aac42021-04-23 14:27:05 +0100387 if (t->end_col_offset != -1) {
388 end_col_offset = t->end_col_offset + 1;
389 }
390
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300391 va_list va;
392 va_start(va, errmsg);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100393 _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 +0300394 va_end(va);
395
396 return NULL;
397}
398
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200399static PyObject *
400get_error_line(Parser *p, Py_ssize_t lineno)
401{
Pablo Galindo123ff262021-03-22 16:24:39 +0000402 /* If the file descriptor is interactive, the source lines of the current
403 * (multi-line) statement are stored in p->tok->interactive_src_start.
404 * If not, we're parsing from a string, which means that the whole source
405 * is stored in p->tok->str. */
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200406 assert(p->tok->fp == NULL || p->tok->fp == stdin);
407
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100408 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
409
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200410 for (int i = 0; i < lineno - 1; i++) {
411 cur_line = strchr(cur_line, '\n') + 1;
412 }
413
414 char *next_newline;
415 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
416 next_newline = cur_line + strlen(cur_line);
417 }
418 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
419}
420
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300421void *
422_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100423 Py_ssize_t lineno, Py_ssize_t col_offset,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100424 Py_ssize_t end_lineno, Py_ssize_t end_col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300425 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100426{
427 PyObject *value = NULL;
428 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300429 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100430 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300431 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100432
Pablo Galindoa77aac42021-04-23 14:27:05 +0100433 if (end_lineno == CURRENT_POS) {
434 end_lineno = p->tok->lineno;
435 }
436 if (end_col_offset == CURRENT_POS) {
437 end_col_offset = p->tok->cur - p->tok->line_start;
438 }
439
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300440 if (p->start_rule == Py_fstring_input) {
441 const char *fstring_msg = "f-string: ";
442 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
443
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300444 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300445 if (!new_errmsg) {
446 return (void *) PyErr_NoMemory();
447 }
448
449 // Copy both strings into new buffer
450 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
451 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
452 new_errmsg[len] = 0;
453 errmsg = new_errmsg;
454 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100455 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100456 if (!errstr) {
457 goto error;
458 }
459
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700460 // PyErr_ProgramTextObject assumes that the text is utf-8 so we cannot call it with a file
461 // with an arbitrary encoding or otherwise we could get some badly decoded text.
462 int uses_utf8_codec = (!p->tok->encoding || strcmp(p->tok->encoding, "utf-8") == 0);
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100463 if (p->tok->fp_interactive) {
464 error_line = get_error_line(p, lineno);
465 }
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700466 else if (uses_utf8_codec && p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300467 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100468 }
469
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300470 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200471 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
472 then we need to find the error line from some other source, because
473 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
474 failed or we're parsing from a string or the REPL. There's a third edge case where
475 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
476 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
477 does not physically exist */
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700478 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF || !uses_utf8_codec);
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200479
Pablo Galindo40901512021-01-31 22:48:23 +0000480 if (p->tok->lineno <= lineno) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200481 Py_ssize_t size = p->tok->inp - p->tok->buf;
482 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
483 }
484 else {
485 error_line = get_error_line(p, lineno);
486 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300487 if (!error_line) {
488 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300489 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100490 }
491
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300492 if (p->start_rule == Py_fstring_input) {
493 col_offset -= p->starting_col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100494 end_col_offset -= p->starting_col_offset;
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300495 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100496
Pablo Galindo51c58962020-06-16 16:49:43 +0100497 Py_ssize_t col_number = col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100498 Py_ssize_t end_col_number = end_col_offset;
Pablo Galindo51c58962020-06-16 16:49:43 +0100499
500 if (p->tok->encoding != NULL) {
501 col_number = byte_offset_to_character_offset(error_line, col_offset);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100502 end_col_number = end_col_number > 0 ?
503 byte_offset_to_character_offset(error_line, end_col_offset) :
504 end_col_number;
Pablo Galindo51c58962020-06-16 16:49:43 +0100505 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100506 tmp = Py_BuildValue("(OiiNii)", p->tok->filename, lineno, col_number, error_line, end_lineno, end_col_number);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100507 if (!tmp) {
508 goto error;
509 }
510 value = PyTuple_Pack(2, errstr, tmp);
511 Py_DECREF(tmp);
512 if (!value) {
513 goto error;
514 }
515 PyErr_SetObject(errtype, value);
516
517 Py_DECREF(errstr);
518 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300519 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300520 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300521 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100522 return NULL;
523
524error:
525 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300526 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300527 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300528 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300529 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100530 return NULL;
531}
532
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100533#if 0
534static const char *
535token_name(int type)
536{
537 if (0 <= type && type <= N_TOKENS) {
538 return _PyParser_TokenNames[type];
539 }
540 return "<Huh?>";
541}
542#endif
543
544// Here, mark is the start of the node, while p->mark is the end.
545// If node==NULL, they should be the same.
546int
547_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
548{
549 // Insert in front
Victor Stinner8370e072021-03-24 02:23:01 +0100550 Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100551 if (m == NULL) {
552 return -1;
553 }
554 m->type = type;
555 m->node = node;
556 m->mark = p->mark;
557 m->next = p->tokens[mark]->memo;
558 p->tokens[mark]->memo = m;
559 return 0;
560}
561
562// Like _PyPegen_insert_memo(), but updates an existing node if found.
563int
564_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
565{
566 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
567 if (m->type == type) {
568 // Update existing node.
569 m->node = node;
570 m->mark = p->mark;
571 return 0;
572 }
573 }
574 // Insert new node.
575 return _PyPegen_insert_memo(p, mark, type, node);
576}
577
578// Return dummy NAME.
579void *
580_PyPegen_dummy_name(Parser *p, ...)
581{
582 static void *cache = NULL;
583
584 if (cache != NULL) {
585 return cache;
586 }
587
588 PyObject *id = _create_dummy_identifier(p);
589 if (!id) {
590 return NULL;
591 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200592 cache = _PyAST_Name(id, Load, 1, 0, 1, 0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100593 return cache;
594}
595
596static int
597_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
598{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300599 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100600 if (name_len >= p->n_keyword_lists ||
601 p->keywords[name_len] == NULL ||
602 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100603 return NAME;
604 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100605 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100606 if (strncmp(k->str, name, name_len) == 0) {
607 return k->type;
608 }
609 }
610 return NAME;
611}
612
Guido van Rossumc001c092020-04-30 12:12:19 -0700613static int
614growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
615 assert(initial_size > 0);
616 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
617 arr->size = initial_size;
618 arr->num_items = 0;
619
620 return arr->items != NULL;
621}
622
623static int
624growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
625 if (arr->num_items >= arr->size) {
626 size_t new_size = arr->size * 2;
627 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
628 if (!new_items_array) {
629 return 0;
630 }
631 arr->items = new_items_array;
632 arr->size = new_size;
633 }
634
635 arr->items[arr->num_items].lineno = lineno;
636 arr->items[arr->num_items].comment = comment; // Take ownership
637 arr->num_items++;
638 return 1;
639}
640
641static void
642growable_comment_array_deallocate(growable_comment_array *arr) {
643 for (unsigned i = 0; i < arr->num_items; i++) {
644 PyMem_Free(arr->items[i].comment);
645 }
646 PyMem_Free(arr->items);
647}
648
Pablo Galindod00a4492021-04-09 01:32:25 +0100649static int
650initialize_token(Parser *p, Token *token, const char *start, const char *end, int token_type) {
651 assert(token != NULL);
652
653 token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : token_type;
654 token->bytes = PyBytes_FromStringAndSize(start, end - start);
655 if (token->bytes == NULL) {
656 return -1;
657 }
658
659 if (_PyArena_AddPyObject(p->arena, token->bytes) < 0) {
660 Py_DECREF(token->bytes);
661 return -1;
662 }
663
664 const char *line_start = token_type == STRING ? p->tok->multi_line_start : p->tok->line_start;
665 int lineno = token_type == STRING ? p->tok->first_lineno : p->tok->lineno;
666 int end_lineno = p->tok->lineno;
667
668 int col_offset = (start != NULL && start >= line_start) ? (int)(start - line_start) : -1;
669 int end_col_offset = (end != NULL && end >= p->tok->line_start) ? (int)(end - p->tok->line_start) : -1;
670
671 token->lineno = p->starting_lineno + lineno;
672 token->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
673 token->end_lineno = p->starting_lineno + end_lineno;
674 token->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
675
676 p->fill += 1;
677
678 if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
679 return raise_decode_error(p);
680 }
681
682 return (token_type == ERRORTOKEN ? tokenizer_error(p) : 0);
683}
684
685static int
686_resize_tokens_array(Parser *p) {
687 int newsize = p->size * 2;
688 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
689 if (new_tokens == NULL) {
690 PyErr_NoMemory();
691 return -1;
692 }
693 p->tokens = new_tokens;
694
695 for (int i = p->size; i < newsize; i++) {
696 p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
697 if (p->tokens[i] == NULL) {
698 p->size = i; // Needed, in order to cleanup correctly after parser fails
699 PyErr_NoMemory();
700 return -1;
701 }
702 }
703 p->size = newsize;
704 return 0;
705}
706
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100707int
708_PyPegen_fill_token(Parser *p)
709{
Pablo Galindofb61c422020-06-15 14:23:43 +0100710 const char *start;
711 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100712 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700713
714 // Record and skip '# type: ignore' comments
715 while (type == TYPE_IGNORE) {
716 Py_ssize_t len = end - start;
717 char *tag = PyMem_Malloc(len + 1);
718 if (tag == NULL) {
719 PyErr_NoMemory();
720 return -1;
721 }
722 strncpy(tag, start, len);
723 tag[len] = '\0';
724 // Ownership of tag passes to the growable array
725 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
726 PyErr_NoMemory();
727 return -1;
728 }
729 type = PyTokenizer_Get(p->tok, &start, &end);
730 }
731
Pablo Galindod00a4492021-04-09 01:32:25 +0100732 // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
733 if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100734 type = NEWLINE; /* Add an extra newline */
735 p->parsing_started = 0;
736
Pablo Galindob94dbd72020-04-27 18:35:58 +0100737 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100738 p->tok->pendin = -p->tok->indent;
739 p->tok->indent = 0;
740 }
741 }
742 else {
743 p->parsing_started = 1;
744 }
745
Pablo Galindod00a4492021-04-09 01:32:25 +0100746 // Check if we are at the limit of the token array capacity and resize if needed
747 if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
748 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100749 }
750
751 Token *t = p->tokens[p->fill];
Pablo Galindod00a4492021-04-09 01:32:25 +0100752 return initialize_token(p, t, start, end, type);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100753}
754
Pablo Galindo58bafe42021-04-09 01:17:31 +0100755
756#if defined(Py_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100757// Instrumentation to count the effectiveness of memoization.
758// The array counts the number of tokens skipped by memoization,
759// indexed by type.
760
761#define NSTATISTICS 2000
762static long memo_statistics[NSTATISTICS];
763
764void
765_PyPegen_clear_memo_statistics()
766{
767 for (int i = 0; i < NSTATISTICS; i++) {
768 memo_statistics[i] = 0;
769 }
770}
771
772PyObject *
773_PyPegen_get_memo_statistics()
774{
775 PyObject *ret = PyList_New(NSTATISTICS);
776 if (ret == NULL) {
777 return NULL;
778 }
779 for (int i = 0; i < NSTATISTICS; i++) {
780 PyObject *value = PyLong_FromLong(memo_statistics[i]);
781 if (value == NULL) {
782 Py_DECREF(ret);
783 return NULL;
784 }
785 // PyList_SetItem borrows a reference to value.
786 if (PyList_SetItem(ret, i, value) < 0) {
787 Py_DECREF(ret);
788 return NULL;
789 }
790 }
791 return ret;
792}
Pablo Galindo58bafe42021-04-09 01:17:31 +0100793#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100794
795int // bool
796_PyPegen_is_memoized(Parser *p, int type, void *pres)
797{
798 if (p->mark == p->fill) {
799 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300800 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100801 return -1;
802 }
803 }
804
805 Token *t = p->tokens[p->mark];
806
807 for (Memo *m = t->memo; m != NULL; m = m->next) {
808 if (m->type == type) {
Pablo Galindo58bafe42021-04-09 01:17:31 +0100809#if defined(PY_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100810 if (0 <= type && type < NSTATISTICS) {
811 long count = m->mark - p->mark;
812 // A memoized negative result counts for one.
813 if (count <= 0) {
814 count = 1;
815 }
816 memo_statistics[type] += count;
817 }
Pablo Galindo58bafe42021-04-09 01:17:31 +0100818#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100819 p->mark = m->mark;
820 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100821 return 1;
822 }
823 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100824 return 0;
825}
826
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100827int
828_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
829{
830 int mark = p->mark;
831 void *res = func(p);
832 p->mark = mark;
833 return (res != NULL) == positive;
834}
835
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100836int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100837_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
838{
839 int mark = p->mark;
840 void *res = func(p, arg);
841 p->mark = mark;
842 return (res != NULL) == positive;
843}
844
845int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100846_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
847{
848 int mark = p->mark;
849 void *res = func(p, arg);
850 p->mark = mark;
851 return (res != NULL) == positive;
852}
853
854int
855_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
856{
857 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100858 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100859 p->mark = mark;
860 return (res != NULL) == positive;
861}
862
863Token *
864_PyPegen_expect_token(Parser *p, int type)
865{
866 if (p->mark == p->fill) {
867 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300868 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100869 return NULL;
870 }
871 }
872 Token *t = p->tokens[p->mark];
873 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100874 return NULL;
875 }
876 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100877 return t;
878}
879
Pablo Galindo58fb1562021-02-02 19:54:22 +0000880Token *
881_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
882
883 if (p->error_indicator == 1) {
884 return NULL;
885 }
886
887 if (p->mark == p->fill) {
888 if (_PyPegen_fill_token(p) < 0) {
889 p->error_indicator = 1;
890 return NULL;
891 }
892 }
893 Token *t = p->tokens[p->mark];
894 if (t->type != type) {
895 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
896 return NULL;
897 }
898 p->mark += 1;
899 return t;
900}
901
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700902expr_ty
903_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
904{
905 if (p->mark == p->fill) {
906 if (_PyPegen_fill_token(p) < 0) {
907 p->error_indicator = 1;
908 return NULL;
909 }
910 }
911 Token *t = p->tokens[p->mark];
912 if (t->type != NAME) {
913 return NULL;
914 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +0300915 const char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700916 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300917 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700918 return NULL;
919 }
920 if (strcmp(s, keyword) != 0) {
921 return NULL;
922 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300923 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700924}
925
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100926Token *
927_PyPegen_get_last_nonnwhitespace_token(Parser *p)
928{
929 assert(p->mark >= 0);
930 Token *token = NULL;
931 for (int m = p->mark - 1; m >= 0; m--) {
932 token = p->tokens[m];
933 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
934 break;
935 }
936 }
937 return token;
938}
939
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700940static expr_ty
941_PyPegen_name_from_token(Parser *p, Token* t)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100942{
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100943 if (t == NULL) {
944 return NULL;
945 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +0300946 const char *s = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100947 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
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700960
961expr_ty
962_PyPegen_name_token(Parser *p)
963{
964 Token *t = _PyPegen_expect_token(p, NAME);
965 return _PyPegen_name_from_token(p, t);
966}
967
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100968void *
969_PyPegen_string_token(Parser *p)
970{
971 return _PyPegen_expect_token(p, STRING);
972}
973
Pablo Galindob2802482021-04-15 21:38:45 +0100974
975expr_ty _PyPegen_soft_keyword_token(Parser *p) {
976 Token *t = _PyPegen_expect_token(p, NAME);
977 if (t == NULL) {
978 return NULL;
979 }
980 char *the_token;
981 Py_ssize_t size;
982 PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
983 for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
984 if (strncmp(*keyword, the_token, size) == 0) {
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700985 return _PyPegen_name_from_token(p, t);
Pablo Galindob2802482021-04-15 21:38:45 +0100986 }
987 }
988 return NULL;
989}
990
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100991static PyObject *
992parsenumber_raw(const char *s)
993{
994 const char *end;
995 long x;
996 double dx;
997 Py_complex compl;
998 int imflag;
999
1000 assert(s != NULL);
1001 errno = 0;
1002 end = s + strlen(s) - 1;
1003 imflag = *end == 'j' || *end == 'J';
1004 if (s[0] == '0') {
1005 x = (long)PyOS_strtoul(s, (char **)&end, 0);
1006 if (x < 0 && errno == 0) {
1007 return PyLong_FromString(s, (char **)0, 0);
1008 }
1009 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001010 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001011 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001012 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001013 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +01001014 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001015 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001016 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001017 return PyLong_FromLong(x);
1018 }
1019 /* XXX Huge floats may silently fail */
1020 if (imflag) {
1021 compl.real = 0.;
1022 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +01001023 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001024 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +01001025 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001026 return PyComplex_FromCComplex(compl);
1027 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001028 dx = PyOS_string_to_double(s, NULL, NULL);
1029 if (dx == -1.0 && PyErr_Occurred()) {
1030 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001031 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001032 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001033}
1034
1035static PyObject *
1036parsenumber(const char *s)
1037{
Pablo Galindofb61c422020-06-15 14:23:43 +01001038 char *dup;
1039 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001040 PyObject *res = NULL;
1041
1042 assert(s != NULL);
1043
1044 if (strchr(s, '_') == NULL) {
1045 return parsenumber_raw(s);
1046 }
1047 /* Create a duplicate without underscores. */
1048 dup = PyMem_Malloc(strlen(s) + 1);
1049 if (dup == NULL) {
1050 return PyErr_NoMemory();
1051 }
1052 end = dup;
1053 for (; *s; s++) {
1054 if (*s != '_') {
1055 *end++ = *s;
1056 }
1057 }
1058 *end = '\0';
1059 res = parsenumber_raw(dup);
1060 PyMem_Free(dup);
1061 return res;
1062}
1063
1064expr_ty
1065_PyPegen_number_token(Parser *p)
1066{
1067 Token *t = _PyPegen_expect_token(p, NUMBER);
1068 if (t == NULL) {
1069 return NULL;
1070 }
1071
Serhiy Storchakac43317d2021-06-12 20:44:32 +03001072 const char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001073 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001074 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001075 return NULL;
1076 }
1077
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001078 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1079 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -07001080 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001081 "in Python 3.6 and greater");
1082 }
1083
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001084 PyObject *c = parsenumber(num_raw);
1085
1086 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001087 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001088 return NULL;
1089 }
1090
Victor Stinner8370e072021-03-24 02:23:01 +01001091 if (_PyArena_AddPyObject(p->arena, c) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001092 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001093 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001094 return NULL;
1095 }
1096
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001097 return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
1098 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001099}
1100
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001101static int // bool
1102newline_in_string(Parser *p, const char *cur)
1103{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001104 for (const char *c = cur; c >= p->tok->buf; c--) {
1105 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001106 return 1;
1107 }
1108 }
1109 return 0;
1110}
1111
1112/* Check that the source for a single input statement really is a single
1113 statement by looking at what is left in the buffer after parsing.
1114 Trailing whitespace and comments are OK. */
1115static int // bool
1116bad_single_statement(Parser *p)
1117{
1118 const char *cur = strchr(p->tok->buf, '\n');
1119
1120 /* Newlines are allowed if preceded by a line continuation character
1121 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001122 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1123 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001124 return 0;
1125 }
1126 char c = *cur;
1127
1128 for (;;) {
1129 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1130 c = *++cur;
1131 }
1132
1133 if (!c) {
1134 return 0;
1135 }
1136
1137 if (c != '#') {
1138 return 1;
1139 }
1140
1141 /* Suck up comment. */
1142 while (c && c != '\n') {
1143 c = *++cur;
1144 }
1145 }
1146}
1147
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001148void
1149_PyPegen_Parser_Free(Parser *p)
1150{
1151 Py_XDECREF(p->normalize);
1152 for (int i = 0; i < p->size; i++) {
1153 PyMem_Free(p->tokens[i]);
1154 }
1155 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001156 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001157 PyMem_Free(p);
1158}
1159
Pablo Galindo2b74c832020-04-27 18:02:07 +01001160static int
1161compute_parser_flags(PyCompilerFlags *flags)
1162{
1163 int parser_flags = 0;
1164 if (!flags) {
1165 return 0;
1166 }
1167 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1168 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1169 }
1170 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1171 parser_flags |= PyPARSE_IGNORE_COOKIE;
1172 }
1173 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1174 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1175 }
1176 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1177 parser_flags |= PyPARSE_TYPE_COMMENTS;
1178 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001179 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001180 parser_flags |= PyPARSE_ASYNC_HACKS;
1181 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001182 return parser_flags;
1183}
1184
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001185Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001186_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001187 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001188{
1189 Parser *p = PyMem_Malloc(sizeof(Parser));
1190 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001191 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001192 }
1193 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001194 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1195 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001196 p->tok = tok;
1197 p->keywords = NULL;
1198 p->n_keyword_lists = -1;
Pablo Galindob2802482021-04-15 21:38:45 +01001199 p->soft_keywords = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001200 p->tokens = PyMem_Malloc(sizeof(Token *));
1201 if (!p->tokens) {
1202 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001203 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001204 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001205 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001206 if (!p->tokens) {
1207 PyMem_Free(p->tokens);
1208 PyMem_Free(p);
1209 return (Parser *) PyErr_NoMemory();
1210 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001211 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1212 PyMem_Free(p->tokens[0]);
1213 PyMem_Free(p->tokens);
1214 PyMem_Free(p);
1215 return (Parser *) PyErr_NoMemory();
1216 }
1217
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001218 p->mark = 0;
1219 p->fill = 0;
1220 p->size = 1;
1221
1222 p->errcode = errcode;
1223 p->arena = arena;
1224 p->start_rule = start_rule;
1225 p->parsing_started = 0;
1226 p->normalize = NULL;
1227 p->error_indicator = 0;
1228
1229 p->starting_lineno = 0;
1230 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001231 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001232 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001233 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001234 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001235 p->call_invalid_rules = 0;
Miss Islington (bot)ae1732d2021-05-21 11:20:43 -07001236 p->in_raw_rule = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001237 return p;
1238}
1239
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001240static void
1241reset_parser_state(Parser *p)
1242{
1243 for (int i = 0; i < p->fill; i++) {
1244 p->tokens[i]->memo = NULL;
1245 }
1246 p->mark = 0;
1247 p->call_invalid_rules = 1;
Miss Islington (bot)1fb6b9e2021-05-22 15:23:26 -07001248 // Don't try to get extra tokens in interactive mode when trying to
1249 // raise specialized errors in the second pass.
1250 p->tok->interactive_underflow = IUNDERFLOW_STOP;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001251}
1252
Pablo Galindod6d63712021-01-19 23:59:33 +00001253static int
1254_PyPegen_check_tokenizer_errors(Parser *p) {
1255 // Tokenize the whole input to see if there are any tokenization
1256 // errors such as mistmatching parentheses. These will get priority
1257 // over generic syntax errors only if the line number of the error is
1258 // before the one that we had for the generic error.
1259
1260 // We don't want to tokenize to the end for interactive input
1261 if (p->tok->prompt != NULL) {
1262 return 0;
1263 }
1264
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001265 PyObject *type, *value, *traceback;
1266 PyErr_Fetch(&type, &value, &traceback);
1267
Pablo Galindod6d63712021-01-19 23:59:33 +00001268 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1269 Py_ssize_t current_err_line = current_token->lineno;
1270
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001271 int ret = 0;
1272
Pablo Galindod6d63712021-01-19 23:59:33 +00001273 for (;;) {
1274 const char *start;
1275 const char *end;
1276 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1277 case ERRORTOKEN:
1278 if (p->tok->level != 0) {
1279 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1280 if (current_err_line > error_lineno) {
1281 raise_unclosed_parentheses_error(p);
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001282 ret = -1;
1283 goto exit;
Pablo Galindod6d63712021-01-19 23:59:33 +00001284 }
1285 }
1286 break;
1287 case ENDMARKER:
1288 break;
1289 default:
1290 continue;
1291 }
1292 break;
1293 }
1294
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001295
1296exit:
1297 if (PyErr_Occurred()) {
1298 Py_XDECREF(value);
1299 Py_XDECREF(type);
1300 Py_XDECREF(traceback);
1301 } else {
1302 PyErr_Restore(type, value, traceback);
1303 }
1304 return ret;
Pablo Galindod6d63712021-01-19 23:59:33 +00001305}
1306
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001307void *
1308_PyPegen_run_parser(Parser *p)
1309{
1310 void *res = _PyPegen_parse(p);
1311 if (res == NULL) {
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001312 Token *last_token = p->tokens[p->fill - 1];
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001313 reset_parser_state(p);
1314 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001315 if (PyErr_Occurred()) {
Miss Islington (bot)933b5b62021-06-08 04:46:56 -07001316 // Prioritize tokenizer errors to custom syntax errors raised
1317 // on the second phase only if the errors come from the parser.
1318 if (p->tok->done != E_ERROR && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
Miss Islington (bot)756b7b92021-05-03 18:06:45 -07001319 _PyPegen_check_tokenizer_errors(p);
1320 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001321 return NULL;
1322 }
1323 if (p->fill == 0) {
1324 RAISE_SYNTAX_ERROR("error at start before reading any input");
1325 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001326 else if (p->tok->done == E_EOF) {
Pablo Galindod6d63712021-01-19 23:59:33 +00001327 if (p->tok->level) {
1328 raise_unclosed_parentheses_error(p);
1329 } else {
1330 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1331 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001332 }
1333 else {
1334 if (p->tokens[p->fill-1]->type == INDENT) {
1335 RAISE_INDENTATION_ERROR("unexpected indent");
1336 }
1337 else if (p->tokens[p->fill-1]->type == DEDENT) {
1338 RAISE_INDENTATION_ERROR("unexpected unindent");
1339 }
1340 else {
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001341 // Use the last token we found on the first pass to avoid reporting
1342 // incorrect locations for generic syntax errors just because we reached
1343 // further away when trying to find specific syntax errors in the second
1344 // pass.
1345 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(last_token, "invalid syntax");
Pablo Galindoc3f167d2021-01-20 19:11:56 +00001346 // _PyPegen_check_tokenizer_errors will override the existing
1347 // generic SyntaxError we just raised if errors are found.
1348 _PyPegen_check_tokenizer_errors(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001349 }
1350 }
1351 return NULL;
1352 }
1353
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001354 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1355 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1356 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1357 }
1358
Victor Stinnere0bf70d2021-03-18 02:46:06 +01001359 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1360#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
Pablo Galindo13322262020-07-27 23:46:59 +01001361 if (p->start_rule == Py_single_input ||
1362 p->start_rule == Py_file_input ||
1363 p->start_rule == Py_eval_input)
1364 {
Victor Stinnereec8e612021-03-18 14:57:49 +01001365 if (!_PyAST_Validate(res)) {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001366 return NULL;
1367 }
Pablo Galindo13322262020-07-27 23:46:59 +01001368 }
1369#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001370 return res;
1371}
1372
1373mod_ty
1374_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1375 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001376 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001377{
1378 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1379 if (tok == NULL) {
1380 if (PyErr_Occurred()) {
1381 raise_tokenizer_init_error(filename_ob);
1382 return NULL;
1383 }
1384 return NULL;
1385 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001386 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1387 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1388 tok->fp_interactive = 1;
1389 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001390 // This transfers the ownership to the tokenizer
1391 tok->filename = filename_ob;
1392 Py_INCREF(filename_ob);
1393
1394 // From here on we need to clean up even if there's an error
1395 mod_ty result = NULL;
1396
Pablo Galindo2b74c832020-04-27 18:02:07 +01001397 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001398 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1399 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001400 if (p == NULL) {
1401 goto error;
1402 }
1403
1404 result = _PyPegen_run_parser(p);
1405 _PyPegen_Parser_Free(p);
1406
1407error:
1408 PyTokenizer_Free(tok);
1409 return result;
1410}
1411
1412mod_ty
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001413_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001414 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001415{
1416 int exec_input = start_rule == Py_file_input;
1417
1418 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001419 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001420 tok = PyTokenizer_FromUTF8(str, exec_input);
1421 } else {
1422 tok = PyTokenizer_FromString(str, exec_input);
1423 }
1424 if (tok == NULL) {
1425 if (PyErr_Occurred()) {
1426 raise_tokenizer_init_error(filename_ob);
1427 }
1428 return NULL;
1429 }
1430 // This transfers the ownership to the tokenizer
1431 tok->filename = filename_ob;
1432 Py_INCREF(filename_ob);
1433
1434 // We need to clear up from here on
1435 mod_ty result = NULL;
1436
Pablo Galindo2b74c832020-04-27 18:02:07 +01001437 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001438 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1439 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001440 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1441 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001442 if (p == NULL) {
1443 goto error;
1444 }
1445
1446 result = _PyPegen_run_parser(p);
1447 _PyPegen_Parser_Free(p);
1448
1449error:
1450 PyTokenizer_Free(tok);
1451 return result;
1452}
1453
Pablo Galindoa5634c42020-09-16 19:42:00 +01001454asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001455_PyPegen_interactive_exit(Parser *p)
1456{
1457 if (p->errcode) {
1458 *(p->errcode) = E_EOF;
1459 }
1460 return NULL;
1461}
1462
1463/* Creates a single-element asdl_seq* that contains a */
1464asdl_seq *
1465_PyPegen_singleton_seq(Parser *p, void *a)
1466{
1467 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001468 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001469 if (!seq) {
1470 return NULL;
1471 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001472 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001473 return seq;
1474}
1475
1476/* Creates a copy of seq and prepends a to it */
1477asdl_seq *
1478_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1479{
1480 assert(a != NULL);
1481 if (!seq) {
1482 return _PyPegen_singleton_seq(p, a);
1483 }
1484
Pablo Galindoa5634c42020-09-16 19:42:00 +01001485 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 +01001486 if (!new_seq) {
1487 return NULL;
1488 }
1489
Pablo Galindoa5634c42020-09-16 19:42:00 +01001490 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001491 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001492 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001493 }
1494 return new_seq;
1495}
1496
Guido van Rossumc001c092020-04-30 12:12:19 -07001497/* Creates a copy of seq and appends a to it */
1498asdl_seq *
1499_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1500{
1501 assert(a != NULL);
1502 if (!seq) {
1503 return _PyPegen_singleton_seq(p, a);
1504 }
1505
Pablo Galindoa5634c42020-09-16 19:42:00 +01001506 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 -07001507 if (!new_seq) {
1508 return NULL;
1509 }
1510
1511 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001512 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001513 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001514 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001515 return new_seq;
1516}
1517
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001518static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001519_get_flattened_seq_size(asdl_seq *seqs)
1520{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001521 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001522 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001523 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001524 size += asdl_seq_LEN(inner_seq);
1525 }
1526 return size;
1527}
1528
1529/* Flattens an asdl_seq* of asdl_seq*s */
1530asdl_seq *
1531_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1532{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001533 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001534 assert(flattened_seq_size > 0);
1535
Pablo Galindoa5634c42020-09-16 19:42:00 +01001536 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001537 if (!flattened_seq) {
1538 return NULL;
1539 }
1540
1541 int flattened_seq_idx = 0;
1542 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001543 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001544 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001545 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001546 }
1547 }
1548 assert(flattened_seq_idx == flattened_seq_size);
1549
1550 return flattened_seq;
1551}
1552
Pablo Galindoa77aac42021-04-23 14:27:05 +01001553void *
1554_PyPegen_seq_last_item(asdl_seq *seq)
1555{
1556 Py_ssize_t len = asdl_seq_LEN(seq);
1557 return asdl_seq_GET_UNTYPED(seq, len - 1);
1558}
1559
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001560/* Creates a new name of the form <first_name>.<second_name> */
1561expr_ty
1562_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1563{
1564 assert(first_name != NULL && second_name != NULL);
1565 PyObject *first_identifier = first_name->v.Name.id;
1566 PyObject *second_identifier = second_name->v.Name.id;
1567
1568 if (PyUnicode_READY(first_identifier) == -1) {
1569 return NULL;
1570 }
1571 if (PyUnicode_READY(second_identifier) == -1) {
1572 return NULL;
1573 }
1574 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1575 if (!first_str) {
1576 return NULL;
1577 }
1578 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1579 if (!second_str) {
1580 return NULL;
1581 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001582 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001583
1584 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1585 if (!str) {
1586 return NULL;
1587 }
1588
1589 char *s = PyBytes_AS_STRING(str);
1590 if (!s) {
1591 return NULL;
1592 }
1593
1594 strcpy(s, first_str);
1595 s += strlen(first_str);
1596 *s++ = '.';
1597 strcpy(s, second_str);
1598 s += strlen(second_str);
1599 *s = '\0';
1600
1601 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1602 Py_DECREF(str);
1603 if (!uni) {
1604 return NULL;
1605 }
1606 PyUnicode_InternInPlace(&uni);
Victor Stinner8370e072021-03-24 02:23:01 +01001607 if (_PyArena_AddPyObject(p->arena, uni) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001608 Py_DECREF(uni);
1609 return NULL;
1610 }
1611
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001612 return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001613}
1614
1615/* Counts the total number of dots in seq's tokens */
1616int
1617_PyPegen_seq_count_dots(asdl_seq *seq)
1618{
1619 int number_of_dots = 0;
1620 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001621 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001622 switch (current_expr->type) {
1623 case ELLIPSIS:
1624 number_of_dots += 3;
1625 break;
1626 case DOT:
1627 number_of_dots += 1;
1628 break;
1629 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001630 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001631 }
1632 }
1633
1634 return number_of_dots;
1635}
1636
1637/* Creates an alias with '*' as the identifier name */
1638alias_ty
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001639_PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
1640 int end_col_offset, PyArena *arena) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001641 PyObject *str = PyUnicode_InternFromString("*");
1642 if (!str) {
1643 return NULL;
1644 }
Victor Stinner8370e072021-03-24 02:23:01 +01001645 if (_PyArena_AddPyObject(p->arena, str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001646 Py_DECREF(str);
1647 return NULL;
1648 }
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001649 return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001650}
1651
1652/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001653asdl_identifier_seq *
1654_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001655{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001656 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001657 assert(len > 0);
1658
Pablo Galindoa5634c42020-09-16 19:42:00 +01001659 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001660 if (!new_seq) {
1661 return NULL;
1662 }
1663 for (Py_ssize_t i = 0; i < len; i++) {
1664 expr_ty e = asdl_seq_GET(seq, i);
1665 asdl_seq_SET(new_seq, i, e->v.Name.id);
1666 }
1667 return new_seq;
1668}
1669
1670/* Constructs a CmpopExprPair */
1671CmpopExprPair *
1672_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1673{
1674 assert(expr != NULL);
Victor Stinner8370e072021-03-24 02:23:01 +01001675 CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001676 if (!a) {
1677 return NULL;
1678 }
1679 a->cmpop = cmpop;
1680 a->expr = expr;
1681 return a;
1682}
1683
1684asdl_int_seq *
1685_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1686{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001687 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001688 assert(len > 0);
1689
1690 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1691 if (!new_seq) {
1692 return NULL;
1693 }
1694 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001695 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001696 asdl_seq_SET(new_seq, i, pair->cmpop);
1697 }
1698 return new_seq;
1699}
1700
Pablo Galindoa5634c42020-09-16 19:42:00 +01001701asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001702_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1703{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001704 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001705 assert(len > 0);
1706
Pablo Galindoa5634c42020-09-16 19:42:00 +01001707 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001708 if (!new_seq) {
1709 return NULL;
1710 }
1711 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001712 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001713 asdl_seq_SET(new_seq, i, pair->expr);
1714 }
1715 return new_seq;
1716}
1717
1718/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001719static asdl_expr_seq *
1720_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001721{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001722 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001723 if (len == 0) {
1724 return NULL;
1725 }
1726
Pablo Galindoa5634c42020-09-16 19:42:00 +01001727 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001728 if (!new_seq) {
1729 return NULL;
1730 }
1731 for (Py_ssize_t i = 0; i < len; i++) {
1732 expr_ty e = asdl_seq_GET(seq, i);
1733 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1734 }
1735 return new_seq;
1736}
1737
1738static expr_ty
1739_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1740{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001741 return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001742}
1743
1744static expr_ty
1745_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1746{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001747 return _PyAST_Tuple(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001748 _set_seq_context(p, e->v.Tuple.elts, ctx),
1749 ctx,
1750 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001751}
1752
1753static expr_ty
1754_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1755{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001756 return _PyAST_List(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001757 _set_seq_context(p, e->v.List.elts, ctx),
1758 ctx,
1759 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001760}
1761
1762static expr_ty
1763_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1764{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001765 return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
1766 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001767}
1768
1769static expr_ty
1770_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1771{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001772 return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
1773 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001774}
1775
1776static expr_ty
1777_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1778{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001779 return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
1780 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001781}
1782
1783/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1784expr_ty
1785_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1786{
1787 assert(expr != NULL);
1788
1789 expr_ty new = NULL;
1790 switch (expr->kind) {
1791 case Name_kind:
1792 new = _set_name_context(p, expr, ctx);
1793 break;
1794 case Tuple_kind:
1795 new = _set_tuple_context(p, expr, ctx);
1796 break;
1797 case List_kind:
1798 new = _set_list_context(p, expr, ctx);
1799 break;
1800 case Subscript_kind:
1801 new = _set_subscript_context(p, expr, ctx);
1802 break;
1803 case Attribute_kind:
1804 new = _set_attribute_context(p, expr, ctx);
1805 break;
1806 case Starred_kind:
1807 new = _set_starred_context(p, expr, ctx);
1808 break;
1809 default:
1810 new = expr;
1811 }
1812 return new;
1813}
1814
1815/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1816KeyValuePair *
1817_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1818{
Victor Stinner8370e072021-03-24 02:23:01 +01001819 KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001820 if (!a) {
1821 return NULL;
1822 }
1823 a->key = key;
1824 a->value = value;
1825 return a;
1826}
1827
1828/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001829asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001830_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1831{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001832 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001833 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001834 if (!new_seq) {
1835 return NULL;
1836 }
1837 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001838 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001839 asdl_seq_SET(new_seq, i, pair->key);
1840 }
1841 return new_seq;
1842}
1843
1844/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001845asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001846_PyPegen_get_values(Parser *p, asdl_seq *seq)
1847{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001848 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001849 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001850 if (!new_seq) {
1851 return NULL;
1852 }
1853 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001854 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001855 asdl_seq_SET(new_seq, i, pair->value);
1856 }
1857 return new_seq;
1858}
1859
Nick Coghlan1e7b8582021-04-29 15:58:44 +10001860/* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
1861KeyPatternPair *
1862_PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
1863{
1864 KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
1865 if (!a) {
1866 return NULL;
1867 }
1868 a->key = key;
1869 a->pattern = pattern;
1870 return a;
1871}
1872
1873/* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
1874asdl_expr_seq *
1875_PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
1876{
1877 Py_ssize_t len = asdl_seq_LEN(seq);
1878 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1879 if (!new_seq) {
1880 return NULL;
1881 }
1882 for (Py_ssize_t i = 0; i < len; i++) {
1883 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1884 asdl_seq_SET(new_seq, i, pair->key);
1885 }
1886 return new_seq;
1887}
1888
1889/* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
1890asdl_pattern_seq *
1891_PyPegen_get_patterns(Parser *p, asdl_seq *seq)
1892{
1893 Py_ssize_t len = asdl_seq_LEN(seq);
1894 asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
1895 if (!new_seq) {
1896 return NULL;
1897 }
1898 for (Py_ssize_t i = 0; i < len; i++) {
1899 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1900 asdl_seq_SET(new_seq, i, pair->pattern);
1901 }
1902 return new_seq;
1903}
1904
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001905/* Constructs a NameDefaultPair */
1906NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001907_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001908{
Victor Stinner8370e072021-03-24 02:23:01 +01001909 NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001910 if (!a) {
1911 return NULL;
1912 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001913 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001914 a->value = value;
1915 return a;
1916}
1917
1918/* Constructs a SlashWithDefault */
1919SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001920_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001921{
Victor Stinner8370e072021-03-24 02:23:01 +01001922 SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001923 if (!a) {
1924 return NULL;
1925 }
1926 a->plain_names = plain_names;
1927 a->names_with_defaults = names_with_defaults;
1928 return a;
1929}
1930
1931/* Constructs a StarEtc */
1932StarEtc *
1933_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1934{
Victor Stinner8370e072021-03-24 02:23:01 +01001935 StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001936 if (!a) {
1937 return NULL;
1938 }
1939 a->vararg = vararg;
1940 a->kwonlyargs = kwonlyargs;
1941 a->kwarg = kwarg;
1942 return a;
1943}
1944
1945asdl_seq *
1946_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1947{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001948 Py_ssize_t first_len = asdl_seq_LEN(a);
1949 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001950 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001951 if (!new_seq) {
1952 return NULL;
1953 }
1954
1955 int k = 0;
1956 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001957 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001958 }
1959 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001960 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001961 }
1962
1963 return new_seq;
1964}
1965
Pablo Galindoa5634c42020-09-16 19:42:00 +01001966static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001967_get_names(Parser *p, asdl_seq *names_with_defaults)
1968{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001969 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001970 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001971 if (!seq) {
1972 return NULL;
1973 }
1974 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001975 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001976 asdl_seq_SET(seq, i, pair->arg);
1977 }
1978 return seq;
1979}
1980
Pablo Galindoa5634c42020-09-16 19:42:00 +01001981static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001982_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1983{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001984 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001985 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001986 if (!seq) {
1987 return NULL;
1988 }
1989 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001990 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001991 asdl_seq_SET(seq, i, pair->value);
1992 }
1993 return seq;
1994}
1995
Pablo Galindo4f642da2021-04-09 00:48:53 +01001996static int
1997_make_posonlyargs(Parser *p,
1998 asdl_arg_seq *slash_without_default,
1999 SlashWithDefault *slash_with_default,
2000 asdl_arg_seq **posonlyargs) {
2001 if (slash_without_default != NULL) {
2002 *posonlyargs = slash_without_default;
2003 }
2004 else if (slash_with_default != NULL) {
2005 asdl_arg_seq *slash_with_default_names =
2006 _get_names(p, slash_with_default->names_with_defaults);
2007 if (!slash_with_default_names) {
2008 return -1;
2009 }
2010 *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2011 p,
2012 (asdl_seq*)slash_with_default->plain_names,
2013 (asdl_seq*)slash_with_default_names);
2014 }
2015 else {
2016 *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2017 }
2018 return *posonlyargs == NULL ? -1 : 0;
2019}
2020
2021static int
2022_make_posargs(Parser *p,
2023 asdl_arg_seq *plain_names,
2024 asdl_seq *names_with_default,
2025 asdl_arg_seq **posargs) {
2026 if (plain_names != NULL && names_with_default != NULL) {
2027 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
2028 if (!names_with_default_names) {
2029 return -1;
2030 }
2031 *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2032 p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
2033 }
2034 else if (plain_names == NULL && names_with_default != NULL) {
2035 *posargs = _get_names(p, names_with_default);
2036 }
2037 else if (plain_names != NULL && names_with_default == NULL) {
2038 *posargs = plain_names;
2039 }
2040 else {
2041 *posargs = _Py_asdl_arg_seq_new(0, p->arena);
2042 }
2043 return *posargs == NULL ? -1 : 0;
2044}
2045
2046static int
2047_make_posdefaults(Parser *p,
2048 SlashWithDefault *slash_with_default,
2049 asdl_seq *names_with_default,
2050 asdl_expr_seq **posdefaults) {
2051 if (slash_with_default != NULL && names_with_default != NULL) {
2052 asdl_expr_seq *slash_with_default_values =
2053 _get_defaults(p, slash_with_default->names_with_defaults);
2054 if (!slash_with_default_values) {
2055 return -1;
2056 }
2057 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
2058 if (!names_with_default_values) {
2059 return -1;
2060 }
2061 *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
2062 p,
2063 (asdl_seq*)slash_with_default_values,
2064 (asdl_seq*)names_with_default_values);
2065 }
2066 else if (slash_with_default == NULL && names_with_default != NULL) {
2067 *posdefaults = _get_defaults(p, names_with_default);
2068 }
2069 else if (slash_with_default != NULL && names_with_default == NULL) {
2070 *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
2071 }
2072 else {
2073 *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2074 }
2075 return *posdefaults == NULL ? -1 : 0;
2076}
2077
2078static int
2079_make_kwargs(Parser *p, StarEtc *star_etc,
2080 asdl_arg_seq **kwonlyargs,
2081 asdl_expr_seq **kwdefaults) {
2082 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2083 *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
2084 }
2085 else {
2086 *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2087 }
2088
2089 if (*kwonlyargs == NULL) {
2090 return -1;
2091 }
2092
2093 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2094 *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
2095 }
2096 else {
2097 *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2098 }
2099
2100 if (*kwdefaults == NULL) {
2101 return -1;
2102 }
2103
2104 return 0;
2105}
2106
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002107/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
2108arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002109_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
2110 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002111 asdl_seq *names_with_default, StarEtc *star_etc)
2112{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002113 asdl_arg_seq *posonlyargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002114 if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
2115 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002116 }
2117
Pablo Galindoa5634c42020-09-16 19:42:00 +01002118 asdl_arg_seq *posargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002119 if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
2120 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002121 }
2122
Pablo Galindoa5634c42020-09-16 19:42:00 +01002123 asdl_expr_seq *posdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002124 if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
2125 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002126 }
2127
2128 arg_ty vararg = NULL;
2129 if (star_etc != NULL && star_etc->vararg != NULL) {
2130 vararg = star_etc->vararg;
2131 }
2132
Pablo Galindoa5634c42020-09-16 19:42:00 +01002133 asdl_arg_seq *kwonlyargs;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002134 asdl_expr_seq *kwdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002135 if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
2136 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002137 }
2138
2139 arg_ty kwarg = NULL;
2140 if (star_etc != NULL && star_etc->kwarg != NULL) {
2141 kwarg = star_etc->kwarg;
2142 }
2143
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002144 return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
2145 kwdefaults, kwarg, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002146}
2147
Pablo Galindo4f642da2021-04-09 00:48:53 +01002148
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002149/* Constructs an empty arguments_ty object, that gets used when a function accepts no
2150 * arguments. */
2151arguments_ty
2152_PyPegen_empty_arguments(Parser *p)
2153{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002154 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002155 if (!posonlyargs) {
2156 return NULL;
2157 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002158 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002159 if (!posargs) {
2160 return NULL;
2161 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002162 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002163 if (!posdefaults) {
2164 return NULL;
2165 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002166 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002167 if (!kwonlyargs) {
2168 return NULL;
2169 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002170 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002171 if (!kwdefaults) {
2172 return NULL;
2173 }
2174
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002175 return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
2176 kwdefaults, NULL, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002177}
2178
2179/* Encapsulates the value of an operator_ty into an AugOperator struct */
2180AugOperator *
2181_PyPegen_augoperator(Parser *p, operator_ty kind)
2182{
Victor Stinner8370e072021-03-24 02:23:01 +01002183 AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002184 if (!a) {
2185 return NULL;
2186 }
2187 a->kind = kind;
2188 return a;
2189}
2190
2191/* Construct a FunctionDef equivalent to function_def, but with decorators */
2192stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002193_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002194{
2195 assert(function_def != NULL);
2196 if (function_def->kind == AsyncFunctionDef_kind) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002197 return _PyAST_AsyncFunctionDef(
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002198 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2199 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2200 function_def->v.FunctionDef.type_comment, function_def->lineno,
2201 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2202 p->arena);
2203 }
2204
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002205 return _PyAST_FunctionDef(
2206 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2207 function_def->v.FunctionDef.body, decorators,
2208 function_def->v.FunctionDef.returns,
2209 function_def->v.FunctionDef.type_comment, function_def->lineno,
2210 function_def->col_offset, function_def->end_lineno,
2211 function_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002212}
2213
2214/* Construct a ClassDef equivalent to class_def, but with decorators */
2215stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002216_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002217{
2218 assert(class_def != NULL);
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002219 return _PyAST_ClassDef(
2220 class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2221 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2222 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2223 class_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002224}
2225
2226/* Construct a KeywordOrStarred */
2227KeywordOrStarred *
2228_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2229{
Victor Stinner8370e072021-03-24 02:23:01 +01002230 KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002231 if (!a) {
2232 return NULL;
2233 }
2234 a->element = element;
2235 a->is_keyword = is_keyword;
2236 return a;
2237}
2238
2239/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2240static int
2241_seq_number_of_starred_exprs(asdl_seq *seq)
2242{
2243 int n = 0;
2244 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002245 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002246 if (!k->is_keyword) {
2247 n++;
2248 }
2249 }
2250 return n;
2251}
2252
2253/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002254asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002255_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2256{
2257 int new_len = _seq_number_of_starred_exprs(kwargs);
2258 if (new_len == 0) {
2259 return NULL;
2260 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002261 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002262 if (!new_seq) {
2263 return NULL;
2264 }
2265
2266 int idx = 0;
2267 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002268 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002269 if (!k->is_keyword) {
2270 asdl_seq_SET(new_seq, idx++, k->element);
2271 }
2272 }
2273 return new_seq;
2274}
2275
2276/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002277asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002278_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2279{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002280 Py_ssize_t len = asdl_seq_LEN(kwargs);
2281 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002282 if (new_len == 0) {
2283 return NULL;
2284 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002285 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002286 if (!new_seq) {
2287 return NULL;
2288 }
2289
2290 int idx = 0;
2291 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002292 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002293 if (k->is_keyword) {
2294 asdl_seq_SET(new_seq, idx++, k->element);
2295 }
2296 }
2297 return new_seq;
2298}
2299
2300expr_ty
2301_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2302{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002303 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002304 assert(len > 0);
2305
Pablo Galindoa5634c42020-09-16 19:42:00 +01002306 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2307 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002308
2309 int bytesmode = 0;
2310 PyObject *bytes_str = NULL;
2311
2312 FstringParser state;
2313 _PyPegen_FstringParser_Init(&state);
2314
2315 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002316 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002317
2318 int this_bytesmode;
2319 int this_rawmode;
2320 PyObject *s;
2321 const char *fstr;
2322 Py_ssize_t fstrlen = -1;
2323
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002324 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002325 goto error;
2326 }
2327
2328 /* Check that we are not mixing bytes with unicode. */
2329 if (i != 0 && bytesmode != this_bytesmode) {
2330 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2331 Py_XDECREF(s);
2332 goto error;
2333 }
2334 bytesmode = this_bytesmode;
2335
2336 if (fstr != NULL) {
2337 assert(s == NULL && !bytesmode);
2338
2339 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2340 this_rawmode, 0, first, t, last);
2341 if (result < 0) {
2342 goto error;
2343 }
2344 }
2345 else {
2346 /* String or byte string. */
2347 assert(s != NULL && fstr == NULL);
2348 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2349
2350 if (bytesmode) {
2351 if (i == 0) {
2352 bytes_str = s;
2353 }
2354 else {
2355 PyBytes_ConcatAndDel(&bytes_str, s);
2356 if (!bytes_str) {
2357 goto error;
2358 }
2359 }
2360 }
2361 else {
2362 /* This is a regular string. Concatenate it. */
2363 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2364 goto error;
2365 }
2366 }
2367 }
2368 }
2369
2370 if (bytesmode) {
Victor Stinner8370e072021-03-24 02:23:01 +01002371 if (_PyArena_AddPyObject(p->arena, bytes_str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002372 goto error;
2373 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002374 return _PyAST_Constant(bytes_str, NULL, first->lineno,
2375 first->col_offset, last->end_lineno,
2376 last->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002377 }
2378
2379 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2380
2381error:
2382 Py_XDECREF(bytes_str);
2383 _PyPegen_FstringParser_Dealloc(&state);
2384 if (PyErr_Occurred()) {
2385 raise_decode_error(p);
2386 }
2387 return NULL;
2388}
Guido van Rossumc001c092020-04-30 12:12:19 -07002389
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002390expr_ty
2391_PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
2392{
2393 if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07002394 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
2395 return NULL;
2396 }
2397 return exp;
2398}
2399
2400expr_ty
2401_PyPegen_ensure_real(Parser *p, expr_ty exp)
2402{
2403 if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
2404 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002405 return NULL;
2406 }
2407 return exp;
2408}
2409
Guido van Rossumc001c092020-04-30 12:12:19 -07002410mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002411_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2412 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002413 Py_ssize_t num = p->type_ignore_comments.num_items;
2414 if (num > 0) {
2415 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002416 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002417 if (type_ignores == NULL) {
2418 return NULL;
2419 }
2420 for (int i = 0; i < num; i++) {
2421 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2422 if (tag == NULL) {
2423 return NULL;
2424 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002425 type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
2426 tag, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002427 if (ti == NULL) {
2428 return NULL;
2429 }
2430 asdl_seq_SET(type_ignores, i, ti);
2431 }
2432 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002433 return _PyAST_Module(a, type_ignores, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002434}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002435
2436// Error reporting helpers
2437
2438expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002439_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002440{
2441 if (e == NULL) {
2442 return NULL;
2443 }
2444
2445#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
Pablo Galindo58bafe42021-04-09 01:17:31 +01002446 Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002447 for (Py_ssize_t i = 0; i < len; i++) {\
Pablo Galindo58bafe42021-04-09 01:17:31 +01002448 expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002449 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002450 if (child != NULL) {\
2451 return child;\
2452 }\
2453 }\
2454 } while (0)
2455
2456 // We only need to visit List and Tuple nodes recursively as those
2457 // are the only ones that can contain valid names in targets when
2458 // they are parsed as expressions. Any other kind of expression
2459 // that is a container (like Sets or Dicts) is directly invalid and
2460 // we don't need to visit it recursively.
2461
2462 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002463 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002464 VISIT_CONTAINER(e, List);
2465 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002466 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002467 VISIT_CONTAINER(e, Tuple);
2468 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002469 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002470 if (targets_type == DEL_TARGETS) {
2471 return e;
2472 }
2473 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2474 case Compare_kind:
2475 // This is needed, because the `a in b` in `for a in b` gets parsed
2476 // as a comparison, and so we need to search the left side of the comparison
2477 // for invalid targets.
2478 if (targets_type == FOR_TARGETS) {
2479 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2480 if (cmpop == In) {
2481 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2482 }
2483 return NULL;
2484 }
2485 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002486 case Name_kind:
2487 case Subscript_kind:
2488 case Attribute_kind:
2489 return NULL;
2490 default:
2491 return e;
2492 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002493}
2494
2495void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2496 int kwarg_unpacking = 0;
2497 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2498 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2499 if (!keyword->arg) {
2500 kwarg_unpacking = 1;
2501 }
2502 }
2503
2504 const char *msg = NULL;
2505 if (kwarg_unpacking) {
2506 msg = "positional argument follows keyword argument unpacking";
2507 } else {
2508 msg = "positional argument follows keyword argument";
2509 }
2510
2511 return RAISE_SYNTAX_ERROR(msg);
2512}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002513
2514void *
2515_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2516{
2517 /* The rule that calls this function is 'args for_if_clauses'.
2518 For the input f(L, x for x in y), L and x are in args and
2519 the for is parsed as a for_if_clause. We have to check if
2520 len <= 1, so that input like dict((a, b) for a, b in x)
2521 gets successfully parsed and then we pass the last
2522 argument (x in the above example) as the location of the
2523 error */
2524 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2525 if (len <= 1) {
2526 return NULL;
2527 }
2528
Pablo Galindoa77aac42021-04-23 14:27:05 +01002529 return RAISE_SYNTAX_ERROR_STARTING_FROM(
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002530 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2531 "Generator expression must be parenthesized"
2532 );
2533}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002534
2535
Pablo Galindoa5634c42020-09-16 19:42:00 +01002536expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002537 int lineno, int col_offset, int end_lineno,
2538 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002539 Py_ssize_t args_len = asdl_seq_LEN(a);
2540 Py_ssize_t total_len = args_len;
2541
2542 if (b == NULL) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002543 return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002544 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002545
2546 }
2547
Pablo Galindoa5634c42020-09-16 19:42:00 +01002548 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2549 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002550
2551 if (starreds) {
2552 total_len += asdl_seq_LEN(starreds);
2553 }
2554
Pablo Galindoa5634c42020-09-16 19:42:00 +01002555 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002556
2557 Py_ssize_t i = 0;
2558 for (i = 0; i < args_len; i++) {
2559 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2560 }
2561 for (; i < total_len; i++) {
2562 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2563 }
2564
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002565 return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2566 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002567}