blob: cfb4b8e8fb15767ef3a049d61fdc0759a07cd706 [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 Galindo Salgadob977f852021-07-27 18:52:32 +010080int
81_PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
82 assert(name->kind == Name_kind);
83 const char* candidates[2] = {"print", "exec"};
84 for (int i=0; i<2; i++) {
85 if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
86 return 1;
87 }
88 }
89 return 0;
90}
91
Pablo Galindoc5fc1562020-04-22 23:29:27 +010092PyObject *
Serhiy Storchakac43317d2021-06-12 20:44:32 +030093_PyPegen_new_identifier(Parser *p, const char *n)
Pablo Galindoc5fc1562020-04-22 23:29:27 +010094{
95 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
96 if (!id) {
97 goto error;
98 }
99 /* PyUnicode_DecodeUTF8 should always return a ready string. */
100 assert(PyUnicode_IS_READY(id));
101 /* Check whether there are non-ASCII characters in the
102 identifier; if so, normalize to NFKC. */
103 if (!PyUnicode_IS_ASCII(id))
104 {
105 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300106 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100107 {
108 Py_DECREF(id);
109 goto error;
110 }
111 PyObject *form = PyUnicode_InternFromString("NFKC");
112 if (form == NULL)
113 {
114 Py_DECREF(id);
115 goto error;
116 }
117 PyObject *args[2] = {form, id};
118 id2 = _PyObject_FastCall(p->normalize, args, 2);
119 Py_DECREF(id);
120 Py_DECREF(form);
121 if (!id2) {
122 goto error;
123 }
124 if (!PyUnicode_Check(id2))
125 {
126 PyErr_Format(PyExc_TypeError,
127 "unicodedata.normalize() must return a string, not "
128 "%.200s",
129 _PyType_Name(Py_TYPE(id2)));
130 Py_DECREF(id2);
131 goto error;
132 }
133 id = id2;
134 }
135 PyUnicode_InternInPlace(&id);
Victor Stinner8370e072021-03-24 02:23:01 +0100136 if (_PyArena_AddPyObject(p->arena, id) < 0)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100137 {
138 Py_DECREF(id);
139 goto error;
140 }
141 return id;
142
143error:
144 p->error_indicator = 1;
145 return NULL;
146}
147
148static PyObject *
149_create_dummy_identifier(Parser *p)
150{
151 return _PyPegen_new_identifier(p, "");
152}
153
154static inline Py_ssize_t
Pablo Galindo51c58962020-06-16 16:49:43 +0100155byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100156{
157 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300158 if (!str) {
159 return 0;
160 }
Pablo Galindo123ff262021-03-22 16:24:39 +0000161 Py_ssize_t len = strlen(str);
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100162 if (col_offset > len + 1) {
163 col_offset = len + 1;
Pablo Galindo123ff262021-03-22 16:24:39 +0000164 }
165 assert(col_offset >= 0);
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300166 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100167 if (!text) {
168 return 0;
169 }
170 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
171 Py_DECREF(text);
172 return size;
173}
174
175const char *
176_PyPegen_get_expr_name(expr_ty e)
177{
Pablo Galindo9f495902020-06-08 02:57:00 +0100178 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100179 switch (e->kind) {
180 case Attribute_kind:
181 return "attribute";
182 case Subscript_kind:
183 return "subscript";
184 case Starred_kind:
185 return "starred";
186 case Name_kind:
187 return "name";
188 case List_kind:
189 return "list";
190 case Tuple_kind:
191 return "tuple";
192 case Lambda_kind:
193 return "lambda";
194 case Call_kind:
195 return "function call";
196 case BoolOp_kind:
197 case BinOp_kind:
198 case UnaryOp_kind:
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100199 return "expression";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100200 case GeneratorExp_kind:
201 return "generator expression";
202 case Yield_kind:
203 case YieldFrom_kind:
204 return "yield expression";
205 case Await_kind:
206 return "await expression";
207 case ListComp_kind:
208 return "list comprehension";
209 case SetComp_kind:
210 return "set comprehension";
211 case DictComp_kind:
212 return "dict comprehension";
213 case Dict_kind:
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100214 return "dict literal";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100215 case Set_kind:
216 return "set display";
217 case JoinedStr_kind:
218 case FormattedValue_kind:
219 return "f-string expression";
220 case Constant_kind: {
221 PyObject *value = e->v.Constant.value;
222 if (value == Py_None) {
223 return "None";
224 }
225 if (value == Py_False) {
226 return "False";
227 }
228 if (value == Py_True) {
229 return "True";
230 }
231 if (value == Py_Ellipsis) {
Pablo Galindo3283bf42021-06-03 22:22:28 +0100232 return "ellipsis";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100233 }
234 return "literal";
235 }
236 case Compare_kind:
237 return "comparison";
238 case IfExp_kind:
239 return "conditional expression";
240 case NamedExpr_kind:
241 return "named expression";
242 default:
243 PyErr_Format(PyExc_SystemError,
244 "unexpected expression in assignment %d (line %d)",
245 e->kind, e->lineno);
246 return NULL;
247 }
248}
249
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300250static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100251raise_decode_error(Parser *p)
252{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300253 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100254 const char *errtype = NULL;
255 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
256 errtype = "unicode error";
257 }
258 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
259 errtype = "value error";
260 }
261 if (errtype) {
Pablo Galindofb61c422020-06-15 14:23:43 +0100262 PyObject *type;
263 PyObject *value;
264 PyObject *tback;
265 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100266 PyErr_Fetch(&type, &value, &tback);
267 errstr = PyObject_Str(value);
268 if (errstr) {
269 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
270 Py_DECREF(errstr);
271 }
272 else {
273 PyErr_Clear();
274 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
275 }
276 Py_XDECREF(type);
277 Py_XDECREF(value);
278 Py_XDECREF(tback);
279 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300280
281 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100282}
283
Pablo Galindod6d63712021-01-19 23:59:33 +0000284static inline void
285raise_unclosed_parentheses_error(Parser *p) {
286 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
287 int error_col = p->tok->parencolstack[p->tok->level-1];
288 RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100289 error_lineno, error_col, error_lineno, -1,
Pablo Galindod6d63712021-01-19 23:59:33 +0000290 "'%c' was never closed",
291 p->tok->parenstack[p->tok->level-1]);
292}
293
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100294static void
295raise_tokenizer_init_error(PyObject *filename)
296{
297 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700298 || PyErr_ExceptionMatches(PyExc_SyntaxError)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100299 || PyErr_ExceptionMatches(PyExc_ValueError)
300 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
301 return;
302 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300303 PyObject *errstr = NULL;
304 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100305 PyObject *type;
306 PyObject *value;
307 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308 PyErr_Fetch(&type, &value, &tback);
309 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300310 if (!errstr) {
311 goto error;
312 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100313
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300314 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100315 if (!tmp) {
316 goto error;
317 }
318
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300319 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320 Py_DECREF(tmp);
321 if (!value) {
322 goto error;
323 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300324 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100325
326error:
327 Py_XDECREF(type);
328 Py_XDECREF(value);
329 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300330 Py_XDECREF(errstr);
331 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332}
333
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100334static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100335tokenizer_error(Parser *p)
336{
337 if (PyErr_Occurred()) {
338 return -1;
339 }
340
341 const char *msg = NULL;
342 PyObject* errtype = PyExc_SyntaxError;
Pablo Galindo96eeff52021-03-22 17:28:11 +0000343 Py_ssize_t col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100344 switch (p->tok->done) {
345 case E_TOKEN:
346 msg = "invalid token";
347 break;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300348 case E_EOF:
Pablo Galindod6d63712021-01-19 23:59:33 +0000349 if (p->tok->level) {
350 raise_unclosed_parentheses_error(p);
351 } else {
352 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
353 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300354 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100355 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300356 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
357 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100358 case E_INTR:
359 if (!PyErr_Occurred()) {
360 PyErr_SetNone(PyExc_KeyboardInterrupt);
361 }
362 return -1;
363 case E_NOMEM:
364 PyErr_NoMemory();
365 return -1;
366 case E_TABSPACE:
367 errtype = PyExc_TabError;
368 msg = "inconsistent use of tabs and spaces in indentation";
369 break;
370 case E_TOODEEP:
371 errtype = PyExc_IndentationError;
372 msg = "too many levels of indentation";
373 break;
Łukasz Langa5c9cab52021-10-19 22:31:18 +0200374 case E_LINECONT: {
Miss Islington (bot)bf26a6d2021-11-13 17:30:03 -0800375 col_offset = p->tok->cur - p->tok->buf - 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100376 msg = "unexpected character after line continuation character";
377 break;
Łukasz Langa5c9cab52021-10-19 22:31:18 +0200378 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100379 default:
380 msg = "unknown parsing error";
381 }
382
Miss Islington (bot)bf26a6d2021-11-13 17:30:03 -0800383 RAISE_ERROR_KNOWN_LOCATION(p, errtype, p->tok->lineno,
384 col_offset >= 0 ? col_offset : 0,
385 p->tok->lineno, -1, msg);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100386 return -1;
387}
388
389void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300390_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
391{
392 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100393 Py_ssize_t col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100394 Py_ssize_t end_col_offset = -1;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300395 if (t->col_offset == -1) {
396 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
397 intptr_t, int);
398 } else {
399 col_offset = t->col_offset + 1;
400 }
401
Pablo Galindoa77aac42021-04-23 14:27:05 +0100402 if (t->end_col_offset != -1) {
403 end_col_offset = t->end_col_offset + 1;
404 }
405
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300406 va_list va;
407 va_start(va, errmsg);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100408 _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 +0300409 va_end(va);
410
411 return NULL;
412}
413
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200414static PyObject *
415get_error_line(Parser *p, Py_ssize_t lineno)
416{
Pablo Galindo123ff262021-03-22 16:24:39 +0000417 /* If the file descriptor is interactive, the source lines of the current
418 * (multi-line) statement are stored in p->tok->interactive_src_start.
419 * If not, we're parsing from a string, which means that the whole source
420 * is stored in p->tok->str. */
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200421 assert(p->tok->fp == NULL || p->tok->fp == stdin);
422
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100423 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
424
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200425 for (int i = 0; i < lineno - 1; i++) {
426 cur_line = strchr(cur_line, '\n') + 1;
427 }
428
429 char *next_newline;
430 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
431 next_newline = cur_line + strlen(cur_line);
432 }
433 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
434}
435
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300436void *
437_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100438 Py_ssize_t lineno, Py_ssize_t col_offset,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100439 Py_ssize_t end_lineno, Py_ssize_t end_col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300440 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100441{
442 PyObject *value = NULL;
443 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300444 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100445 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300446 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100447
Pablo Galindoa77aac42021-04-23 14:27:05 +0100448 if (end_lineno == CURRENT_POS) {
449 end_lineno = p->tok->lineno;
450 }
451 if (end_col_offset == CURRENT_POS) {
452 end_col_offset = p->tok->cur - p->tok->line_start;
453 }
454
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300455 if (p->start_rule == Py_fstring_input) {
456 const char *fstring_msg = "f-string: ";
457 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
458
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300459 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300460 if (!new_errmsg) {
461 return (void *) PyErr_NoMemory();
462 }
463
464 // Copy both strings into new buffer
465 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
466 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
467 new_errmsg[len] = 0;
468 errmsg = new_errmsg;
469 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100470 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100471 if (!errstr) {
472 goto error;
473 }
474
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700475 // PyErr_ProgramTextObject assumes that the text is utf-8 so we cannot call it with a file
476 // with an arbitrary encoding or otherwise we could get some badly decoded text.
477 int uses_utf8_codec = (!p->tok->encoding || strcmp(p->tok->encoding, "utf-8") == 0);
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100478 if (p->tok->fp_interactive) {
479 error_line = get_error_line(p, lineno);
480 }
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700481 else if (uses_utf8_codec && p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300482 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100483 }
484
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300485 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200486 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
487 then we need to find the error line from some other source, because
488 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
489 failed or we're parsing from a string or the REPL. There's a third edge case where
490 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
491 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
492 does not physically exist */
Miss Islington (bot)c0496092021-06-08 17:29:21 -0700493 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF || !uses_utf8_codec);
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200494
Miss Islington (bot)bf26a6d2021-11-13 17:30:03 -0800495 if (p->tok->lineno <= lineno && p->tok->inp > p->tok->buf) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200496 Py_ssize_t size = p->tok->inp - p->tok->buf;
497 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
498 }
499 else {
500 error_line = get_error_line(p, lineno);
501 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300502 if (!error_line) {
503 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300504 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100505 }
506
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300507 if (p->start_rule == Py_fstring_input) {
508 col_offset -= p->starting_col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100509 end_col_offset -= p->starting_col_offset;
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300510 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100511
Pablo Galindo51c58962020-06-16 16:49:43 +0100512 Py_ssize_t col_number = col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100513 Py_ssize_t end_col_number = end_col_offset;
Pablo Galindo51c58962020-06-16 16:49:43 +0100514
515 if (p->tok->encoding != NULL) {
516 col_number = byte_offset_to_character_offset(error_line, col_offset);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100517 end_col_number = end_col_number > 0 ?
518 byte_offset_to_character_offset(error_line, end_col_offset) :
519 end_col_number;
Pablo Galindo51c58962020-06-16 16:49:43 +0100520 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100521 tmp = Py_BuildValue("(OiiNii)", p->tok->filename, lineno, col_number, error_line, end_lineno, end_col_number);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100522 if (!tmp) {
523 goto error;
524 }
525 value = PyTuple_Pack(2, errstr, tmp);
526 Py_DECREF(tmp);
527 if (!value) {
528 goto error;
529 }
530 PyErr_SetObject(errtype, value);
531
532 Py_DECREF(errstr);
533 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300534 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300535 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300536 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100537 return NULL;
538
539error:
540 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300541 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300542 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300543 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300544 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100545 return NULL;
546}
547
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100548#if 0
549static const char *
550token_name(int type)
551{
552 if (0 <= type && type <= N_TOKENS) {
553 return _PyParser_TokenNames[type];
554 }
555 return "<Huh?>";
556}
557#endif
558
559// Here, mark is the start of the node, while p->mark is the end.
560// If node==NULL, they should be the same.
561int
562_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
563{
564 // Insert in front
Victor Stinner8370e072021-03-24 02:23:01 +0100565 Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100566 if (m == NULL) {
567 return -1;
568 }
569 m->type = type;
570 m->node = node;
571 m->mark = p->mark;
572 m->next = p->tokens[mark]->memo;
573 p->tokens[mark]->memo = m;
574 return 0;
575}
576
577// Like _PyPegen_insert_memo(), but updates an existing node if found.
578int
579_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
580{
581 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
582 if (m->type == type) {
583 // Update existing node.
584 m->node = node;
585 m->mark = p->mark;
586 return 0;
587 }
588 }
589 // Insert new node.
590 return _PyPegen_insert_memo(p, mark, type, node);
591}
592
593// Return dummy NAME.
594void *
595_PyPegen_dummy_name(Parser *p, ...)
596{
597 static void *cache = NULL;
598
599 if (cache != NULL) {
600 return cache;
601 }
602
603 PyObject *id = _create_dummy_identifier(p);
604 if (!id) {
605 return NULL;
606 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200607 cache = _PyAST_Name(id, Load, 1, 0, 1, 0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100608 return cache;
609}
610
611static int
612_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
613{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300614 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100615 if (name_len >= p->n_keyword_lists ||
616 p->keywords[name_len] == NULL ||
617 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100618 return NAME;
619 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100620 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100621 if (strncmp(k->str, name, name_len) == 0) {
622 return k->type;
623 }
624 }
625 return NAME;
626}
627
Guido van Rossumc001c092020-04-30 12:12:19 -0700628static int
629growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
630 assert(initial_size > 0);
631 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
632 arr->size = initial_size;
633 arr->num_items = 0;
634
635 return arr->items != NULL;
636}
637
638static int
639growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
640 if (arr->num_items >= arr->size) {
641 size_t new_size = arr->size * 2;
642 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
643 if (!new_items_array) {
644 return 0;
645 }
646 arr->items = new_items_array;
647 arr->size = new_size;
648 }
649
650 arr->items[arr->num_items].lineno = lineno;
651 arr->items[arr->num_items].comment = comment; // Take ownership
652 arr->num_items++;
653 return 1;
654}
655
656static void
657growable_comment_array_deallocate(growable_comment_array *arr) {
658 for (unsigned i = 0; i < arr->num_items; i++) {
659 PyMem_Free(arr->items[i].comment);
660 }
661 PyMem_Free(arr->items);
662}
663
Pablo Galindod00a4492021-04-09 01:32:25 +0100664static int
665initialize_token(Parser *p, Token *token, const char *start, const char *end, int token_type) {
666 assert(token != NULL);
667
668 token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : token_type;
669 token->bytes = PyBytes_FromStringAndSize(start, end - start);
670 if (token->bytes == NULL) {
671 return -1;
672 }
673
674 if (_PyArena_AddPyObject(p->arena, token->bytes) < 0) {
675 Py_DECREF(token->bytes);
676 return -1;
677 }
678
679 const char *line_start = token_type == STRING ? p->tok->multi_line_start : p->tok->line_start;
680 int lineno = token_type == STRING ? p->tok->first_lineno : p->tok->lineno;
681 int end_lineno = p->tok->lineno;
682
683 int col_offset = (start != NULL && start >= line_start) ? (int)(start - line_start) : -1;
684 int end_col_offset = (end != NULL && end >= p->tok->line_start) ? (int)(end - p->tok->line_start) : -1;
685
686 token->lineno = p->starting_lineno + lineno;
687 token->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
688 token->end_lineno = p->starting_lineno + end_lineno;
689 token->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
690
691 p->fill += 1;
692
693 if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
694 return raise_decode_error(p);
695 }
696
697 return (token_type == ERRORTOKEN ? tokenizer_error(p) : 0);
698}
699
700static int
701_resize_tokens_array(Parser *p) {
702 int newsize = p->size * 2;
703 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
704 if (new_tokens == NULL) {
705 PyErr_NoMemory();
706 return -1;
707 }
708 p->tokens = new_tokens;
709
710 for (int i = p->size; i < newsize; i++) {
711 p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
712 if (p->tokens[i] == NULL) {
713 p->size = i; // Needed, in order to cleanup correctly after parser fails
714 PyErr_NoMemory();
715 return -1;
716 }
717 }
718 p->size = newsize;
719 return 0;
720}
721
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100722int
723_PyPegen_fill_token(Parser *p)
724{
Pablo Galindofb61c422020-06-15 14:23:43 +0100725 const char *start;
726 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100727 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700728
729 // Record and skip '# type: ignore' comments
730 while (type == TYPE_IGNORE) {
731 Py_ssize_t len = end - start;
732 char *tag = PyMem_Malloc(len + 1);
733 if (tag == NULL) {
734 PyErr_NoMemory();
735 return -1;
736 }
737 strncpy(tag, start, len);
738 tag[len] = '\0';
739 // Ownership of tag passes to the growable array
740 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
741 PyErr_NoMemory();
742 return -1;
743 }
744 type = PyTokenizer_Get(p->tok, &start, &end);
745 }
746
Pablo Galindod00a4492021-04-09 01:32:25 +0100747 // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
748 if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100749 type = NEWLINE; /* Add an extra newline */
750 p->parsing_started = 0;
751
Pablo Galindob94dbd72020-04-27 18:35:58 +0100752 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100753 p->tok->pendin = -p->tok->indent;
754 p->tok->indent = 0;
755 }
756 }
757 else {
758 p->parsing_started = 1;
759 }
760
Pablo Galindod00a4492021-04-09 01:32:25 +0100761 // Check if we are at the limit of the token array capacity and resize if needed
762 if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
763 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100764 }
765
766 Token *t = p->tokens[p->fill];
Pablo Galindod00a4492021-04-09 01:32:25 +0100767 return initialize_token(p, t, start, end, type);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100768}
769
Pablo Galindo58bafe42021-04-09 01:17:31 +0100770
771#if defined(Py_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100772// Instrumentation to count the effectiveness of memoization.
773// The array counts the number of tokens skipped by memoization,
774// indexed by type.
775
776#define NSTATISTICS 2000
777static long memo_statistics[NSTATISTICS];
778
779void
780_PyPegen_clear_memo_statistics()
781{
782 for (int i = 0; i < NSTATISTICS; i++) {
783 memo_statistics[i] = 0;
784 }
785}
786
787PyObject *
788_PyPegen_get_memo_statistics()
789{
790 PyObject *ret = PyList_New(NSTATISTICS);
791 if (ret == NULL) {
792 return NULL;
793 }
794 for (int i = 0; i < NSTATISTICS; i++) {
795 PyObject *value = PyLong_FromLong(memo_statistics[i]);
796 if (value == NULL) {
797 Py_DECREF(ret);
798 return NULL;
799 }
800 // PyList_SetItem borrows a reference to value.
801 if (PyList_SetItem(ret, i, value) < 0) {
802 Py_DECREF(ret);
803 return NULL;
804 }
805 }
806 return ret;
807}
Pablo Galindo58bafe42021-04-09 01:17:31 +0100808#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100809
810int // bool
811_PyPegen_is_memoized(Parser *p, int type, void *pres)
812{
813 if (p->mark == p->fill) {
814 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300815 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100816 return -1;
817 }
818 }
819
820 Token *t = p->tokens[p->mark];
821
822 for (Memo *m = t->memo; m != NULL; m = m->next) {
823 if (m->type == type) {
Pablo Galindo58bafe42021-04-09 01:17:31 +0100824#if defined(PY_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100825 if (0 <= type && type < NSTATISTICS) {
826 long count = m->mark - p->mark;
827 // A memoized negative result counts for one.
828 if (count <= 0) {
829 count = 1;
830 }
831 memo_statistics[type] += count;
832 }
Pablo Galindo58bafe42021-04-09 01:17:31 +0100833#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100834 p->mark = m->mark;
835 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100836 return 1;
837 }
838 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100839 return 0;
840}
841
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100842int
843_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
844{
845 int mark = p->mark;
846 void *res = func(p);
847 p->mark = mark;
848 return (res != NULL) == positive;
849}
850
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100851int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100852_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
853{
854 int mark = p->mark;
855 void *res = func(p, arg);
856 p->mark = mark;
857 return (res != NULL) == positive;
858}
859
860int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100861_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
862{
863 int mark = p->mark;
864 void *res = func(p, arg);
865 p->mark = mark;
866 return (res != NULL) == positive;
867}
868
869int
870_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
871{
872 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100873 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100874 p->mark = mark;
875 return (res != NULL) == positive;
876}
877
878Token *
879_PyPegen_expect_token(Parser *p, int type)
880{
881 if (p->mark == p->fill) {
882 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300883 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100884 return NULL;
885 }
886 }
887 Token *t = p->tokens[p->mark];
888 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100889 return NULL;
890 }
891 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100892 return t;
893}
894
Pablo Galindo58fb1562021-02-02 19:54:22 +0000895Token *
896_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
897
898 if (p->error_indicator == 1) {
899 return NULL;
900 }
901
902 if (p->mark == p->fill) {
903 if (_PyPegen_fill_token(p) < 0) {
904 p->error_indicator = 1;
905 return NULL;
906 }
907 }
908 Token *t = p->tokens[p->mark];
909 if (t->type != type) {
910 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
911 return NULL;
912 }
913 p->mark += 1;
914 return t;
915}
916
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700917expr_ty
918_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
919{
920 if (p->mark == p->fill) {
921 if (_PyPegen_fill_token(p) < 0) {
922 p->error_indicator = 1;
923 return NULL;
924 }
925 }
926 Token *t = p->tokens[p->mark];
927 if (t->type != NAME) {
928 return NULL;
929 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +0300930 const char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700931 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300932 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700933 return NULL;
934 }
935 if (strcmp(s, keyword) != 0) {
936 return NULL;
937 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300938 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700939}
940
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100941Token *
942_PyPegen_get_last_nonnwhitespace_token(Parser *p)
943{
944 assert(p->mark >= 0);
945 Token *token = NULL;
946 for (int m = p->mark - 1; m >= 0; m--) {
947 token = p->tokens[m];
948 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
949 break;
950 }
951 }
952 return token;
953}
954
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700955static expr_ty
956_PyPegen_name_from_token(Parser *p, Token* t)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100957{
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100958 if (t == NULL) {
959 return NULL;
960 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +0300961 const char *s = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100962 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300963 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100964 return NULL;
965 }
966 PyObject *id = _PyPegen_new_identifier(p, s);
967 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300968 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100969 return NULL;
970 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200971 return _PyAST_Name(id, Load, t->lineno, t->col_offset, t->end_lineno,
972 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100973}
974
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700975
976expr_ty
977_PyPegen_name_token(Parser *p)
978{
979 Token *t = _PyPegen_expect_token(p, NAME);
980 return _PyPegen_name_from_token(p, t);
981}
982
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100983void *
984_PyPegen_string_token(Parser *p)
985{
986 return _PyPegen_expect_token(p, STRING);
987}
988
Pablo Galindob2802482021-04-15 21:38:45 +0100989
990expr_ty _PyPegen_soft_keyword_token(Parser *p) {
991 Token *t = _PyPegen_expect_token(p, NAME);
992 if (t == NULL) {
993 return NULL;
994 }
995 char *the_token;
996 Py_ssize_t size;
997 PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
998 for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
999 if (strncmp(*keyword, the_token, size) == 0) {
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -07001000 return _PyPegen_name_from_token(p, t);
Pablo Galindob2802482021-04-15 21:38:45 +01001001 }
1002 }
1003 return NULL;
1004}
1005
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001006static PyObject *
1007parsenumber_raw(const char *s)
1008{
1009 const char *end;
1010 long x;
1011 double dx;
1012 Py_complex compl;
1013 int imflag;
1014
1015 assert(s != NULL);
1016 errno = 0;
1017 end = s + strlen(s) - 1;
1018 imflag = *end == 'j' || *end == 'J';
1019 if (s[0] == '0') {
1020 x = (long)PyOS_strtoul(s, (char **)&end, 0);
1021 if (x < 0 && errno == 0) {
1022 return PyLong_FromString(s, (char **)0, 0);
1023 }
1024 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001025 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001026 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001027 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001028 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +01001029 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001030 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001031 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001032 return PyLong_FromLong(x);
1033 }
1034 /* XXX Huge floats may silently fail */
1035 if (imflag) {
1036 compl.real = 0.;
1037 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +01001038 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001039 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +01001040 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001041 return PyComplex_FromCComplex(compl);
1042 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001043 dx = PyOS_string_to_double(s, NULL, NULL);
1044 if (dx == -1.0 && PyErr_Occurred()) {
1045 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001046 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001047 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001048}
1049
1050static PyObject *
1051parsenumber(const char *s)
1052{
Pablo Galindofb61c422020-06-15 14:23:43 +01001053 char *dup;
1054 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001055 PyObject *res = NULL;
1056
1057 assert(s != NULL);
1058
1059 if (strchr(s, '_') == NULL) {
1060 return parsenumber_raw(s);
1061 }
1062 /* Create a duplicate without underscores. */
1063 dup = PyMem_Malloc(strlen(s) + 1);
1064 if (dup == NULL) {
1065 return PyErr_NoMemory();
1066 }
1067 end = dup;
1068 for (; *s; s++) {
1069 if (*s != '_') {
1070 *end++ = *s;
1071 }
1072 }
1073 *end = '\0';
1074 res = parsenumber_raw(dup);
1075 PyMem_Free(dup);
1076 return res;
1077}
1078
1079expr_ty
1080_PyPegen_number_token(Parser *p)
1081{
1082 Token *t = _PyPegen_expect_token(p, NUMBER);
1083 if (t == NULL) {
1084 return NULL;
1085 }
1086
Serhiy Storchakac43317d2021-06-12 20:44:32 +03001087 const char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001088 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001089 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001090 return NULL;
1091 }
1092
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001093 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1094 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -07001095 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001096 "in Python 3.6 and greater");
1097 }
1098
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001099 PyObject *c = parsenumber(num_raw);
1100
1101 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001102 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001103 return NULL;
1104 }
1105
Victor Stinner8370e072021-03-24 02:23:01 +01001106 if (_PyArena_AddPyObject(p->arena, c) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001107 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001108 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001109 return NULL;
1110 }
1111
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001112 return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
1113 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001114}
1115
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001116static int // bool
1117newline_in_string(Parser *p, const char *cur)
1118{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001119 for (const char *c = cur; c >= p->tok->buf; c--) {
1120 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001121 return 1;
1122 }
1123 }
1124 return 0;
1125}
1126
1127/* Check that the source for a single input statement really is a single
1128 statement by looking at what is left in the buffer after parsing.
1129 Trailing whitespace and comments are OK. */
1130static int // bool
1131bad_single_statement(Parser *p)
1132{
1133 const char *cur = strchr(p->tok->buf, '\n');
1134
1135 /* Newlines are allowed if preceded by a line continuation character
1136 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001137 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1138 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001139 return 0;
1140 }
1141 char c = *cur;
1142
1143 for (;;) {
1144 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1145 c = *++cur;
1146 }
1147
1148 if (!c) {
1149 return 0;
1150 }
1151
1152 if (c != '#') {
1153 return 1;
1154 }
1155
1156 /* Suck up comment. */
1157 while (c && c != '\n') {
1158 c = *++cur;
1159 }
1160 }
1161}
1162
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001163void
1164_PyPegen_Parser_Free(Parser *p)
1165{
1166 Py_XDECREF(p->normalize);
1167 for (int i = 0; i < p->size; i++) {
1168 PyMem_Free(p->tokens[i]);
1169 }
1170 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001171 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001172 PyMem_Free(p);
1173}
1174
Pablo Galindo2b74c832020-04-27 18:02:07 +01001175static int
1176compute_parser_flags(PyCompilerFlags *flags)
1177{
1178 int parser_flags = 0;
1179 if (!flags) {
1180 return 0;
1181 }
1182 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1183 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1184 }
1185 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1186 parser_flags |= PyPARSE_IGNORE_COOKIE;
1187 }
1188 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1189 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1190 }
1191 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1192 parser_flags |= PyPARSE_TYPE_COMMENTS;
1193 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001194 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001195 parser_flags |= PyPARSE_ASYNC_HACKS;
1196 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001197 return parser_flags;
1198}
1199
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001200Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001201_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001202 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001203{
1204 Parser *p = PyMem_Malloc(sizeof(Parser));
1205 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001206 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001207 }
1208 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001209 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1210 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001211 p->tok = tok;
1212 p->keywords = NULL;
1213 p->n_keyword_lists = -1;
Pablo Galindob2802482021-04-15 21:38:45 +01001214 p->soft_keywords = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001215 p->tokens = PyMem_Malloc(sizeof(Token *));
1216 if (!p->tokens) {
1217 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001218 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001219 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001220 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001221 if (!p->tokens) {
1222 PyMem_Free(p->tokens);
1223 PyMem_Free(p);
1224 return (Parser *) PyErr_NoMemory();
1225 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001226 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1227 PyMem_Free(p->tokens[0]);
1228 PyMem_Free(p->tokens);
1229 PyMem_Free(p);
1230 return (Parser *) PyErr_NoMemory();
1231 }
1232
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001233 p->mark = 0;
1234 p->fill = 0;
1235 p->size = 1;
1236
1237 p->errcode = errcode;
1238 p->arena = arena;
1239 p->start_rule = start_rule;
1240 p->parsing_started = 0;
1241 p->normalize = NULL;
1242 p->error_indicator = 0;
1243
1244 p->starting_lineno = 0;
1245 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001246 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001247 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001248 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001249 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001250 p->call_invalid_rules = 0;
Miss Islington (bot)ae1732d2021-05-21 11:20:43 -07001251 p->in_raw_rule = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001252 return p;
1253}
1254
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001255static void
1256reset_parser_state(Parser *p)
1257{
1258 for (int i = 0; i < p->fill; i++) {
1259 p->tokens[i]->memo = NULL;
1260 }
1261 p->mark = 0;
1262 p->call_invalid_rules = 1;
Miss Islington (bot)1fb6b9e2021-05-22 15:23:26 -07001263 // Don't try to get extra tokens in interactive mode when trying to
1264 // raise specialized errors in the second pass.
1265 p->tok->interactive_underflow = IUNDERFLOW_STOP;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001266}
1267
Pablo Galindod6d63712021-01-19 23:59:33 +00001268static int
1269_PyPegen_check_tokenizer_errors(Parser *p) {
1270 // Tokenize the whole input to see if there are any tokenization
1271 // errors such as mistmatching parentheses. These will get priority
1272 // over generic syntax errors only if the line number of the error is
1273 // before the one that we had for the generic error.
1274
1275 // We don't want to tokenize to the end for interactive input
1276 if (p->tok->prompt != NULL) {
1277 return 0;
1278 }
1279
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001280 PyObject *type, *value, *traceback;
1281 PyErr_Fetch(&type, &value, &traceback);
1282
Pablo Galindod6d63712021-01-19 23:59:33 +00001283 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1284 Py_ssize_t current_err_line = current_token->lineno;
1285
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001286 int ret = 0;
1287
Pablo Galindod6d63712021-01-19 23:59:33 +00001288 for (;;) {
1289 const char *start;
1290 const char *end;
1291 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1292 case ERRORTOKEN:
1293 if (p->tok->level != 0) {
1294 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1295 if (current_err_line > error_lineno) {
1296 raise_unclosed_parentheses_error(p);
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001297 ret = -1;
1298 goto exit;
Pablo Galindod6d63712021-01-19 23:59:33 +00001299 }
1300 }
1301 break;
1302 case ENDMARKER:
1303 break;
1304 default:
1305 continue;
1306 }
1307 break;
1308 }
1309
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001310
1311exit:
1312 if (PyErr_Occurred()) {
1313 Py_XDECREF(value);
1314 Py_XDECREF(type);
1315 Py_XDECREF(traceback);
1316 } else {
1317 PyErr_Restore(type, value, traceback);
1318 }
1319 return ret;
Pablo Galindod6d63712021-01-19 23:59:33 +00001320}
1321
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001322void *
1323_PyPegen_run_parser(Parser *p)
1324{
1325 void *res = _PyPegen_parse(p);
1326 if (res == NULL) {
Pablo Galindo Salgado4ce55a22021-10-08 00:50:10 +01001327 if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_SyntaxError)) {
1328 return NULL;
1329 }
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001330 Token *last_token = p->tokens[p->fill - 1];
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001331 reset_parser_state(p);
1332 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001333 if (PyErr_Occurred()) {
Miss Islington (bot)933b5b62021-06-08 04:46:56 -07001334 // Prioritize tokenizer errors to custom syntax errors raised
1335 // on the second phase only if the errors come from the parser.
Pablo Galindo Salgado4ce55a22021-10-08 00:50:10 +01001336 if (p->tok->done == E_DONE && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
Miss Islington (bot)756b7b92021-05-03 18:06:45 -07001337 _PyPegen_check_tokenizer_errors(p);
1338 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001339 return NULL;
1340 }
1341 if (p->fill == 0) {
1342 RAISE_SYNTAX_ERROR("error at start before reading any input");
1343 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001344 else if (p->tok->done == E_EOF) {
Pablo Galindod6d63712021-01-19 23:59:33 +00001345 if (p->tok->level) {
1346 raise_unclosed_parentheses_error(p);
1347 } else {
1348 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1349 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001350 }
1351 else {
1352 if (p->tokens[p->fill-1]->type == INDENT) {
1353 RAISE_INDENTATION_ERROR("unexpected indent");
1354 }
1355 else if (p->tokens[p->fill-1]->type == DEDENT) {
1356 RAISE_INDENTATION_ERROR("unexpected unindent");
1357 }
1358 else {
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001359 // Use the last token we found on the first pass to avoid reporting
1360 // incorrect locations for generic syntax errors just because we reached
1361 // further away when trying to find specific syntax errors in the second
1362 // pass.
1363 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(last_token, "invalid syntax");
Pablo Galindoc3f167d2021-01-20 19:11:56 +00001364 // _PyPegen_check_tokenizer_errors will override the existing
1365 // generic SyntaxError we just raised if errors are found.
1366 _PyPegen_check_tokenizer_errors(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001367 }
1368 }
1369 return NULL;
1370 }
1371
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001372 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1373 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1374 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1375 }
1376
Victor Stinnere0bf70d2021-03-18 02:46:06 +01001377 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1378#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
Pablo Galindo13322262020-07-27 23:46:59 +01001379 if (p->start_rule == Py_single_input ||
1380 p->start_rule == Py_file_input ||
1381 p->start_rule == Py_eval_input)
1382 {
Victor Stinnereec8e612021-03-18 14:57:49 +01001383 if (!_PyAST_Validate(res)) {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001384 return NULL;
1385 }
Pablo Galindo13322262020-07-27 23:46:59 +01001386 }
1387#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001388 return res;
1389}
1390
1391mod_ty
1392_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1393 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001394 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001395{
1396 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1397 if (tok == NULL) {
1398 if (PyErr_Occurred()) {
1399 raise_tokenizer_init_error(filename_ob);
1400 return NULL;
1401 }
1402 return NULL;
1403 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001404 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1405 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1406 tok->fp_interactive = 1;
1407 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001408 // This transfers the ownership to the tokenizer
1409 tok->filename = filename_ob;
1410 Py_INCREF(filename_ob);
1411
1412 // From here on we need to clean up even if there's an error
1413 mod_ty result = NULL;
1414
Pablo Galindo2b74c832020-04-27 18:02:07 +01001415 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001416 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1417 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001418 if (p == NULL) {
1419 goto error;
1420 }
1421
1422 result = _PyPegen_run_parser(p);
1423 _PyPegen_Parser_Free(p);
1424
1425error:
1426 PyTokenizer_Free(tok);
1427 return result;
1428}
1429
1430mod_ty
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001431_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001432 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001433{
1434 int exec_input = start_rule == Py_file_input;
1435
1436 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001437 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001438 tok = PyTokenizer_FromUTF8(str, exec_input);
1439 } else {
1440 tok = PyTokenizer_FromString(str, exec_input);
1441 }
1442 if (tok == NULL) {
1443 if (PyErr_Occurred()) {
1444 raise_tokenizer_init_error(filename_ob);
1445 }
1446 return NULL;
1447 }
1448 // This transfers the ownership to the tokenizer
1449 tok->filename = filename_ob;
1450 Py_INCREF(filename_ob);
1451
1452 // We need to clear up from here on
1453 mod_ty result = NULL;
1454
Pablo Galindo2b74c832020-04-27 18:02:07 +01001455 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001456 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1457 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001458 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1459 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001460 if (p == NULL) {
1461 goto error;
1462 }
1463
1464 result = _PyPegen_run_parser(p);
1465 _PyPegen_Parser_Free(p);
1466
1467error:
1468 PyTokenizer_Free(tok);
1469 return result;
1470}
1471
Pablo Galindoa5634c42020-09-16 19:42:00 +01001472asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001473_PyPegen_interactive_exit(Parser *p)
1474{
1475 if (p->errcode) {
1476 *(p->errcode) = E_EOF;
1477 }
1478 return NULL;
1479}
1480
1481/* Creates a single-element asdl_seq* that contains a */
1482asdl_seq *
1483_PyPegen_singleton_seq(Parser *p, void *a)
1484{
1485 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001486 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001487 if (!seq) {
1488 return NULL;
1489 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001490 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001491 return seq;
1492}
1493
1494/* Creates a copy of seq and prepends a to it */
1495asdl_seq *
1496_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1497{
1498 assert(a != NULL);
1499 if (!seq) {
1500 return _PyPegen_singleton_seq(p, a);
1501 }
1502
Pablo Galindoa5634c42020-09-16 19:42:00 +01001503 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 +01001504 if (!new_seq) {
1505 return NULL;
1506 }
1507
Pablo Galindoa5634c42020-09-16 19:42:00 +01001508 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001509 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001510 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001511 }
1512 return new_seq;
1513}
1514
Guido van Rossumc001c092020-04-30 12:12:19 -07001515/* Creates a copy of seq and appends a to it */
1516asdl_seq *
1517_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1518{
1519 assert(a != NULL);
1520 if (!seq) {
1521 return _PyPegen_singleton_seq(p, a);
1522 }
1523
Pablo Galindoa5634c42020-09-16 19:42:00 +01001524 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 -07001525 if (!new_seq) {
1526 return NULL;
1527 }
1528
1529 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001530 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001531 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001532 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001533 return new_seq;
1534}
1535
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001536static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001537_get_flattened_seq_size(asdl_seq *seqs)
1538{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001539 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001540 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001541 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001542 size += asdl_seq_LEN(inner_seq);
1543 }
1544 return size;
1545}
1546
1547/* Flattens an asdl_seq* of asdl_seq*s */
1548asdl_seq *
1549_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1550{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001551 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001552 assert(flattened_seq_size > 0);
1553
Pablo Galindoa5634c42020-09-16 19:42:00 +01001554 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001555 if (!flattened_seq) {
1556 return NULL;
1557 }
1558
1559 int flattened_seq_idx = 0;
1560 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001561 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001562 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001563 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001564 }
1565 }
1566 assert(flattened_seq_idx == flattened_seq_size);
1567
1568 return flattened_seq;
1569}
1570
Pablo Galindoa77aac42021-04-23 14:27:05 +01001571void *
1572_PyPegen_seq_last_item(asdl_seq *seq)
1573{
1574 Py_ssize_t len = asdl_seq_LEN(seq);
1575 return asdl_seq_GET_UNTYPED(seq, len - 1);
1576}
1577
Miss Islington (bot)11f1a302021-06-24 08:34:28 -07001578void *
1579_PyPegen_seq_first_item(asdl_seq *seq)
1580{
1581 return asdl_seq_GET_UNTYPED(seq, 0);
1582}
1583
1584
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001585/* Creates a new name of the form <first_name>.<second_name> */
1586expr_ty
1587_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1588{
1589 assert(first_name != NULL && second_name != NULL);
1590 PyObject *first_identifier = first_name->v.Name.id;
1591 PyObject *second_identifier = second_name->v.Name.id;
1592
1593 if (PyUnicode_READY(first_identifier) == -1) {
1594 return NULL;
1595 }
1596 if (PyUnicode_READY(second_identifier) == -1) {
1597 return NULL;
1598 }
1599 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1600 if (!first_str) {
1601 return NULL;
1602 }
1603 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1604 if (!second_str) {
1605 return NULL;
1606 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001607 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001608
1609 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1610 if (!str) {
1611 return NULL;
1612 }
1613
1614 char *s = PyBytes_AS_STRING(str);
1615 if (!s) {
1616 return NULL;
1617 }
1618
1619 strcpy(s, first_str);
1620 s += strlen(first_str);
1621 *s++ = '.';
1622 strcpy(s, second_str);
1623 s += strlen(second_str);
1624 *s = '\0';
1625
1626 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1627 Py_DECREF(str);
1628 if (!uni) {
1629 return NULL;
1630 }
1631 PyUnicode_InternInPlace(&uni);
Victor Stinner8370e072021-03-24 02:23:01 +01001632 if (_PyArena_AddPyObject(p->arena, uni) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001633 Py_DECREF(uni);
1634 return NULL;
1635 }
1636
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001637 return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001638}
1639
1640/* Counts the total number of dots in seq's tokens */
1641int
1642_PyPegen_seq_count_dots(asdl_seq *seq)
1643{
1644 int number_of_dots = 0;
1645 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001646 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001647 switch (current_expr->type) {
1648 case ELLIPSIS:
1649 number_of_dots += 3;
1650 break;
1651 case DOT:
1652 number_of_dots += 1;
1653 break;
1654 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001655 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001656 }
1657 }
1658
1659 return number_of_dots;
1660}
1661
1662/* Creates an alias with '*' as the identifier name */
1663alias_ty
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001664_PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
1665 int end_col_offset, PyArena *arena) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001666 PyObject *str = PyUnicode_InternFromString("*");
1667 if (!str) {
1668 return NULL;
1669 }
Victor Stinner8370e072021-03-24 02:23:01 +01001670 if (_PyArena_AddPyObject(p->arena, str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001671 Py_DECREF(str);
1672 return NULL;
1673 }
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001674 return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001675}
1676
1677/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001678asdl_identifier_seq *
1679_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001680{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001681 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001682 assert(len > 0);
1683
Pablo Galindoa5634c42020-09-16 19:42:00 +01001684 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001685 if (!new_seq) {
1686 return NULL;
1687 }
1688 for (Py_ssize_t i = 0; i < len; i++) {
1689 expr_ty e = asdl_seq_GET(seq, i);
1690 asdl_seq_SET(new_seq, i, e->v.Name.id);
1691 }
1692 return new_seq;
1693}
1694
1695/* Constructs a CmpopExprPair */
1696CmpopExprPair *
1697_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1698{
1699 assert(expr != NULL);
Victor Stinner8370e072021-03-24 02:23:01 +01001700 CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001701 if (!a) {
1702 return NULL;
1703 }
1704 a->cmpop = cmpop;
1705 a->expr = expr;
1706 return a;
1707}
1708
1709asdl_int_seq *
1710_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1711{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001712 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001713 assert(len > 0);
1714
1715 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1716 if (!new_seq) {
1717 return NULL;
1718 }
1719 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001720 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001721 asdl_seq_SET(new_seq, i, pair->cmpop);
1722 }
1723 return new_seq;
1724}
1725
Pablo Galindoa5634c42020-09-16 19:42:00 +01001726asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001727_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1728{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001729 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001730 assert(len > 0);
1731
Pablo Galindoa5634c42020-09-16 19:42:00 +01001732 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001733 if (!new_seq) {
1734 return NULL;
1735 }
1736 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001737 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001738 asdl_seq_SET(new_seq, i, pair->expr);
1739 }
1740 return new_seq;
1741}
1742
1743/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001744static asdl_expr_seq *
1745_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001746{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001747 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001748 if (len == 0) {
1749 return NULL;
1750 }
1751
Pablo Galindoa5634c42020-09-16 19:42:00 +01001752 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001753 if (!new_seq) {
1754 return NULL;
1755 }
1756 for (Py_ssize_t i = 0; i < len; i++) {
1757 expr_ty e = asdl_seq_GET(seq, i);
1758 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1759 }
1760 return new_seq;
1761}
1762
1763static expr_ty
1764_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1765{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001766 return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001767}
1768
1769static expr_ty
1770_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1771{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001772 return _PyAST_Tuple(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001773 _set_seq_context(p, e->v.Tuple.elts, ctx),
1774 ctx,
1775 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001776}
1777
1778static expr_ty
1779_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1780{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001781 return _PyAST_List(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001782 _set_seq_context(p, e->v.List.elts, ctx),
1783 ctx,
1784 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001785}
1786
1787static expr_ty
1788_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1789{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001790 return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
1791 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001792}
1793
1794static expr_ty
1795_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1796{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001797 return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
1798 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001799}
1800
1801static expr_ty
1802_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1803{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001804 return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
1805 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001806}
1807
1808/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1809expr_ty
1810_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1811{
1812 assert(expr != NULL);
1813
1814 expr_ty new = NULL;
1815 switch (expr->kind) {
1816 case Name_kind:
1817 new = _set_name_context(p, expr, ctx);
1818 break;
1819 case Tuple_kind:
1820 new = _set_tuple_context(p, expr, ctx);
1821 break;
1822 case List_kind:
1823 new = _set_list_context(p, expr, ctx);
1824 break;
1825 case Subscript_kind:
1826 new = _set_subscript_context(p, expr, ctx);
1827 break;
1828 case Attribute_kind:
1829 new = _set_attribute_context(p, expr, ctx);
1830 break;
1831 case Starred_kind:
1832 new = _set_starred_context(p, expr, ctx);
1833 break;
1834 default:
1835 new = expr;
1836 }
1837 return new;
1838}
1839
1840/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1841KeyValuePair *
1842_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1843{
Victor Stinner8370e072021-03-24 02:23:01 +01001844 KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001845 if (!a) {
1846 return NULL;
1847 }
1848 a->key = key;
1849 a->value = value;
1850 return a;
1851}
1852
1853/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001854asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001855_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1856{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001857 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001858 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001859 if (!new_seq) {
1860 return NULL;
1861 }
1862 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001863 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001864 asdl_seq_SET(new_seq, i, pair->key);
1865 }
1866 return new_seq;
1867}
1868
1869/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001870asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001871_PyPegen_get_values(Parser *p, asdl_seq *seq)
1872{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001873 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001874 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001875 if (!new_seq) {
1876 return NULL;
1877 }
1878 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001879 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001880 asdl_seq_SET(new_seq, i, pair->value);
1881 }
1882 return new_seq;
1883}
1884
Nick Coghlan1e7b8582021-04-29 15:58:44 +10001885/* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
1886KeyPatternPair *
1887_PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
1888{
1889 KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
1890 if (!a) {
1891 return NULL;
1892 }
1893 a->key = key;
1894 a->pattern = pattern;
1895 return a;
1896}
1897
1898/* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
1899asdl_expr_seq *
1900_PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
1901{
1902 Py_ssize_t len = asdl_seq_LEN(seq);
1903 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1904 if (!new_seq) {
1905 return NULL;
1906 }
1907 for (Py_ssize_t i = 0; i < len; i++) {
1908 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1909 asdl_seq_SET(new_seq, i, pair->key);
1910 }
1911 return new_seq;
1912}
1913
1914/* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
1915asdl_pattern_seq *
1916_PyPegen_get_patterns(Parser *p, asdl_seq *seq)
1917{
1918 Py_ssize_t len = asdl_seq_LEN(seq);
1919 asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
1920 if (!new_seq) {
1921 return NULL;
1922 }
1923 for (Py_ssize_t i = 0; i < len; i++) {
1924 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1925 asdl_seq_SET(new_seq, i, pair->pattern);
1926 }
1927 return new_seq;
1928}
1929
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001930/* Constructs a NameDefaultPair */
1931NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001932_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001933{
Victor Stinner8370e072021-03-24 02:23:01 +01001934 NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001935 if (!a) {
1936 return NULL;
1937 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001938 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001939 a->value = value;
1940 return a;
1941}
1942
1943/* Constructs a SlashWithDefault */
1944SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001945_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001946{
Victor Stinner8370e072021-03-24 02:23:01 +01001947 SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001948 if (!a) {
1949 return NULL;
1950 }
1951 a->plain_names = plain_names;
1952 a->names_with_defaults = names_with_defaults;
1953 return a;
1954}
1955
1956/* Constructs a StarEtc */
1957StarEtc *
1958_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1959{
Victor Stinner8370e072021-03-24 02:23:01 +01001960 StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001961 if (!a) {
1962 return NULL;
1963 }
1964 a->vararg = vararg;
1965 a->kwonlyargs = kwonlyargs;
1966 a->kwarg = kwarg;
1967 return a;
1968}
1969
1970asdl_seq *
1971_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1972{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001973 Py_ssize_t first_len = asdl_seq_LEN(a);
1974 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001975 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001976 if (!new_seq) {
1977 return NULL;
1978 }
1979
1980 int k = 0;
1981 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001982 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001983 }
1984 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001985 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001986 }
1987
1988 return new_seq;
1989}
1990
Pablo Galindoa5634c42020-09-16 19:42:00 +01001991static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001992_get_names(Parser *p, asdl_seq *names_with_defaults)
1993{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001994 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001995 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001996 if (!seq) {
1997 return NULL;
1998 }
1999 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002000 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002001 asdl_seq_SET(seq, i, pair->arg);
2002 }
2003 return seq;
2004}
2005
Pablo Galindoa5634c42020-09-16 19:42:00 +01002006static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002007_get_defaults(Parser *p, asdl_seq *names_with_defaults)
2008{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002009 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01002010 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002011 if (!seq) {
2012 return NULL;
2013 }
2014 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002015 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002016 asdl_seq_SET(seq, i, pair->value);
2017 }
2018 return seq;
2019}
2020
Pablo Galindo4f642da2021-04-09 00:48:53 +01002021static int
2022_make_posonlyargs(Parser *p,
2023 asdl_arg_seq *slash_without_default,
2024 SlashWithDefault *slash_with_default,
2025 asdl_arg_seq **posonlyargs) {
2026 if (slash_without_default != NULL) {
2027 *posonlyargs = slash_without_default;
2028 }
2029 else if (slash_with_default != NULL) {
2030 asdl_arg_seq *slash_with_default_names =
2031 _get_names(p, slash_with_default->names_with_defaults);
2032 if (!slash_with_default_names) {
2033 return -1;
2034 }
2035 *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2036 p,
2037 (asdl_seq*)slash_with_default->plain_names,
2038 (asdl_seq*)slash_with_default_names);
2039 }
2040 else {
2041 *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2042 }
2043 return *posonlyargs == NULL ? -1 : 0;
2044}
2045
2046static int
2047_make_posargs(Parser *p,
2048 asdl_arg_seq *plain_names,
2049 asdl_seq *names_with_default,
2050 asdl_arg_seq **posargs) {
2051 if (plain_names != NULL && names_with_default != NULL) {
2052 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
2053 if (!names_with_default_names) {
2054 return -1;
2055 }
2056 *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2057 p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
2058 }
2059 else if (plain_names == NULL && names_with_default != NULL) {
2060 *posargs = _get_names(p, names_with_default);
2061 }
2062 else if (plain_names != NULL && names_with_default == NULL) {
2063 *posargs = plain_names;
2064 }
2065 else {
2066 *posargs = _Py_asdl_arg_seq_new(0, p->arena);
2067 }
2068 return *posargs == NULL ? -1 : 0;
2069}
2070
2071static int
2072_make_posdefaults(Parser *p,
2073 SlashWithDefault *slash_with_default,
2074 asdl_seq *names_with_default,
2075 asdl_expr_seq **posdefaults) {
2076 if (slash_with_default != NULL && names_with_default != NULL) {
2077 asdl_expr_seq *slash_with_default_values =
2078 _get_defaults(p, slash_with_default->names_with_defaults);
2079 if (!slash_with_default_values) {
2080 return -1;
2081 }
2082 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
2083 if (!names_with_default_values) {
2084 return -1;
2085 }
2086 *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
2087 p,
2088 (asdl_seq*)slash_with_default_values,
2089 (asdl_seq*)names_with_default_values);
2090 }
2091 else if (slash_with_default == NULL && names_with_default != NULL) {
2092 *posdefaults = _get_defaults(p, names_with_default);
2093 }
2094 else if (slash_with_default != NULL && names_with_default == NULL) {
2095 *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
2096 }
2097 else {
2098 *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2099 }
2100 return *posdefaults == NULL ? -1 : 0;
2101}
2102
2103static int
2104_make_kwargs(Parser *p, StarEtc *star_etc,
2105 asdl_arg_seq **kwonlyargs,
2106 asdl_expr_seq **kwdefaults) {
2107 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2108 *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
2109 }
2110 else {
2111 *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2112 }
2113
2114 if (*kwonlyargs == NULL) {
2115 return -1;
2116 }
2117
2118 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2119 *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
2120 }
2121 else {
2122 *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2123 }
2124
2125 if (*kwdefaults == NULL) {
2126 return -1;
2127 }
2128
2129 return 0;
2130}
2131
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002132/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
2133arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002134_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
2135 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002136 asdl_seq *names_with_default, StarEtc *star_etc)
2137{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002138 asdl_arg_seq *posonlyargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002139 if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
2140 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002141 }
2142
Pablo Galindoa5634c42020-09-16 19:42:00 +01002143 asdl_arg_seq *posargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002144 if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
2145 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002146 }
2147
Pablo Galindoa5634c42020-09-16 19:42:00 +01002148 asdl_expr_seq *posdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002149 if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
2150 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002151 }
2152
2153 arg_ty vararg = NULL;
2154 if (star_etc != NULL && star_etc->vararg != NULL) {
2155 vararg = star_etc->vararg;
2156 }
2157
Pablo Galindoa5634c42020-09-16 19:42:00 +01002158 asdl_arg_seq *kwonlyargs;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002159 asdl_expr_seq *kwdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002160 if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
2161 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002162 }
2163
2164 arg_ty kwarg = NULL;
2165 if (star_etc != NULL && star_etc->kwarg != NULL) {
2166 kwarg = star_etc->kwarg;
2167 }
2168
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002169 return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
2170 kwdefaults, kwarg, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002171}
2172
Pablo Galindo4f642da2021-04-09 00:48:53 +01002173
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002174/* Constructs an empty arguments_ty object, that gets used when a function accepts no
2175 * arguments. */
2176arguments_ty
2177_PyPegen_empty_arguments(Parser *p)
2178{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002179 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002180 if (!posonlyargs) {
2181 return NULL;
2182 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002183 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002184 if (!posargs) {
2185 return NULL;
2186 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002187 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002188 if (!posdefaults) {
2189 return NULL;
2190 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002191 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002192 if (!kwonlyargs) {
2193 return NULL;
2194 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002195 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002196 if (!kwdefaults) {
2197 return NULL;
2198 }
2199
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002200 return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
2201 kwdefaults, NULL, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002202}
2203
2204/* Encapsulates the value of an operator_ty into an AugOperator struct */
2205AugOperator *
2206_PyPegen_augoperator(Parser *p, operator_ty kind)
2207{
Victor Stinner8370e072021-03-24 02:23:01 +01002208 AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002209 if (!a) {
2210 return NULL;
2211 }
2212 a->kind = kind;
2213 return a;
2214}
2215
2216/* Construct a FunctionDef equivalent to function_def, but with decorators */
2217stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002218_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002219{
2220 assert(function_def != NULL);
2221 if (function_def->kind == AsyncFunctionDef_kind) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002222 return _PyAST_AsyncFunctionDef(
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002223 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2224 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2225 function_def->v.FunctionDef.type_comment, function_def->lineno,
2226 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2227 p->arena);
2228 }
2229
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002230 return _PyAST_FunctionDef(
2231 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2232 function_def->v.FunctionDef.body, decorators,
2233 function_def->v.FunctionDef.returns,
2234 function_def->v.FunctionDef.type_comment, function_def->lineno,
2235 function_def->col_offset, function_def->end_lineno,
2236 function_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002237}
2238
2239/* Construct a ClassDef equivalent to class_def, but with decorators */
2240stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002241_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002242{
2243 assert(class_def != NULL);
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002244 return _PyAST_ClassDef(
2245 class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2246 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2247 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2248 class_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002249}
2250
2251/* Construct a KeywordOrStarred */
2252KeywordOrStarred *
2253_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2254{
Victor Stinner8370e072021-03-24 02:23:01 +01002255 KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002256 if (!a) {
2257 return NULL;
2258 }
2259 a->element = element;
2260 a->is_keyword = is_keyword;
2261 return a;
2262}
2263
2264/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2265static int
2266_seq_number_of_starred_exprs(asdl_seq *seq)
2267{
2268 int n = 0;
2269 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002270 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002271 if (!k->is_keyword) {
2272 n++;
2273 }
2274 }
2275 return n;
2276}
2277
2278/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002279asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002280_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2281{
2282 int new_len = _seq_number_of_starred_exprs(kwargs);
2283 if (new_len == 0) {
2284 return NULL;
2285 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002286 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002287 if (!new_seq) {
2288 return NULL;
2289 }
2290
2291 int idx = 0;
2292 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002293 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002294 if (!k->is_keyword) {
2295 asdl_seq_SET(new_seq, idx++, k->element);
2296 }
2297 }
2298 return new_seq;
2299}
2300
2301/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002302asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002303_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2304{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002305 Py_ssize_t len = asdl_seq_LEN(kwargs);
2306 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002307 if (new_len == 0) {
2308 return NULL;
2309 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002310 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002311 if (!new_seq) {
2312 return NULL;
2313 }
2314
2315 int idx = 0;
2316 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002317 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002318 if (k->is_keyword) {
2319 asdl_seq_SET(new_seq, idx++, k->element);
2320 }
2321 }
2322 return new_seq;
2323}
2324
2325expr_ty
2326_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2327{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002328 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002329 assert(len > 0);
2330
Pablo Galindoa5634c42020-09-16 19:42:00 +01002331 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2332 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002333
2334 int bytesmode = 0;
2335 PyObject *bytes_str = NULL;
2336
2337 FstringParser state;
2338 _PyPegen_FstringParser_Init(&state);
2339
2340 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002341 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002342
2343 int this_bytesmode;
2344 int this_rawmode;
2345 PyObject *s;
2346 const char *fstr;
2347 Py_ssize_t fstrlen = -1;
2348
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002349 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002350 goto error;
2351 }
2352
2353 /* Check that we are not mixing bytes with unicode. */
2354 if (i != 0 && bytesmode != this_bytesmode) {
2355 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2356 Py_XDECREF(s);
2357 goto error;
2358 }
2359 bytesmode = this_bytesmode;
2360
2361 if (fstr != NULL) {
2362 assert(s == NULL && !bytesmode);
2363
2364 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2365 this_rawmode, 0, first, t, last);
2366 if (result < 0) {
2367 goto error;
2368 }
2369 }
2370 else {
2371 /* String or byte string. */
2372 assert(s != NULL && fstr == NULL);
2373 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2374
2375 if (bytesmode) {
2376 if (i == 0) {
2377 bytes_str = s;
2378 }
2379 else {
2380 PyBytes_ConcatAndDel(&bytes_str, s);
2381 if (!bytes_str) {
2382 goto error;
2383 }
2384 }
2385 }
2386 else {
2387 /* This is a regular string. Concatenate it. */
2388 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2389 goto error;
2390 }
2391 }
2392 }
2393 }
2394
2395 if (bytesmode) {
Victor Stinner8370e072021-03-24 02:23:01 +01002396 if (_PyArena_AddPyObject(p->arena, bytes_str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002397 goto error;
2398 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002399 return _PyAST_Constant(bytes_str, NULL, first->lineno,
2400 first->col_offset, last->end_lineno,
2401 last->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002402 }
2403
2404 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2405
2406error:
2407 Py_XDECREF(bytes_str);
2408 _PyPegen_FstringParser_Dealloc(&state);
2409 if (PyErr_Occurred()) {
2410 raise_decode_error(p);
2411 }
2412 return NULL;
2413}
Guido van Rossumc001c092020-04-30 12:12:19 -07002414
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002415expr_ty
2416_PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
2417{
2418 if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07002419 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
2420 return NULL;
2421 }
2422 return exp;
2423}
2424
2425expr_ty
2426_PyPegen_ensure_real(Parser *p, expr_ty exp)
2427{
2428 if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
2429 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002430 return NULL;
2431 }
2432 return exp;
2433}
2434
Guido van Rossumc001c092020-04-30 12:12:19 -07002435mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002436_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2437 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002438 Py_ssize_t num = p->type_ignore_comments.num_items;
2439 if (num > 0) {
2440 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002441 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002442 if (type_ignores == NULL) {
2443 return NULL;
2444 }
2445 for (int i = 0; i < num; i++) {
2446 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2447 if (tag == NULL) {
2448 return NULL;
2449 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002450 type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
2451 tag, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002452 if (ti == NULL) {
2453 return NULL;
2454 }
2455 asdl_seq_SET(type_ignores, i, ti);
2456 }
2457 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002458 return _PyAST_Module(a, type_ignores, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002459}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002460
2461// Error reporting helpers
2462
2463expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002464_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002465{
2466 if (e == NULL) {
2467 return NULL;
2468 }
2469
2470#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
Pablo Galindo58bafe42021-04-09 01:17:31 +01002471 Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002472 for (Py_ssize_t i = 0; i < len; i++) {\
Pablo Galindo58bafe42021-04-09 01:17:31 +01002473 expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002474 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002475 if (child != NULL) {\
2476 return child;\
2477 }\
2478 }\
2479 } while (0)
2480
2481 // We only need to visit List and Tuple nodes recursively as those
2482 // are the only ones that can contain valid names in targets when
2483 // they are parsed as expressions. Any other kind of expression
2484 // that is a container (like Sets or Dicts) is directly invalid and
2485 // we don't need to visit it recursively.
2486
2487 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002488 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002489 VISIT_CONTAINER(e, List);
2490 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002491 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002492 VISIT_CONTAINER(e, Tuple);
2493 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002494 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002495 if (targets_type == DEL_TARGETS) {
2496 return e;
2497 }
2498 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2499 case Compare_kind:
2500 // This is needed, because the `a in b` in `for a in b` gets parsed
2501 // as a comparison, and so we need to search the left side of the comparison
2502 // for invalid targets.
2503 if (targets_type == FOR_TARGETS) {
2504 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2505 if (cmpop == In) {
2506 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2507 }
2508 return NULL;
2509 }
2510 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002511 case Name_kind:
2512 case Subscript_kind:
2513 case Attribute_kind:
2514 return NULL;
2515 default:
2516 return e;
2517 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002518}
2519
2520void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2521 int kwarg_unpacking = 0;
2522 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2523 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2524 if (!keyword->arg) {
2525 kwarg_unpacking = 1;
2526 }
2527 }
2528
2529 const char *msg = NULL;
2530 if (kwarg_unpacking) {
2531 msg = "positional argument follows keyword argument unpacking";
2532 } else {
2533 msg = "positional argument follows keyword argument";
2534 }
2535
2536 return RAISE_SYNTAX_ERROR(msg);
2537}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002538
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002539
2540static inline expr_ty
2541_PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
2542 if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
2543 return comprehension->iter;
2544 }
2545 return PyPegen_last_item(comprehension->ifs, expr_ty);
2546}
2547
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002548void *
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002549_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions)
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002550{
2551 /* The rule that calls this function is 'args for_if_clauses'.
2552 For the input f(L, x for x in y), L and x are in args and
2553 the for is parsed as a for_if_clause. We have to check if
2554 len <= 1, so that input like dict((a, b) for a, b in x)
2555 gets successfully parsed and then we pass the last
2556 argument (x in the above example) as the location of the
2557 error */
2558 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2559 if (len <= 1) {
2560 return NULL;
2561 }
2562
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002563 comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
2564
2565 return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002566 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002567 _PyPegen_get_last_comprehension_item(last_comprehension),
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002568 "Generator expression must be parenthesized"
2569 );
2570}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002571
2572
Pablo Galindoa5634c42020-09-16 19:42:00 +01002573expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002574 int lineno, int col_offset, int end_lineno,
2575 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002576 Py_ssize_t args_len = asdl_seq_LEN(a);
2577 Py_ssize_t total_len = args_len;
2578
2579 if (b == NULL) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002580 return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002581 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002582
2583 }
2584
Pablo Galindoa5634c42020-09-16 19:42:00 +01002585 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2586 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002587
2588 if (starreds) {
2589 total_len += asdl_seq_LEN(starreds);
2590 }
2591
Pablo Galindoa5634c42020-09-16 19:42:00 +01002592 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002593
2594 Py_ssize_t i = 0;
2595 for (i = 0; i < args_len; i++) {
2596 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2597 }
2598 for (; i < total_len; i++) {
2599 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2600 }
2601
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002602 return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2603 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002604}