blob: 98f07a13c92cbb484b574b8f7557e17e5775e5fa [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) {
Pablo Galindo Salgado511ee1c2021-11-20 17:39:17 +000082 if (name->kind != Name_kind) {
83 return 0;
84 }
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +010085 const char* candidates[2] = {"print", "exec"};
86 for (int i=0; i<2; i++) {
87 if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
88 return 1;
89 }
90 }
91 return 0;
92}
93
Pablo Galindoc5fc1562020-04-22 23:29:27 +010094PyObject *
Serhiy Storchakac43317d2021-06-12 20:44:32 +030095_PyPegen_new_identifier(Parser *p, const char *n)
Pablo Galindoc5fc1562020-04-22 23:29:27 +010096{
97 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
98 if (!id) {
99 goto error;
100 }
101 /* PyUnicode_DecodeUTF8 should always return a ready string. */
102 assert(PyUnicode_IS_READY(id));
103 /* Check whether there are non-ASCII characters in the
104 identifier; if so, normalize to NFKC. */
105 if (!PyUnicode_IS_ASCII(id))
106 {
107 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300108 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100109 {
110 Py_DECREF(id);
111 goto error;
112 }
113 PyObject *form = PyUnicode_InternFromString("NFKC");
114 if (form == NULL)
115 {
116 Py_DECREF(id);
117 goto error;
118 }
119 PyObject *args[2] = {form, id};
120 id2 = _PyObject_FastCall(p->normalize, args, 2);
121 Py_DECREF(id);
122 Py_DECREF(form);
123 if (!id2) {
124 goto error;
125 }
126 if (!PyUnicode_Check(id2))
127 {
128 PyErr_Format(PyExc_TypeError,
129 "unicodedata.normalize() must return a string, not "
130 "%.200s",
131 _PyType_Name(Py_TYPE(id2)));
132 Py_DECREF(id2);
133 goto error;
134 }
135 id = id2;
136 }
137 PyUnicode_InternInPlace(&id);
Victor Stinner8370e072021-03-24 02:23:01 +0100138 if (_PyArena_AddPyObject(p->arena, id) < 0)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100139 {
140 Py_DECREF(id);
141 goto error;
142 }
143 return id;
144
145error:
146 p->error_indicator = 1;
147 return NULL;
148}
149
150static PyObject *
151_create_dummy_identifier(Parser *p)
152{
153 return _PyPegen_new_identifier(p, "");
154}
155
156static inline Py_ssize_t
Pablo Galindo51c58962020-06-16 16:49:43 +0100157byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100158{
159 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300160 if (!str) {
161 return 0;
162 }
Pablo Galindo123ff262021-03-22 16:24:39 +0000163 Py_ssize_t len = strlen(str);
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100164 if (col_offset > len + 1) {
165 col_offset = len + 1;
Pablo Galindo123ff262021-03-22 16:24:39 +0000166 }
167 assert(col_offset >= 0);
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300168 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100169 if (!text) {
170 return 0;
171 }
172 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
173 Py_DECREF(text);
174 return size;
175}
176
177const char *
178_PyPegen_get_expr_name(expr_ty e)
179{
Pablo Galindo9f495902020-06-08 02:57:00 +0100180 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100181 switch (e->kind) {
182 case Attribute_kind:
183 return "attribute";
184 case Subscript_kind:
185 return "subscript";
186 case Starred_kind:
187 return "starred";
188 case Name_kind:
189 return "name";
190 case List_kind:
191 return "list";
192 case Tuple_kind:
193 return "tuple";
194 case Lambda_kind:
195 return "lambda";
196 case Call_kind:
197 return "function call";
198 case BoolOp_kind:
199 case BinOp_kind:
200 case UnaryOp_kind:
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100201 return "expression";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100202 case GeneratorExp_kind:
203 return "generator expression";
204 case Yield_kind:
205 case YieldFrom_kind:
206 return "yield expression";
207 case Await_kind:
208 return "await expression";
209 case ListComp_kind:
210 return "list comprehension";
211 case SetComp_kind:
212 return "set comprehension";
213 case DictComp_kind:
214 return "dict comprehension";
215 case Dict_kind:
Pablo Galindob86ed8e2021-04-12 16:59:30 +0100216 return "dict literal";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100217 case Set_kind:
218 return "set display";
219 case JoinedStr_kind:
220 case FormattedValue_kind:
221 return "f-string expression";
222 case Constant_kind: {
223 PyObject *value = e->v.Constant.value;
224 if (value == Py_None) {
225 return "None";
226 }
227 if (value == Py_False) {
228 return "False";
229 }
230 if (value == Py_True) {
231 return "True";
232 }
233 if (value == Py_Ellipsis) {
Pablo Galindo3283bf42021-06-03 22:22:28 +0100234 return "ellipsis";
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100235 }
236 return "literal";
237 }
238 case Compare_kind:
239 return "comparison";
240 case IfExp_kind:
241 return "conditional expression";
242 case NamedExpr_kind:
243 return "named expression";
244 default:
245 PyErr_Format(PyExc_SystemError,
246 "unexpected expression in assignment %d (line %d)",
247 e->kind, e->lineno);
248 return NULL;
249 }
250}
251
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300252static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100253raise_decode_error(Parser *p)
254{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300255 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100256 const char *errtype = NULL;
257 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
258 errtype = "unicode error";
259 }
260 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
261 errtype = "value error";
262 }
263 if (errtype) {
Pablo Galindofb61c422020-06-15 14:23:43 +0100264 PyObject *type;
265 PyObject *value;
266 PyObject *tback;
267 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100268 PyErr_Fetch(&type, &value, &tback);
269 errstr = PyObject_Str(value);
270 if (errstr) {
271 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
272 Py_DECREF(errstr);
273 }
274 else {
275 PyErr_Clear();
276 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
277 }
278 Py_XDECREF(type);
279 Py_XDECREF(value);
280 Py_XDECREF(tback);
281 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300282
283 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100284}
285
Pablo Galindod6d63712021-01-19 23:59:33 +0000286static inline void
287raise_unclosed_parentheses_error(Parser *p) {
288 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
289 int error_col = p->tok->parencolstack[p->tok->level-1];
290 RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100291 error_lineno, error_col, error_lineno, -1,
Pablo Galindod6d63712021-01-19 23:59:33 +0000292 "'%c' was never closed",
293 p->tok->parenstack[p->tok->level-1]);
294}
295
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100296static void
297raise_tokenizer_init_error(PyObject *filename)
298{
299 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700300 || PyErr_ExceptionMatches(PyExc_SyntaxError)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100301 || PyErr_ExceptionMatches(PyExc_ValueError)
302 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
303 return;
304 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300305 PyObject *errstr = NULL;
306 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100307 PyObject *type;
308 PyObject *value;
309 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100310 PyErr_Fetch(&type, &value, &tback);
311 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300312 if (!errstr) {
313 goto error;
314 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100315
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300316 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100317 if (!tmp) {
318 goto error;
319 }
320
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300321 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100322 Py_DECREF(tmp);
323 if (!value) {
324 goto error;
325 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300326 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100327
328error:
329 Py_XDECREF(type);
330 Py_XDECREF(value);
331 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300332 Py_XDECREF(errstr);
333 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100334}
335
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100336static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100337tokenizer_error(Parser *p)
338{
339 if (PyErr_Occurred()) {
340 return -1;
341 }
342
343 const char *msg = NULL;
344 PyObject* errtype = PyExc_SyntaxError;
Pablo Galindo96eeff52021-03-22 17:28:11 +0000345 Py_ssize_t col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100346 switch (p->tok->done) {
347 case E_TOKEN:
348 msg = "invalid token";
349 break;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300350 case E_EOF:
Pablo Galindod6d63712021-01-19 23:59:33 +0000351 if (p->tok->level) {
352 raise_unclosed_parentheses_error(p);
353 } else {
354 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
355 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300356 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100357 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300358 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
359 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100360 case E_INTR:
361 if (!PyErr_Occurred()) {
362 PyErr_SetNone(PyExc_KeyboardInterrupt);
363 }
364 return -1;
365 case E_NOMEM:
366 PyErr_NoMemory();
367 return -1;
368 case E_TABSPACE:
369 errtype = PyExc_TabError;
370 msg = "inconsistent use of tabs and spaces in indentation";
371 break;
372 case E_TOODEEP:
373 errtype = PyExc_IndentationError;
374 msg = "too many levels of indentation";
375 break;
Łukasz Langa5c9cab52021-10-19 22:31:18 +0200376 case E_LINECONT: {
Miss Islington (bot)bf26a6d2021-11-13 17:30:03 -0800377 col_offset = p->tok->cur - p->tok->buf - 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100378 msg = "unexpected character after line continuation character";
379 break;
Łukasz Langa5c9cab52021-10-19 22:31:18 +0200380 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100381 default:
382 msg = "unknown parsing error";
383 }
384
Miss Islington (bot)bf26a6d2021-11-13 17:30:03 -0800385 RAISE_ERROR_KNOWN_LOCATION(p, errtype, p->tok->lineno,
386 col_offset >= 0 ? col_offset : 0,
387 p->tok->lineno, -1, msg);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100388 return -1;
389}
390
391void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300392_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
393{
Miss Islington (bot)b455df52021-11-17 15:43:14 -0800394 if (p->fill == 0) {
395 va_list va;
396 va_start(va, errmsg);
397 _PyPegen_raise_error_known_location(p, errtype, 0, 0, 0, -1, errmsg, va);
398 va_end(va);
399 return NULL;
400 }
401
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300402 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100403 Py_ssize_t col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100404 Py_ssize_t end_col_offset = -1;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300405 if (t->col_offset == -1) {
406 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
407 intptr_t, int);
408 } else {
409 col_offset = t->col_offset + 1;
410 }
411
Pablo Galindoa77aac42021-04-23 14:27:05 +0100412 if (t->end_col_offset != -1) {
413 end_col_offset = t->end_col_offset + 1;
414 }
415
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300416 va_list va;
417 va_start(va, errmsg);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100418 _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 +0300419 va_end(va);
420
421 return NULL;
422}
423
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200424static PyObject *
425get_error_line(Parser *p, Py_ssize_t lineno)
426{
Pablo Galindo123ff262021-03-22 16:24:39 +0000427 /* If the file descriptor is interactive, the source lines of the current
428 * (multi-line) statement are stored in p->tok->interactive_src_start.
429 * If not, we're parsing from a string, which means that the whole source
430 * is stored in p->tok->str. */
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200431 assert(p->tok->fp == NULL || p->tok->fp == stdin);
432
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100433 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
434
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200435 for (int i = 0; i < lineno - 1; i++) {
436 cur_line = strchr(cur_line, '\n') + 1;
437 }
438
439 char *next_newline;
440 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
441 next_newline = cur_line + strlen(cur_line);
442 }
443 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
444}
445
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300446void *
447_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100448 Py_ssize_t lineno, Py_ssize_t col_offset,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100449 Py_ssize_t end_lineno, Py_ssize_t end_col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300450 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100451{
452 PyObject *value = NULL;
453 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300454 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100455 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300456 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100457
Pablo Galindoa77aac42021-04-23 14:27:05 +0100458 if (end_lineno == CURRENT_POS) {
459 end_lineno = p->tok->lineno;
460 }
461 if (end_col_offset == CURRENT_POS) {
462 end_col_offset = p->tok->cur - p->tok->line_start;
463 }
464
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300465 if (p->start_rule == Py_fstring_input) {
466 const char *fstring_msg = "f-string: ";
467 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
468
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300469 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300470 if (!new_errmsg) {
471 return (void *) PyErr_NoMemory();
472 }
473
474 // Copy both strings into new buffer
475 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
476 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
477 new_errmsg[len] = 0;
478 errmsg = new_errmsg;
479 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100480 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100481 if (!errstr) {
482 goto error;
483 }
484
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100485 if (p->tok->fp_interactive) {
486 error_line = get_error_line(p, lineno);
487 }
Łukasz Langa904af3d2021-11-20 16:34:56 +0100488 else if (p->start_rule == Py_file_input) {
489 error_line = _PyErr_ProgramDecodedTextObject(p->tok->filename,
490 (int) lineno, p->tok->encoding);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100491 }
492
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300493 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200494 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
495 then we need to find the error line from some other source, because
496 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
497 failed or we're parsing from a string or the REPL. There's a third edge case where
498 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
499 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
500 does not physically exist */
Łukasz Langa904af3d2021-11-20 16:34:56 +0100501 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200502
Miss Islington (bot)bf26a6d2021-11-13 17:30:03 -0800503 if (p->tok->lineno <= lineno && p->tok->inp > p->tok->buf) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200504 Py_ssize_t size = p->tok->inp - p->tok->buf;
505 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
506 }
Łukasz Langa904af3d2021-11-20 16:34:56 +0100507 else if (p->tok->fp == NULL || p->tok->fp == stdin) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200508 error_line = get_error_line(p, lineno);
509 }
Łukasz Langa904af3d2021-11-20 16:34:56 +0100510 else {
511 error_line = PyUnicode_FromStringAndSize("", 0);
512 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300513 if (!error_line) {
514 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300515 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100516 }
517
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300518 if (p->start_rule == Py_fstring_input) {
519 col_offset -= p->starting_col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100520 end_col_offset -= p->starting_col_offset;
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300521 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100522
Pablo Galindo51c58962020-06-16 16:49:43 +0100523 Py_ssize_t col_number = col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100524 Py_ssize_t end_col_number = end_col_offset;
Pablo Galindo51c58962020-06-16 16:49:43 +0100525
526 if (p->tok->encoding != NULL) {
527 col_number = byte_offset_to_character_offset(error_line, col_offset);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100528 end_col_number = end_col_number > 0 ?
529 byte_offset_to_character_offset(error_line, end_col_offset) :
530 end_col_number;
Pablo Galindo51c58962020-06-16 16:49:43 +0100531 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100532 tmp = Py_BuildValue("(OiiNii)", p->tok->filename, lineno, col_number, error_line, end_lineno, end_col_number);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100533 if (!tmp) {
534 goto error;
535 }
536 value = PyTuple_Pack(2, errstr, tmp);
537 Py_DECREF(tmp);
538 if (!value) {
539 goto error;
540 }
541 PyErr_SetObject(errtype, value);
542
543 Py_DECREF(errstr);
544 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300545 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300546 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300547 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100548 return NULL;
549
550error:
551 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300552 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300553 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300554 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300555 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100556 return NULL;
557}
558
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100559#if 0
560static const char *
561token_name(int type)
562{
563 if (0 <= type && type <= N_TOKENS) {
564 return _PyParser_TokenNames[type];
565 }
566 return "<Huh?>";
567}
568#endif
569
570// Here, mark is the start of the node, while p->mark is the end.
571// If node==NULL, they should be the same.
572int
573_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
574{
575 // Insert in front
Victor Stinner8370e072021-03-24 02:23:01 +0100576 Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100577 if (m == NULL) {
578 return -1;
579 }
580 m->type = type;
581 m->node = node;
582 m->mark = p->mark;
583 m->next = p->tokens[mark]->memo;
584 p->tokens[mark]->memo = m;
585 return 0;
586}
587
588// Like _PyPegen_insert_memo(), but updates an existing node if found.
589int
590_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
591{
592 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
593 if (m->type == type) {
594 // Update existing node.
595 m->node = node;
596 m->mark = p->mark;
597 return 0;
598 }
599 }
600 // Insert new node.
601 return _PyPegen_insert_memo(p, mark, type, node);
602}
603
604// Return dummy NAME.
605void *
606_PyPegen_dummy_name(Parser *p, ...)
607{
608 static void *cache = NULL;
609
610 if (cache != NULL) {
611 return cache;
612 }
613
614 PyObject *id = _create_dummy_identifier(p);
615 if (!id) {
616 return NULL;
617 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200618 cache = _PyAST_Name(id, Load, 1, 0, 1, 0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100619 return cache;
620}
621
622static int
623_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
624{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300625 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100626 if (name_len >= p->n_keyword_lists ||
627 p->keywords[name_len] == NULL ||
628 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100629 return NAME;
630 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100631 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100632 if (strncmp(k->str, name, name_len) == 0) {
633 return k->type;
634 }
635 }
636 return NAME;
637}
638
Guido van Rossumc001c092020-04-30 12:12:19 -0700639static int
640growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
641 assert(initial_size > 0);
642 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
643 arr->size = initial_size;
644 arr->num_items = 0;
645
646 return arr->items != NULL;
647}
648
649static int
650growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
651 if (arr->num_items >= arr->size) {
652 size_t new_size = arr->size * 2;
653 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
654 if (!new_items_array) {
655 return 0;
656 }
657 arr->items = new_items_array;
658 arr->size = new_size;
659 }
660
661 arr->items[arr->num_items].lineno = lineno;
662 arr->items[arr->num_items].comment = comment; // Take ownership
663 arr->num_items++;
664 return 1;
665}
666
667static void
668growable_comment_array_deallocate(growable_comment_array *arr) {
669 for (unsigned i = 0; i < arr->num_items; i++) {
670 PyMem_Free(arr->items[i].comment);
671 }
672 PyMem_Free(arr->items);
673}
674
Pablo Galindod00a4492021-04-09 01:32:25 +0100675static int
676initialize_token(Parser *p, Token *token, const char *start, const char *end, int token_type) {
677 assert(token != NULL);
678
679 token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : token_type;
680 token->bytes = PyBytes_FromStringAndSize(start, end - start);
681 if (token->bytes == NULL) {
682 return -1;
683 }
684
685 if (_PyArena_AddPyObject(p->arena, token->bytes) < 0) {
686 Py_DECREF(token->bytes);
687 return -1;
688 }
689
690 const char *line_start = token_type == STRING ? p->tok->multi_line_start : p->tok->line_start;
691 int lineno = token_type == STRING ? p->tok->first_lineno : p->tok->lineno;
692 int end_lineno = p->tok->lineno;
693
694 int col_offset = (start != NULL && start >= line_start) ? (int)(start - line_start) : -1;
695 int end_col_offset = (end != NULL && end >= p->tok->line_start) ? (int)(end - p->tok->line_start) : -1;
696
697 token->lineno = p->starting_lineno + lineno;
698 token->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
699 token->end_lineno = p->starting_lineno + end_lineno;
700 token->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
701
702 p->fill += 1;
703
704 if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
705 return raise_decode_error(p);
706 }
707
708 return (token_type == ERRORTOKEN ? tokenizer_error(p) : 0);
709}
710
711static int
712_resize_tokens_array(Parser *p) {
713 int newsize = p->size * 2;
714 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
715 if (new_tokens == NULL) {
716 PyErr_NoMemory();
717 return -1;
718 }
719 p->tokens = new_tokens;
720
721 for (int i = p->size; i < newsize; i++) {
722 p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
723 if (p->tokens[i] == NULL) {
724 p->size = i; // Needed, in order to cleanup correctly after parser fails
725 PyErr_NoMemory();
726 return -1;
727 }
728 }
729 p->size = newsize;
730 return 0;
731}
732
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100733int
734_PyPegen_fill_token(Parser *p)
735{
Pablo Galindofb61c422020-06-15 14:23:43 +0100736 const char *start;
737 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100738 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700739
740 // Record and skip '# type: ignore' comments
741 while (type == TYPE_IGNORE) {
742 Py_ssize_t len = end - start;
743 char *tag = PyMem_Malloc(len + 1);
744 if (tag == NULL) {
745 PyErr_NoMemory();
746 return -1;
747 }
748 strncpy(tag, start, len);
749 tag[len] = '\0';
750 // Ownership of tag passes to the growable array
751 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
752 PyErr_NoMemory();
753 return -1;
754 }
755 type = PyTokenizer_Get(p->tok, &start, &end);
756 }
757
Pablo Galindod00a4492021-04-09 01:32:25 +0100758 // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
759 if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100760 type = NEWLINE; /* Add an extra newline */
761 p->parsing_started = 0;
762
Pablo Galindob94dbd72020-04-27 18:35:58 +0100763 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100764 p->tok->pendin = -p->tok->indent;
765 p->tok->indent = 0;
766 }
767 }
768 else {
769 p->parsing_started = 1;
770 }
771
Pablo Galindod00a4492021-04-09 01:32:25 +0100772 // Check if we are at the limit of the token array capacity and resize if needed
773 if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
774 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100775 }
776
777 Token *t = p->tokens[p->fill];
Pablo Galindod00a4492021-04-09 01:32:25 +0100778 return initialize_token(p, t, start, end, type);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100779}
780
Pablo Galindo58bafe42021-04-09 01:17:31 +0100781
782#if defined(Py_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100783// Instrumentation to count the effectiveness of memoization.
784// The array counts the number of tokens skipped by memoization,
785// indexed by type.
786
787#define NSTATISTICS 2000
788static long memo_statistics[NSTATISTICS];
789
790void
791_PyPegen_clear_memo_statistics()
792{
793 for (int i = 0; i < NSTATISTICS; i++) {
794 memo_statistics[i] = 0;
795 }
796}
797
798PyObject *
799_PyPegen_get_memo_statistics()
800{
801 PyObject *ret = PyList_New(NSTATISTICS);
802 if (ret == NULL) {
803 return NULL;
804 }
805 for (int i = 0; i < NSTATISTICS; i++) {
806 PyObject *value = PyLong_FromLong(memo_statistics[i]);
807 if (value == NULL) {
808 Py_DECREF(ret);
809 return NULL;
810 }
811 // PyList_SetItem borrows a reference to value.
812 if (PyList_SetItem(ret, i, value) < 0) {
813 Py_DECREF(ret);
814 return NULL;
815 }
816 }
817 return ret;
818}
Pablo Galindo58bafe42021-04-09 01:17:31 +0100819#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100820
821int // bool
822_PyPegen_is_memoized(Parser *p, int type, void *pres)
823{
824 if (p->mark == p->fill) {
825 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300826 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100827 return -1;
828 }
829 }
830
831 Token *t = p->tokens[p->mark];
832
833 for (Memo *m = t->memo; m != NULL; m = m->next) {
834 if (m->type == type) {
Pablo Galindo58bafe42021-04-09 01:17:31 +0100835#if defined(PY_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100836 if (0 <= type && type < NSTATISTICS) {
837 long count = m->mark - p->mark;
838 // A memoized negative result counts for one.
839 if (count <= 0) {
840 count = 1;
841 }
842 memo_statistics[type] += count;
843 }
Pablo Galindo58bafe42021-04-09 01:17:31 +0100844#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100845 p->mark = m->mark;
846 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100847 return 1;
848 }
849 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100850 return 0;
851}
852
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100853int
854_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
855{
856 int mark = p->mark;
857 void *res = func(p);
858 p->mark = mark;
859 return (res != NULL) == positive;
860}
861
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100862int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100863_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
864{
865 int mark = p->mark;
866 void *res = func(p, arg);
867 p->mark = mark;
868 return (res != NULL) == positive;
869}
870
871int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100872_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
873{
874 int mark = p->mark;
875 void *res = func(p, arg);
876 p->mark = mark;
877 return (res != NULL) == positive;
878}
879
880int
881_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
882{
883 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100884 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100885 p->mark = mark;
886 return (res != NULL) == positive;
887}
888
889Token *
890_PyPegen_expect_token(Parser *p, int type)
891{
892 if (p->mark == p->fill) {
893 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300894 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100895 return NULL;
896 }
897 }
898 Token *t = p->tokens[p->mark];
899 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100900 return NULL;
901 }
902 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100903 return t;
904}
905
Pablo Galindo58fb1562021-02-02 19:54:22 +0000906Token *
907_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
908
909 if (p->error_indicator == 1) {
910 return NULL;
911 }
912
913 if (p->mark == p->fill) {
914 if (_PyPegen_fill_token(p) < 0) {
915 p->error_indicator = 1;
916 return NULL;
917 }
918 }
919 Token *t = p->tokens[p->mark];
920 if (t->type != type) {
921 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
922 return NULL;
923 }
924 p->mark += 1;
925 return t;
926}
927
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700928expr_ty
929_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
930{
931 if (p->mark == p->fill) {
932 if (_PyPegen_fill_token(p) < 0) {
933 p->error_indicator = 1;
934 return NULL;
935 }
936 }
937 Token *t = p->tokens[p->mark];
938 if (t->type != NAME) {
939 return NULL;
940 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +0300941 const char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700942 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300943 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700944 return NULL;
945 }
946 if (strcmp(s, keyword) != 0) {
947 return NULL;
948 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300949 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700950}
951
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100952Token *
953_PyPegen_get_last_nonnwhitespace_token(Parser *p)
954{
955 assert(p->mark >= 0);
956 Token *token = NULL;
957 for (int m = p->mark - 1; m >= 0; m--) {
958 token = p->tokens[m];
959 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
960 break;
961 }
962 }
963 return token;
964}
965
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700966static expr_ty
967_PyPegen_name_from_token(Parser *p, Token* t)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100968{
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100969 if (t == NULL) {
970 return NULL;
971 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +0300972 const char *s = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100973 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300974 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100975 return NULL;
976 }
977 PyObject *id = _PyPegen_new_identifier(p, s);
978 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300979 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100980 return NULL;
981 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200982 return _PyAST_Name(id, Load, t->lineno, t->col_offset, t->end_lineno,
983 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100984}
985
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700986
987expr_ty
988_PyPegen_name_token(Parser *p)
989{
990 Token *t = _PyPegen_expect_token(p, NAME);
991 return _PyPegen_name_from_token(p, t);
992}
993
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100994void *
995_PyPegen_string_token(Parser *p)
996{
997 return _PyPegen_expect_token(p, STRING);
998}
999
Pablo Galindob2802482021-04-15 21:38:45 +01001000
1001expr_ty _PyPegen_soft_keyword_token(Parser *p) {
1002 Token *t = _PyPegen_expect_token(p, NAME);
1003 if (t == NULL) {
1004 return NULL;
1005 }
1006 char *the_token;
1007 Py_ssize_t size;
1008 PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
1009 for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
1010 if (strncmp(*keyword, the_token, size) == 0) {
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -07001011 return _PyPegen_name_from_token(p, t);
Pablo Galindob2802482021-04-15 21:38:45 +01001012 }
1013 }
1014 return NULL;
1015}
1016
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001017static PyObject *
1018parsenumber_raw(const char *s)
1019{
1020 const char *end;
1021 long x;
1022 double dx;
1023 Py_complex compl;
1024 int imflag;
1025
1026 assert(s != NULL);
1027 errno = 0;
1028 end = s + strlen(s) - 1;
1029 imflag = *end == 'j' || *end == 'J';
1030 if (s[0] == '0') {
1031 x = (long)PyOS_strtoul(s, (char **)&end, 0);
1032 if (x < 0 && errno == 0) {
1033 return PyLong_FromString(s, (char **)0, 0);
1034 }
1035 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001036 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001037 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001038 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001039 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +01001040 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001041 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001042 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001043 return PyLong_FromLong(x);
1044 }
1045 /* XXX Huge floats may silently fail */
1046 if (imflag) {
1047 compl.real = 0.;
1048 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +01001049 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001050 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +01001051 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001052 return PyComplex_FromCComplex(compl);
1053 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001054 dx = PyOS_string_to_double(s, NULL, NULL);
1055 if (dx == -1.0 && PyErr_Occurred()) {
1056 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001057 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001058 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001059}
1060
1061static PyObject *
1062parsenumber(const char *s)
1063{
Pablo Galindofb61c422020-06-15 14:23:43 +01001064 char *dup;
1065 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001066 PyObject *res = NULL;
1067
1068 assert(s != NULL);
1069
1070 if (strchr(s, '_') == NULL) {
1071 return parsenumber_raw(s);
1072 }
1073 /* Create a duplicate without underscores. */
1074 dup = PyMem_Malloc(strlen(s) + 1);
1075 if (dup == NULL) {
1076 return PyErr_NoMemory();
1077 }
1078 end = dup;
1079 for (; *s; s++) {
1080 if (*s != '_') {
1081 *end++ = *s;
1082 }
1083 }
1084 *end = '\0';
1085 res = parsenumber_raw(dup);
1086 PyMem_Free(dup);
1087 return res;
1088}
1089
1090expr_ty
1091_PyPegen_number_token(Parser *p)
1092{
1093 Token *t = _PyPegen_expect_token(p, NUMBER);
1094 if (t == NULL) {
1095 return NULL;
1096 }
1097
Serhiy Storchakac43317d2021-06-12 20:44:32 +03001098 const char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001099 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001100 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001101 return NULL;
1102 }
1103
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001104 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1105 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -07001106 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001107 "in Python 3.6 and greater");
1108 }
1109
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001110 PyObject *c = parsenumber(num_raw);
1111
1112 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001113 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001114 return NULL;
1115 }
1116
Victor Stinner8370e072021-03-24 02:23:01 +01001117 if (_PyArena_AddPyObject(p->arena, c) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001118 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001119 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001120 return NULL;
1121 }
1122
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001123 return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
1124 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001125}
1126
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001127static int // bool
1128newline_in_string(Parser *p, const char *cur)
1129{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001130 for (const char *c = cur; c >= p->tok->buf; c--) {
1131 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001132 return 1;
1133 }
1134 }
1135 return 0;
1136}
1137
1138/* Check that the source for a single input statement really is a single
1139 statement by looking at what is left in the buffer after parsing.
1140 Trailing whitespace and comments are OK. */
1141static int // bool
1142bad_single_statement(Parser *p)
1143{
1144 const char *cur = strchr(p->tok->buf, '\n');
1145
1146 /* Newlines are allowed if preceded by a line continuation character
1147 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001148 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1149 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001150 return 0;
1151 }
1152 char c = *cur;
1153
1154 for (;;) {
1155 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1156 c = *++cur;
1157 }
1158
1159 if (!c) {
1160 return 0;
1161 }
1162
1163 if (c != '#') {
1164 return 1;
1165 }
1166
1167 /* Suck up comment. */
1168 while (c && c != '\n') {
1169 c = *++cur;
1170 }
1171 }
1172}
1173
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001174void
1175_PyPegen_Parser_Free(Parser *p)
1176{
1177 Py_XDECREF(p->normalize);
1178 for (int i = 0; i < p->size; i++) {
1179 PyMem_Free(p->tokens[i]);
1180 }
1181 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001182 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001183 PyMem_Free(p);
1184}
1185
Pablo Galindo2b74c832020-04-27 18:02:07 +01001186static int
1187compute_parser_flags(PyCompilerFlags *flags)
1188{
1189 int parser_flags = 0;
1190 if (!flags) {
1191 return 0;
1192 }
1193 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1194 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1195 }
1196 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1197 parser_flags |= PyPARSE_IGNORE_COOKIE;
1198 }
1199 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1200 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1201 }
1202 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1203 parser_flags |= PyPARSE_TYPE_COMMENTS;
1204 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001205 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001206 parser_flags |= PyPARSE_ASYNC_HACKS;
1207 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001208 return parser_flags;
1209}
1210
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001211Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001212_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001213 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001214{
1215 Parser *p = PyMem_Malloc(sizeof(Parser));
1216 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001217 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001218 }
1219 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001220 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1221 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001222 p->tok = tok;
1223 p->keywords = NULL;
1224 p->n_keyword_lists = -1;
Pablo Galindob2802482021-04-15 21:38:45 +01001225 p->soft_keywords = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001226 p->tokens = PyMem_Malloc(sizeof(Token *));
1227 if (!p->tokens) {
1228 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001229 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001230 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001231 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001232 if (!p->tokens) {
1233 PyMem_Free(p->tokens);
1234 PyMem_Free(p);
1235 return (Parser *) PyErr_NoMemory();
1236 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001237 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1238 PyMem_Free(p->tokens[0]);
1239 PyMem_Free(p->tokens);
1240 PyMem_Free(p);
1241 return (Parser *) PyErr_NoMemory();
1242 }
1243
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001244 p->mark = 0;
1245 p->fill = 0;
1246 p->size = 1;
1247
1248 p->errcode = errcode;
1249 p->arena = arena;
1250 p->start_rule = start_rule;
1251 p->parsing_started = 0;
1252 p->normalize = NULL;
1253 p->error_indicator = 0;
1254
1255 p->starting_lineno = 0;
1256 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001257 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001258 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001259 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001260 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001261 p->call_invalid_rules = 0;
Miss Islington (bot)ae1732d2021-05-21 11:20:43 -07001262 p->in_raw_rule = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001263 return p;
1264}
1265
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001266static void
1267reset_parser_state(Parser *p)
1268{
1269 for (int i = 0; i < p->fill; i++) {
1270 p->tokens[i]->memo = NULL;
1271 }
1272 p->mark = 0;
1273 p->call_invalid_rules = 1;
Miss Islington (bot)1fb6b9e2021-05-22 15:23:26 -07001274 // Don't try to get extra tokens in interactive mode when trying to
1275 // raise specialized errors in the second pass.
1276 p->tok->interactive_underflow = IUNDERFLOW_STOP;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001277}
1278
Pablo Galindod6d63712021-01-19 23:59:33 +00001279static int
1280_PyPegen_check_tokenizer_errors(Parser *p) {
1281 // Tokenize the whole input to see if there are any tokenization
1282 // errors such as mistmatching parentheses. These will get priority
1283 // over generic syntax errors only if the line number of the error is
1284 // before the one that we had for the generic error.
1285
1286 // We don't want to tokenize to the end for interactive input
1287 if (p->tok->prompt != NULL) {
1288 return 0;
1289 }
1290
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001291 PyObject *type, *value, *traceback;
1292 PyErr_Fetch(&type, &value, &traceback);
1293
Pablo Galindod6d63712021-01-19 23:59:33 +00001294 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1295 Py_ssize_t current_err_line = current_token->lineno;
1296
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001297 int ret = 0;
1298
Pablo Galindod6d63712021-01-19 23:59:33 +00001299 for (;;) {
1300 const char *start;
1301 const char *end;
1302 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1303 case ERRORTOKEN:
1304 if (p->tok->level != 0) {
1305 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1306 if (current_err_line > error_lineno) {
1307 raise_unclosed_parentheses_error(p);
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001308 ret = -1;
1309 goto exit;
Pablo Galindod6d63712021-01-19 23:59:33 +00001310 }
1311 }
1312 break;
1313 case ENDMARKER:
1314 break;
1315 default:
1316 continue;
1317 }
1318 break;
1319 }
1320
Miss Islington (bot)2a8d7122021-06-08 12:25:17 -07001321
1322exit:
1323 if (PyErr_Occurred()) {
1324 Py_XDECREF(value);
1325 Py_XDECREF(type);
1326 Py_XDECREF(traceback);
1327 } else {
1328 PyErr_Restore(type, value, traceback);
1329 }
1330 return ret;
Pablo Galindod6d63712021-01-19 23:59:33 +00001331}
1332
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001333void *
1334_PyPegen_run_parser(Parser *p)
1335{
1336 void *res = _PyPegen_parse(p);
1337 if (res == NULL) {
Pablo Galindo Salgado4ce55a22021-10-08 00:50:10 +01001338 if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_SyntaxError)) {
1339 return NULL;
1340 }
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001341 Token *last_token = p->tokens[p->fill - 1];
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001342 reset_parser_state(p);
1343 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001344 if (PyErr_Occurred()) {
Miss Islington (bot)933b5b62021-06-08 04:46:56 -07001345 // Prioritize tokenizer errors to custom syntax errors raised
1346 // on the second phase only if the errors come from the parser.
Pablo Galindo Salgado4ce55a22021-10-08 00:50:10 +01001347 if (p->tok->done == E_DONE && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
Miss Islington (bot)756b7b92021-05-03 18:06:45 -07001348 _PyPegen_check_tokenizer_errors(p);
1349 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001350 return NULL;
1351 }
1352 if (p->fill == 0) {
1353 RAISE_SYNTAX_ERROR("error at start before reading any input");
1354 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001355 else if (p->tok->done == E_EOF) {
Pablo Galindod6d63712021-01-19 23:59:33 +00001356 if (p->tok->level) {
1357 raise_unclosed_parentheses_error(p);
1358 } else {
1359 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1360 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001361 }
1362 else {
1363 if (p->tokens[p->fill-1]->type == INDENT) {
1364 RAISE_INDENTATION_ERROR("unexpected indent");
1365 }
1366 else if (p->tokens[p->fill-1]->type == DEDENT) {
1367 RAISE_INDENTATION_ERROR("unexpected unindent");
1368 }
1369 else {
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001370 // Use the last token we found on the first pass to avoid reporting
1371 // incorrect locations for generic syntax errors just because we reached
1372 // further away when trying to find specific syntax errors in the second
1373 // pass.
1374 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(last_token, "invalid syntax");
Pablo Galindoc3f167d2021-01-20 19:11:56 +00001375 // _PyPegen_check_tokenizer_errors will override the existing
1376 // generic SyntaxError we just raised if errors are found.
1377 _PyPegen_check_tokenizer_errors(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001378 }
1379 }
1380 return NULL;
1381 }
1382
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001383 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1384 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1385 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1386 }
1387
Victor Stinnere0bf70d2021-03-18 02:46:06 +01001388 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1389#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
Pablo Galindo13322262020-07-27 23:46:59 +01001390 if (p->start_rule == Py_single_input ||
1391 p->start_rule == Py_file_input ||
1392 p->start_rule == Py_eval_input)
1393 {
Victor Stinnereec8e612021-03-18 14:57:49 +01001394 if (!_PyAST_Validate(res)) {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001395 return NULL;
1396 }
Pablo Galindo13322262020-07-27 23:46:59 +01001397 }
1398#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001399 return res;
1400}
1401
1402mod_ty
1403_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1404 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001405 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001406{
1407 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1408 if (tok == NULL) {
1409 if (PyErr_Occurred()) {
1410 raise_tokenizer_init_error(filename_ob);
1411 return NULL;
1412 }
1413 return NULL;
1414 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001415 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1416 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1417 tok->fp_interactive = 1;
1418 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001419 // This transfers the ownership to the tokenizer
1420 tok->filename = filename_ob;
1421 Py_INCREF(filename_ob);
1422
1423 // From here on we need to clean up even if there's an error
1424 mod_ty result = NULL;
1425
Pablo Galindo2b74c832020-04-27 18:02:07 +01001426 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001427 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1428 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001429 if (p == NULL) {
1430 goto error;
1431 }
1432
1433 result = _PyPegen_run_parser(p);
1434 _PyPegen_Parser_Free(p);
1435
1436error:
1437 PyTokenizer_Free(tok);
1438 return result;
1439}
1440
1441mod_ty
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001442_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001443 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001444{
1445 int exec_input = start_rule == Py_file_input;
1446
1447 struct tok_state *tok;
Pablo Galindo Salgadoe3aa9fd2021-11-17 23:17:18 +00001448 if (flags != NULL && flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001449 tok = PyTokenizer_FromUTF8(str, exec_input);
1450 } else {
1451 tok = PyTokenizer_FromString(str, exec_input);
1452 }
1453 if (tok == NULL) {
1454 if (PyErr_Occurred()) {
1455 raise_tokenizer_init_error(filename_ob);
1456 }
1457 return NULL;
1458 }
1459 // This transfers the ownership to the tokenizer
1460 tok->filename = filename_ob;
1461 Py_INCREF(filename_ob);
1462
1463 // We need to clear up from here on
1464 mod_ty result = NULL;
1465
Pablo Galindo2b74c832020-04-27 18:02:07 +01001466 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001467 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1468 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001469 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1470 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001471 if (p == NULL) {
1472 goto error;
1473 }
1474
1475 result = _PyPegen_run_parser(p);
1476 _PyPegen_Parser_Free(p);
1477
1478error:
1479 PyTokenizer_Free(tok);
1480 return result;
1481}
1482
Pablo Galindoa5634c42020-09-16 19:42:00 +01001483asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001484_PyPegen_interactive_exit(Parser *p)
1485{
1486 if (p->errcode) {
1487 *(p->errcode) = E_EOF;
1488 }
1489 return NULL;
1490}
1491
1492/* Creates a single-element asdl_seq* that contains a */
1493asdl_seq *
1494_PyPegen_singleton_seq(Parser *p, void *a)
1495{
1496 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001497 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001498 if (!seq) {
1499 return NULL;
1500 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001501 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001502 return seq;
1503}
1504
1505/* Creates a copy of seq and prepends a to it */
1506asdl_seq *
1507_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1508{
1509 assert(a != NULL);
1510 if (!seq) {
1511 return _PyPegen_singleton_seq(p, a);
1512 }
1513
Pablo Galindoa5634c42020-09-16 19:42:00 +01001514 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 +01001515 if (!new_seq) {
1516 return NULL;
1517 }
1518
Pablo Galindoa5634c42020-09-16 19:42:00 +01001519 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001520 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001521 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001522 }
1523 return new_seq;
1524}
1525
Guido van Rossumc001c092020-04-30 12:12:19 -07001526/* Creates a copy of seq and appends a to it */
1527asdl_seq *
1528_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1529{
1530 assert(a != NULL);
1531 if (!seq) {
1532 return _PyPegen_singleton_seq(p, a);
1533 }
1534
Pablo Galindoa5634c42020-09-16 19:42:00 +01001535 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 -07001536 if (!new_seq) {
1537 return NULL;
1538 }
1539
1540 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001541 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001542 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001543 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001544 return new_seq;
1545}
1546
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001547static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001548_get_flattened_seq_size(asdl_seq *seqs)
1549{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001550 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001551 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001552 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001553 size += asdl_seq_LEN(inner_seq);
1554 }
1555 return size;
1556}
1557
1558/* Flattens an asdl_seq* of asdl_seq*s */
1559asdl_seq *
1560_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1561{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001562 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001563 assert(flattened_seq_size > 0);
1564
Pablo Galindoa5634c42020-09-16 19:42:00 +01001565 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001566 if (!flattened_seq) {
1567 return NULL;
1568 }
1569
1570 int flattened_seq_idx = 0;
1571 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001572 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001573 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001574 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001575 }
1576 }
1577 assert(flattened_seq_idx == flattened_seq_size);
1578
1579 return flattened_seq;
1580}
1581
Pablo Galindoa77aac42021-04-23 14:27:05 +01001582void *
1583_PyPegen_seq_last_item(asdl_seq *seq)
1584{
1585 Py_ssize_t len = asdl_seq_LEN(seq);
1586 return asdl_seq_GET_UNTYPED(seq, len - 1);
1587}
1588
Miss Islington (bot)11f1a302021-06-24 08:34:28 -07001589void *
1590_PyPegen_seq_first_item(asdl_seq *seq)
1591{
1592 return asdl_seq_GET_UNTYPED(seq, 0);
1593}
1594
1595
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001596/* Creates a new name of the form <first_name>.<second_name> */
1597expr_ty
1598_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1599{
1600 assert(first_name != NULL && second_name != NULL);
1601 PyObject *first_identifier = first_name->v.Name.id;
1602 PyObject *second_identifier = second_name->v.Name.id;
1603
1604 if (PyUnicode_READY(first_identifier) == -1) {
1605 return NULL;
1606 }
1607 if (PyUnicode_READY(second_identifier) == -1) {
1608 return NULL;
1609 }
1610 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1611 if (!first_str) {
1612 return NULL;
1613 }
1614 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1615 if (!second_str) {
1616 return NULL;
1617 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001618 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001619
1620 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1621 if (!str) {
1622 return NULL;
1623 }
1624
1625 char *s = PyBytes_AS_STRING(str);
1626 if (!s) {
1627 return NULL;
1628 }
1629
1630 strcpy(s, first_str);
1631 s += strlen(first_str);
1632 *s++ = '.';
1633 strcpy(s, second_str);
1634 s += strlen(second_str);
1635 *s = '\0';
1636
1637 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1638 Py_DECREF(str);
1639 if (!uni) {
1640 return NULL;
1641 }
1642 PyUnicode_InternInPlace(&uni);
Victor Stinner8370e072021-03-24 02:23:01 +01001643 if (_PyArena_AddPyObject(p->arena, uni) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001644 Py_DECREF(uni);
1645 return NULL;
1646 }
1647
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001648 return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001649}
1650
1651/* Counts the total number of dots in seq's tokens */
1652int
1653_PyPegen_seq_count_dots(asdl_seq *seq)
1654{
1655 int number_of_dots = 0;
1656 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001657 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001658 switch (current_expr->type) {
1659 case ELLIPSIS:
1660 number_of_dots += 3;
1661 break;
1662 case DOT:
1663 number_of_dots += 1;
1664 break;
1665 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001666 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001667 }
1668 }
1669
1670 return number_of_dots;
1671}
1672
1673/* Creates an alias with '*' as the identifier name */
1674alias_ty
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001675_PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
1676 int end_col_offset, PyArena *arena) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001677 PyObject *str = PyUnicode_InternFromString("*");
1678 if (!str) {
1679 return NULL;
1680 }
Victor Stinner8370e072021-03-24 02:23:01 +01001681 if (_PyArena_AddPyObject(p->arena, str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001682 Py_DECREF(str);
1683 return NULL;
1684 }
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001685 return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001686}
1687
1688/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001689asdl_identifier_seq *
1690_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001691{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001692 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001693 assert(len > 0);
1694
Pablo Galindoa5634c42020-09-16 19:42:00 +01001695 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001696 if (!new_seq) {
1697 return NULL;
1698 }
1699 for (Py_ssize_t i = 0; i < len; i++) {
1700 expr_ty e = asdl_seq_GET(seq, i);
1701 asdl_seq_SET(new_seq, i, e->v.Name.id);
1702 }
1703 return new_seq;
1704}
1705
1706/* Constructs a CmpopExprPair */
1707CmpopExprPair *
1708_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1709{
1710 assert(expr != NULL);
Victor Stinner8370e072021-03-24 02:23:01 +01001711 CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001712 if (!a) {
1713 return NULL;
1714 }
1715 a->cmpop = cmpop;
1716 a->expr = expr;
1717 return a;
1718}
1719
1720asdl_int_seq *
1721_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1722{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001723 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001724 assert(len > 0);
1725
1726 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1727 if (!new_seq) {
1728 return NULL;
1729 }
1730 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001731 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001732 asdl_seq_SET(new_seq, i, pair->cmpop);
1733 }
1734 return new_seq;
1735}
1736
Pablo Galindoa5634c42020-09-16 19:42:00 +01001737asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001738_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1739{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001740 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001741 assert(len > 0);
1742
Pablo Galindoa5634c42020-09-16 19:42:00 +01001743 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001744 if (!new_seq) {
1745 return NULL;
1746 }
1747 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001748 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001749 asdl_seq_SET(new_seq, i, pair->expr);
1750 }
1751 return new_seq;
1752}
1753
1754/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001755static asdl_expr_seq *
1756_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001757{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001758 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001759 if (len == 0) {
1760 return NULL;
1761 }
1762
Pablo Galindoa5634c42020-09-16 19:42:00 +01001763 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001764 if (!new_seq) {
1765 return NULL;
1766 }
1767 for (Py_ssize_t i = 0; i < len; i++) {
1768 expr_ty e = asdl_seq_GET(seq, i);
1769 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1770 }
1771 return new_seq;
1772}
1773
1774static expr_ty
1775_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1776{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001777 return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001778}
1779
1780static expr_ty
1781_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1782{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001783 return _PyAST_Tuple(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001784 _set_seq_context(p, e->v.Tuple.elts, ctx),
1785 ctx,
1786 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001787}
1788
1789static expr_ty
1790_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1791{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001792 return _PyAST_List(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001793 _set_seq_context(p, e->v.List.elts, ctx),
1794 ctx,
1795 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001796}
1797
1798static expr_ty
1799_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1800{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001801 return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
1802 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001803}
1804
1805static expr_ty
1806_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1807{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001808 return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
1809 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001810}
1811
1812static expr_ty
1813_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1814{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001815 return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
1816 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001817}
1818
1819/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1820expr_ty
1821_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1822{
1823 assert(expr != NULL);
1824
1825 expr_ty new = NULL;
1826 switch (expr->kind) {
1827 case Name_kind:
1828 new = _set_name_context(p, expr, ctx);
1829 break;
1830 case Tuple_kind:
1831 new = _set_tuple_context(p, expr, ctx);
1832 break;
1833 case List_kind:
1834 new = _set_list_context(p, expr, ctx);
1835 break;
1836 case Subscript_kind:
1837 new = _set_subscript_context(p, expr, ctx);
1838 break;
1839 case Attribute_kind:
1840 new = _set_attribute_context(p, expr, ctx);
1841 break;
1842 case Starred_kind:
1843 new = _set_starred_context(p, expr, ctx);
1844 break;
1845 default:
1846 new = expr;
1847 }
1848 return new;
1849}
1850
1851/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1852KeyValuePair *
1853_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1854{
Victor Stinner8370e072021-03-24 02:23:01 +01001855 KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001856 if (!a) {
1857 return NULL;
1858 }
1859 a->key = key;
1860 a->value = value;
1861 return a;
1862}
1863
1864/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001865asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001866_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1867{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001868 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001869 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001870 if (!new_seq) {
1871 return NULL;
1872 }
1873 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001874 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001875 asdl_seq_SET(new_seq, i, pair->key);
1876 }
1877 return new_seq;
1878}
1879
1880/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001881asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001882_PyPegen_get_values(Parser *p, asdl_seq *seq)
1883{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001884 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001885 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001886 if (!new_seq) {
1887 return NULL;
1888 }
1889 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001890 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001891 asdl_seq_SET(new_seq, i, pair->value);
1892 }
1893 return new_seq;
1894}
1895
Nick Coghlan1e7b8582021-04-29 15:58:44 +10001896/* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
1897KeyPatternPair *
1898_PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
1899{
1900 KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
1901 if (!a) {
1902 return NULL;
1903 }
1904 a->key = key;
1905 a->pattern = pattern;
1906 return a;
1907}
1908
1909/* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
1910asdl_expr_seq *
1911_PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
1912{
1913 Py_ssize_t len = asdl_seq_LEN(seq);
1914 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
1915 if (!new_seq) {
1916 return NULL;
1917 }
1918 for (Py_ssize_t i = 0; i < len; i++) {
1919 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1920 asdl_seq_SET(new_seq, i, pair->key);
1921 }
1922 return new_seq;
1923}
1924
1925/* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
1926asdl_pattern_seq *
1927_PyPegen_get_patterns(Parser *p, asdl_seq *seq)
1928{
1929 Py_ssize_t len = asdl_seq_LEN(seq);
1930 asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
1931 if (!new_seq) {
1932 return NULL;
1933 }
1934 for (Py_ssize_t i = 0; i < len; i++) {
1935 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1936 asdl_seq_SET(new_seq, i, pair->pattern);
1937 }
1938 return new_seq;
1939}
1940
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001941/* Constructs a NameDefaultPair */
1942NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001943_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001944{
Victor Stinner8370e072021-03-24 02:23:01 +01001945 NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001946 if (!a) {
1947 return NULL;
1948 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001949 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001950 a->value = value;
1951 return a;
1952}
1953
1954/* Constructs a SlashWithDefault */
1955SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001956_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001957{
Victor Stinner8370e072021-03-24 02:23:01 +01001958 SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001959 if (!a) {
1960 return NULL;
1961 }
1962 a->plain_names = plain_names;
1963 a->names_with_defaults = names_with_defaults;
1964 return a;
1965}
1966
1967/* Constructs a StarEtc */
1968StarEtc *
1969_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1970{
Victor Stinner8370e072021-03-24 02:23:01 +01001971 StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001972 if (!a) {
1973 return NULL;
1974 }
1975 a->vararg = vararg;
1976 a->kwonlyargs = kwonlyargs;
1977 a->kwarg = kwarg;
1978 return a;
1979}
1980
1981asdl_seq *
1982_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1983{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001984 Py_ssize_t first_len = asdl_seq_LEN(a);
1985 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001986 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001987 if (!new_seq) {
1988 return NULL;
1989 }
1990
1991 int k = 0;
1992 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001993 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001994 }
1995 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001996 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001997 }
1998
1999 return new_seq;
2000}
2001
Pablo Galindoa5634c42020-09-16 19:42:00 +01002002static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002003_get_names(Parser *p, asdl_seq *names_with_defaults)
2004{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002005 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01002006 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002007 if (!seq) {
2008 return NULL;
2009 }
2010 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002011 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002012 asdl_seq_SET(seq, i, pair->arg);
2013 }
2014 return seq;
2015}
2016
Pablo Galindoa5634c42020-09-16 19:42:00 +01002017static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002018_get_defaults(Parser *p, asdl_seq *names_with_defaults)
2019{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002020 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01002021 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002022 if (!seq) {
2023 return NULL;
2024 }
2025 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002026 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002027 asdl_seq_SET(seq, i, pair->value);
2028 }
2029 return seq;
2030}
2031
Pablo Galindo4f642da2021-04-09 00:48:53 +01002032static int
2033_make_posonlyargs(Parser *p,
2034 asdl_arg_seq *slash_without_default,
2035 SlashWithDefault *slash_with_default,
2036 asdl_arg_seq **posonlyargs) {
2037 if (slash_without_default != NULL) {
2038 *posonlyargs = slash_without_default;
2039 }
2040 else if (slash_with_default != NULL) {
2041 asdl_arg_seq *slash_with_default_names =
2042 _get_names(p, slash_with_default->names_with_defaults);
2043 if (!slash_with_default_names) {
2044 return -1;
2045 }
2046 *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2047 p,
2048 (asdl_seq*)slash_with_default->plain_names,
2049 (asdl_seq*)slash_with_default_names);
2050 }
2051 else {
2052 *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2053 }
2054 return *posonlyargs == NULL ? -1 : 0;
2055}
2056
2057static int
2058_make_posargs(Parser *p,
2059 asdl_arg_seq *plain_names,
2060 asdl_seq *names_with_default,
2061 asdl_arg_seq **posargs) {
2062 if (plain_names != NULL && names_with_default != NULL) {
2063 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
2064 if (!names_with_default_names) {
2065 return -1;
2066 }
2067 *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2068 p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
2069 }
2070 else if (plain_names == NULL && names_with_default != NULL) {
2071 *posargs = _get_names(p, names_with_default);
2072 }
2073 else if (plain_names != NULL && names_with_default == NULL) {
2074 *posargs = plain_names;
2075 }
2076 else {
2077 *posargs = _Py_asdl_arg_seq_new(0, p->arena);
2078 }
2079 return *posargs == NULL ? -1 : 0;
2080}
2081
2082static int
2083_make_posdefaults(Parser *p,
2084 SlashWithDefault *slash_with_default,
2085 asdl_seq *names_with_default,
2086 asdl_expr_seq **posdefaults) {
2087 if (slash_with_default != NULL && names_with_default != NULL) {
2088 asdl_expr_seq *slash_with_default_values =
2089 _get_defaults(p, slash_with_default->names_with_defaults);
2090 if (!slash_with_default_values) {
2091 return -1;
2092 }
2093 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
2094 if (!names_with_default_values) {
2095 return -1;
2096 }
2097 *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
2098 p,
2099 (asdl_seq*)slash_with_default_values,
2100 (asdl_seq*)names_with_default_values);
2101 }
2102 else if (slash_with_default == NULL && names_with_default != NULL) {
2103 *posdefaults = _get_defaults(p, names_with_default);
2104 }
2105 else if (slash_with_default != NULL && names_with_default == NULL) {
2106 *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
2107 }
2108 else {
2109 *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2110 }
2111 return *posdefaults == NULL ? -1 : 0;
2112}
2113
2114static int
2115_make_kwargs(Parser *p, StarEtc *star_etc,
2116 asdl_arg_seq **kwonlyargs,
2117 asdl_expr_seq **kwdefaults) {
2118 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2119 *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
2120 }
2121 else {
2122 *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2123 }
2124
2125 if (*kwonlyargs == NULL) {
2126 return -1;
2127 }
2128
2129 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2130 *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
2131 }
2132 else {
2133 *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2134 }
2135
2136 if (*kwdefaults == NULL) {
2137 return -1;
2138 }
2139
2140 return 0;
2141}
2142
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002143/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
2144arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002145_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
2146 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002147 asdl_seq *names_with_default, StarEtc *star_etc)
2148{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002149 asdl_arg_seq *posonlyargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002150 if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
2151 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002152 }
2153
Pablo Galindoa5634c42020-09-16 19:42:00 +01002154 asdl_arg_seq *posargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002155 if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
2156 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002157 }
2158
Pablo Galindoa5634c42020-09-16 19:42:00 +01002159 asdl_expr_seq *posdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002160 if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
2161 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002162 }
2163
2164 arg_ty vararg = NULL;
2165 if (star_etc != NULL && star_etc->vararg != NULL) {
2166 vararg = star_etc->vararg;
2167 }
2168
Pablo Galindoa5634c42020-09-16 19:42:00 +01002169 asdl_arg_seq *kwonlyargs;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002170 asdl_expr_seq *kwdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002171 if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
2172 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002173 }
2174
2175 arg_ty kwarg = NULL;
2176 if (star_etc != NULL && star_etc->kwarg != NULL) {
2177 kwarg = star_etc->kwarg;
2178 }
2179
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002180 return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
2181 kwdefaults, kwarg, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002182}
2183
Pablo Galindo4f642da2021-04-09 00:48:53 +01002184
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002185/* Constructs an empty arguments_ty object, that gets used when a function accepts no
2186 * arguments. */
2187arguments_ty
2188_PyPegen_empty_arguments(Parser *p)
2189{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002190 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002191 if (!posonlyargs) {
2192 return NULL;
2193 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002194 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002195 if (!posargs) {
2196 return NULL;
2197 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002198 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002199 if (!posdefaults) {
2200 return NULL;
2201 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002202 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002203 if (!kwonlyargs) {
2204 return NULL;
2205 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002206 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002207 if (!kwdefaults) {
2208 return NULL;
2209 }
2210
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002211 return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
2212 kwdefaults, NULL, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002213}
2214
2215/* Encapsulates the value of an operator_ty into an AugOperator struct */
2216AugOperator *
2217_PyPegen_augoperator(Parser *p, operator_ty kind)
2218{
Victor Stinner8370e072021-03-24 02:23:01 +01002219 AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002220 if (!a) {
2221 return NULL;
2222 }
2223 a->kind = kind;
2224 return a;
2225}
2226
2227/* Construct a FunctionDef equivalent to function_def, but with decorators */
2228stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002229_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002230{
2231 assert(function_def != NULL);
2232 if (function_def->kind == AsyncFunctionDef_kind) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002233 return _PyAST_AsyncFunctionDef(
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002234 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2235 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2236 function_def->v.FunctionDef.type_comment, function_def->lineno,
2237 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2238 p->arena);
2239 }
2240
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002241 return _PyAST_FunctionDef(
2242 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2243 function_def->v.FunctionDef.body, decorators,
2244 function_def->v.FunctionDef.returns,
2245 function_def->v.FunctionDef.type_comment, function_def->lineno,
2246 function_def->col_offset, function_def->end_lineno,
2247 function_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002248}
2249
2250/* Construct a ClassDef equivalent to class_def, but with decorators */
2251stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002252_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002253{
2254 assert(class_def != NULL);
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002255 return _PyAST_ClassDef(
2256 class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2257 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2258 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2259 class_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002260}
2261
2262/* Construct a KeywordOrStarred */
2263KeywordOrStarred *
2264_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2265{
Victor Stinner8370e072021-03-24 02:23:01 +01002266 KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002267 if (!a) {
2268 return NULL;
2269 }
2270 a->element = element;
2271 a->is_keyword = is_keyword;
2272 return a;
2273}
2274
2275/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2276static int
2277_seq_number_of_starred_exprs(asdl_seq *seq)
2278{
2279 int n = 0;
2280 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002281 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002282 if (!k->is_keyword) {
2283 n++;
2284 }
2285 }
2286 return n;
2287}
2288
2289/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002290asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002291_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2292{
2293 int new_len = _seq_number_of_starred_exprs(kwargs);
2294 if (new_len == 0) {
2295 return NULL;
2296 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002297 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002298 if (!new_seq) {
2299 return NULL;
2300 }
2301
2302 int idx = 0;
2303 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002304 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002305 if (!k->is_keyword) {
2306 asdl_seq_SET(new_seq, idx++, k->element);
2307 }
2308 }
2309 return new_seq;
2310}
2311
2312/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002313asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002314_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2315{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002316 Py_ssize_t len = asdl_seq_LEN(kwargs);
2317 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002318 if (new_len == 0) {
2319 return NULL;
2320 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002321 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002322 if (!new_seq) {
2323 return NULL;
2324 }
2325
2326 int idx = 0;
2327 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002328 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002329 if (k->is_keyword) {
2330 asdl_seq_SET(new_seq, idx++, k->element);
2331 }
2332 }
2333 return new_seq;
2334}
2335
2336expr_ty
2337_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2338{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002339 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002340 assert(len > 0);
2341
Pablo Galindoa5634c42020-09-16 19:42:00 +01002342 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2343 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002344
2345 int bytesmode = 0;
2346 PyObject *bytes_str = NULL;
2347
2348 FstringParser state;
2349 _PyPegen_FstringParser_Init(&state);
2350
2351 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002352 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002353
2354 int this_bytesmode;
2355 int this_rawmode;
2356 PyObject *s;
2357 const char *fstr;
2358 Py_ssize_t fstrlen = -1;
2359
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002360 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002361 goto error;
2362 }
2363
2364 /* Check that we are not mixing bytes with unicode. */
2365 if (i != 0 && bytesmode != this_bytesmode) {
2366 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2367 Py_XDECREF(s);
2368 goto error;
2369 }
2370 bytesmode = this_bytesmode;
2371
2372 if (fstr != NULL) {
2373 assert(s == NULL && !bytesmode);
2374
2375 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2376 this_rawmode, 0, first, t, last);
2377 if (result < 0) {
2378 goto error;
2379 }
2380 }
2381 else {
2382 /* String or byte string. */
2383 assert(s != NULL && fstr == NULL);
2384 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2385
2386 if (bytesmode) {
2387 if (i == 0) {
2388 bytes_str = s;
2389 }
2390 else {
2391 PyBytes_ConcatAndDel(&bytes_str, s);
2392 if (!bytes_str) {
2393 goto error;
2394 }
2395 }
2396 }
2397 else {
2398 /* This is a regular string. Concatenate it. */
2399 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2400 goto error;
2401 }
2402 }
2403 }
2404 }
2405
2406 if (bytesmode) {
Victor Stinner8370e072021-03-24 02:23:01 +01002407 if (_PyArena_AddPyObject(p->arena, bytes_str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002408 goto error;
2409 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002410 return _PyAST_Constant(bytes_str, NULL, first->lineno,
2411 first->col_offset, last->end_lineno,
2412 last->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002413 }
2414
2415 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2416
2417error:
2418 Py_XDECREF(bytes_str);
2419 _PyPegen_FstringParser_Dealloc(&state);
2420 if (PyErr_Occurred()) {
2421 raise_decode_error(p);
2422 }
2423 return NULL;
2424}
Guido van Rossumc001c092020-04-30 12:12:19 -07002425
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002426expr_ty
2427_PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
2428{
2429 if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07002430 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
2431 return NULL;
2432 }
2433 return exp;
2434}
2435
2436expr_ty
2437_PyPegen_ensure_real(Parser *p, expr_ty exp)
2438{
2439 if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
2440 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002441 return NULL;
2442 }
2443 return exp;
2444}
2445
Guido van Rossumc001c092020-04-30 12:12:19 -07002446mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002447_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2448 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002449 Py_ssize_t num = p->type_ignore_comments.num_items;
2450 if (num > 0) {
2451 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002452 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002453 if (type_ignores == NULL) {
2454 return NULL;
2455 }
2456 for (int i = 0; i < num; i++) {
2457 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2458 if (tag == NULL) {
2459 return NULL;
2460 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002461 type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
2462 tag, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002463 if (ti == NULL) {
2464 return NULL;
2465 }
2466 asdl_seq_SET(type_ignores, i, ti);
2467 }
2468 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002469 return _PyAST_Module(a, type_ignores, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002470}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002471
2472// Error reporting helpers
2473
2474expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002475_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002476{
2477 if (e == NULL) {
2478 return NULL;
2479 }
2480
2481#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
Pablo Galindo58bafe42021-04-09 01:17:31 +01002482 Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002483 for (Py_ssize_t i = 0; i < len; i++) {\
Pablo Galindo58bafe42021-04-09 01:17:31 +01002484 expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002485 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002486 if (child != NULL) {\
2487 return child;\
2488 }\
2489 }\
2490 } while (0)
2491
2492 // We only need to visit List and Tuple nodes recursively as those
2493 // are the only ones that can contain valid names in targets when
2494 // they are parsed as expressions. Any other kind of expression
2495 // that is a container (like Sets or Dicts) is directly invalid and
2496 // we don't need to visit it recursively.
2497
2498 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002499 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002500 VISIT_CONTAINER(e, List);
2501 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002502 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002503 VISIT_CONTAINER(e, Tuple);
2504 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002505 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002506 if (targets_type == DEL_TARGETS) {
2507 return e;
2508 }
2509 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2510 case Compare_kind:
2511 // This is needed, because the `a in b` in `for a in b` gets parsed
2512 // as a comparison, and so we need to search the left side of the comparison
2513 // for invalid targets.
2514 if (targets_type == FOR_TARGETS) {
2515 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2516 if (cmpop == In) {
2517 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2518 }
2519 return NULL;
2520 }
2521 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002522 case Name_kind:
2523 case Subscript_kind:
2524 case Attribute_kind:
2525 return NULL;
2526 default:
2527 return e;
2528 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002529}
2530
2531void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2532 int kwarg_unpacking = 0;
2533 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2534 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2535 if (!keyword->arg) {
2536 kwarg_unpacking = 1;
2537 }
2538 }
2539
2540 const char *msg = NULL;
2541 if (kwarg_unpacking) {
2542 msg = "positional argument follows keyword argument unpacking";
2543 } else {
2544 msg = "positional argument follows keyword argument";
2545 }
2546
2547 return RAISE_SYNTAX_ERROR(msg);
2548}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002549
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002550
2551static inline expr_ty
2552_PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
2553 if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
2554 return comprehension->iter;
2555 }
2556 return PyPegen_last_item(comprehension->ifs, expr_ty);
2557}
2558
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002559void *
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002560_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions)
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002561{
2562 /* The rule that calls this function is 'args for_if_clauses'.
2563 For the input f(L, x for x in y), L and x are in args and
2564 the for is parsed as a for_if_clause. We have to check if
2565 len <= 1, so that input like dict((a, b) for a, b in x)
2566 gets successfully parsed and then we pass the last
2567 argument (x in the above example) as the location of the
2568 error */
2569 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2570 if (len <= 1) {
2571 return NULL;
2572 }
2573
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002574 comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
2575
2576 return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002577 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002578 _PyPegen_get_last_comprehension_item(last_comprehension),
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002579 "Generator expression must be parenthesized"
2580 );
2581}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002582
2583
Pablo Galindoa5634c42020-09-16 19:42:00 +01002584expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002585 int lineno, int col_offset, int end_lineno,
2586 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002587 Py_ssize_t args_len = asdl_seq_LEN(a);
2588 Py_ssize_t total_len = args_len;
2589
2590 if (b == NULL) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002591 return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002592 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002593
2594 }
2595
Pablo Galindoa5634c42020-09-16 19:42:00 +01002596 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2597 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002598
2599 if (starreds) {
2600 total_len += asdl_seq_LEN(starreds);
2601 }
2602
Pablo Galindoa5634c42020-09-16 19:42:00 +01002603 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002604
2605 Py_ssize_t i = 0;
2606 for (i = 0; i < args_len; i++) {
2607 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2608 }
2609 for (; i < total_len; i++) {
2610 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2611 }
2612
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002613 return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2614 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002615}