blob: d7a498393753e0b6297291d2443c9c7c3b3bdda7 [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) {
Miss Islington (bot)a427eb82021-11-20 09:59:34 -0800406 if (p->tok->cur == p->tok->buf) {
407 col_offset = 0;
408 } else {
409 const char* start = p->tok->buf ? p->tok->line_start : p->tok->buf;
410 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - start, intptr_t, int);
411 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300412 } else {
413 col_offset = t->col_offset + 1;
414 }
415
Pablo Galindoa77aac42021-04-23 14:27:05 +0100416 if (t->end_col_offset != -1) {
417 end_col_offset = t->end_col_offset + 1;
418 }
419
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300420 va_list va;
421 va_start(va, errmsg);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100422 _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 +0300423 va_end(va);
424
425 return NULL;
426}
427
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200428static PyObject *
429get_error_line(Parser *p, Py_ssize_t lineno)
430{
Pablo Galindo123ff262021-03-22 16:24:39 +0000431 /* If the file descriptor is interactive, the source lines of the current
432 * (multi-line) statement are stored in p->tok->interactive_src_start.
433 * If not, we're parsing from a string, which means that the whole source
434 * is stored in p->tok->str. */
Pablo Galindo Salgado07cf66f2021-11-21 04:15:22 +0000435 assert((p->tok->fp == NULL && p->tok->str != NULL) || p->tok->fp == stdin);
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200436
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100437 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
Miss Islington (bot)a427eb82021-11-20 09:59:34 -0800438 assert(cur_line != NULL);
Miss Islington (bot)1fb1f5d2022-01-20 05:05:10 -0800439 const char* buf_end = p->tok->fp_interactive ? p->tok->interactive_src_end : p->tok->inp;
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100440
Miss Islington (bot)1fb1f5d2022-01-20 05:05:10 -0800441 Py_ssize_t relative_lineno = p->starting_lineno ? lineno - p->starting_lineno + 1 : lineno;
442
443 for (int i = 0; i < relative_lineno - 1; i++) {
444 char *new_line = strchr(cur_line, '\n') + 1;
445 assert(new_line != NULL && new_line <= buf_end);
446 if (new_line == NULL || new_line > buf_end) {
447 break;
448 }
449 cur_line = new_line;
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200450 }
451
452 char *next_newline;
453 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
454 next_newline = cur_line + strlen(cur_line);
455 }
456 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
457}
458
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300459void *
460_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100461 Py_ssize_t lineno, Py_ssize_t col_offset,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100462 Py_ssize_t end_lineno, Py_ssize_t end_col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300463 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100464{
465 PyObject *value = NULL;
466 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300467 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100468 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300469 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100470
Pablo Galindoa77aac42021-04-23 14:27:05 +0100471 if (end_lineno == CURRENT_POS) {
472 end_lineno = p->tok->lineno;
473 }
474 if (end_col_offset == CURRENT_POS) {
475 end_col_offset = p->tok->cur - p->tok->line_start;
476 }
477
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300478 if (p->start_rule == Py_fstring_input) {
479 const char *fstring_msg = "f-string: ";
480 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
481
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300482 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300483 if (!new_errmsg) {
484 return (void *) PyErr_NoMemory();
485 }
486
487 // Copy both strings into new buffer
488 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
489 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
490 new_errmsg[len] = 0;
491 errmsg = new_errmsg;
492 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100493 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100494 if (!errstr) {
495 goto error;
496 }
497
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100498 if (p->tok->fp_interactive) {
499 error_line = get_error_line(p, lineno);
500 }
Łukasz Langa904af3d2021-11-20 16:34:56 +0100501 else if (p->start_rule == Py_file_input) {
502 error_line = _PyErr_ProgramDecodedTextObject(p->tok->filename,
503 (int) lineno, p->tok->encoding);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100504 }
505
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300506 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200507 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
508 then we need to find the error line from some other source, because
509 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
510 failed or we're parsing from a string or the REPL. There's a third edge case where
511 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
512 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
513 does not physically exist */
Łukasz Langa904af3d2021-11-20 16:34:56 +0100514 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200515
Miss Islington (bot)bf26a6d2021-11-13 17:30:03 -0800516 if (p->tok->lineno <= lineno && p->tok->inp > p->tok->buf) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200517 Py_ssize_t size = p->tok->inp - p->tok->buf;
518 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
519 }
Łukasz Langa904af3d2021-11-20 16:34:56 +0100520 else if (p->tok->fp == NULL || p->tok->fp == stdin) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200521 error_line = get_error_line(p, lineno);
522 }
Łukasz Langa904af3d2021-11-20 16:34:56 +0100523 else {
524 error_line = PyUnicode_FromStringAndSize("", 0);
525 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300526 if (!error_line) {
527 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300528 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100529 }
530
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300531 if (p->start_rule == Py_fstring_input) {
532 col_offset -= p->starting_col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100533 end_col_offset -= p->starting_col_offset;
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300534 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100535
Pablo Galindo51c58962020-06-16 16:49:43 +0100536 Py_ssize_t col_number = col_offset;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100537 Py_ssize_t end_col_number = end_col_offset;
Pablo Galindo51c58962020-06-16 16:49:43 +0100538
539 if (p->tok->encoding != NULL) {
540 col_number = byte_offset_to_character_offset(error_line, col_offset);
Pablo Galindoa77aac42021-04-23 14:27:05 +0100541 end_col_number = end_col_number > 0 ?
542 byte_offset_to_character_offset(error_line, end_col_offset) :
543 end_col_number;
Pablo Galindo51c58962020-06-16 16:49:43 +0100544 }
Pablo Galindoa77aac42021-04-23 14:27:05 +0100545 tmp = Py_BuildValue("(OiiNii)", p->tok->filename, lineno, col_number, error_line, end_lineno, end_col_number);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100546 if (!tmp) {
547 goto error;
548 }
549 value = PyTuple_Pack(2, errstr, tmp);
550 Py_DECREF(tmp);
551 if (!value) {
552 goto error;
553 }
554 PyErr_SetObject(errtype, value);
555
556 Py_DECREF(errstr);
557 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300558 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300559 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300560 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100561 return NULL;
562
563error:
564 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300565 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300566 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300567 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300568 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100569 return NULL;
570}
571
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100572#if 0
573static const char *
574token_name(int type)
575{
576 if (0 <= type && type <= N_TOKENS) {
577 return _PyParser_TokenNames[type];
578 }
579 return "<Huh?>";
580}
581#endif
582
583// Here, mark is the start of the node, while p->mark is the end.
584// If node==NULL, they should be the same.
585int
586_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
587{
588 // Insert in front
Victor Stinner8370e072021-03-24 02:23:01 +0100589 Memo *m = _PyArena_Malloc(p->arena, sizeof(Memo));
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100590 if (m == NULL) {
591 return -1;
592 }
593 m->type = type;
594 m->node = node;
595 m->mark = p->mark;
596 m->next = p->tokens[mark]->memo;
597 p->tokens[mark]->memo = m;
598 return 0;
599}
600
601// Like _PyPegen_insert_memo(), but updates an existing node if found.
602int
603_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
604{
605 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
606 if (m->type == type) {
607 // Update existing node.
608 m->node = node;
609 m->mark = p->mark;
610 return 0;
611 }
612 }
613 // Insert new node.
614 return _PyPegen_insert_memo(p, mark, type, node);
615}
616
617// Return dummy NAME.
618void *
619_PyPegen_dummy_name(Parser *p, ...)
620{
621 static void *cache = NULL;
622
623 if (cache != NULL) {
624 return cache;
625 }
626
627 PyObject *id = _create_dummy_identifier(p);
628 if (!id) {
629 return NULL;
630 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200631 cache = _PyAST_Name(id, Load, 1, 0, 1, 0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100632 return cache;
633}
634
635static int
636_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
637{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300638 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100639 if (name_len >= p->n_keyword_lists ||
640 p->keywords[name_len] == NULL ||
641 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100642 return NAME;
643 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100644 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100645 if (strncmp(k->str, name, name_len) == 0) {
646 return k->type;
647 }
648 }
649 return NAME;
650}
651
Guido van Rossumc001c092020-04-30 12:12:19 -0700652static int
653growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
654 assert(initial_size > 0);
655 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
656 arr->size = initial_size;
657 arr->num_items = 0;
658
659 return arr->items != NULL;
660}
661
662static int
663growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
664 if (arr->num_items >= arr->size) {
665 size_t new_size = arr->size * 2;
666 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
667 if (!new_items_array) {
668 return 0;
669 }
670 arr->items = new_items_array;
671 arr->size = new_size;
672 }
673
674 arr->items[arr->num_items].lineno = lineno;
675 arr->items[arr->num_items].comment = comment; // Take ownership
676 arr->num_items++;
677 return 1;
678}
679
680static void
681growable_comment_array_deallocate(growable_comment_array *arr) {
682 for (unsigned i = 0; i < arr->num_items; i++) {
683 PyMem_Free(arr->items[i].comment);
684 }
685 PyMem_Free(arr->items);
686}
687
Pablo Galindod00a4492021-04-09 01:32:25 +0100688static int
689initialize_token(Parser *p, Token *token, const char *start, const char *end, int token_type) {
690 assert(token != NULL);
691
692 token->type = (token_type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : token_type;
693 token->bytes = PyBytes_FromStringAndSize(start, end - start);
694 if (token->bytes == NULL) {
695 return -1;
696 }
697
698 if (_PyArena_AddPyObject(p->arena, token->bytes) < 0) {
699 Py_DECREF(token->bytes);
700 return -1;
701 }
702
Pablo Galindo Salgadoc72311d2021-11-25 01:01:40 +0000703 token->level = p->tok->level;
704
Pablo Galindod00a4492021-04-09 01:32:25 +0100705 const char *line_start = token_type == STRING ? p->tok->multi_line_start : p->tok->line_start;
706 int lineno = token_type == STRING ? p->tok->first_lineno : p->tok->lineno;
707 int end_lineno = p->tok->lineno;
708
709 int col_offset = (start != NULL && start >= line_start) ? (int)(start - line_start) : -1;
710 int end_col_offset = (end != NULL && end >= p->tok->line_start) ? (int)(end - p->tok->line_start) : -1;
711
Miss Islington (bot)19a85502022-01-11 08:33:08 -0800712 token->lineno = lineno;
713 token->col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + col_offset : col_offset;
714 token->end_lineno = end_lineno;
715 token->end_col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + end_col_offset : end_col_offset;
Pablo Galindod00a4492021-04-09 01:32:25 +0100716
717 p->fill += 1;
718
719 if (token_type == ERRORTOKEN && p->tok->done == E_DECODE) {
720 return raise_decode_error(p);
721 }
722
723 return (token_type == ERRORTOKEN ? tokenizer_error(p) : 0);
724}
725
726static int
727_resize_tokens_array(Parser *p) {
728 int newsize = p->size * 2;
729 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
730 if (new_tokens == NULL) {
731 PyErr_NoMemory();
732 return -1;
733 }
734 p->tokens = new_tokens;
735
736 for (int i = p->size; i < newsize; i++) {
737 p->tokens[i] = PyMem_Calloc(1, sizeof(Token));
738 if (p->tokens[i] == NULL) {
739 p->size = i; // Needed, in order to cleanup correctly after parser fails
740 PyErr_NoMemory();
741 return -1;
742 }
743 }
744 p->size = newsize;
745 return 0;
746}
747
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100748int
749_PyPegen_fill_token(Parser *p)
750{
Pablo Galindofb61c422020-06-15 14:23:43 +0100751 const char *start;
752 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100753 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700754
755 // Record and skip '# type: ignore' comments
756 while (type == TYPE_IGNORE) {
757 Py_ssize_t len = end - start;
758 char *tag = PyMem_Malloc(len + 1);
759 if (tag == NULL) {
760 PyErr_NoMemory();
761 return -1;
762 }
763 strncpy(tag, start, len);
764 tag[len] = '\0';
765 // Ownership of tag passes to the growable array
766 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
767 PyErr_NoMemory();
768 return -1;
769 }
770 type = PyTokenizer_Get(p->tok, &start, &end);
771 }
772
Pablo Galindod00a4492021-04-09 01:32:25 +0100773 // If we have reached the end and we are in single input mode we need to insert a newline and reset the parsing
774 if (p->start_rule == Py_single_input && type == ENDMARKER && p->parsing_started) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100775 type = NEWLINE; /* Add an extra newline */
776 p->parsing_started = 0;
777
Pablo Galindob94dbd72020-04-27 18:35:58 +0100778 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100779 p->tok->pendin = -p->tok->indent;
780 p->tok->indent = 0;
781 }
782 }
783 else {
784 p->parsing_started = 1;
785 }
786
Pablo Galindod00a4492021-04-09 01:32:25 +0100787 // Check if we are at the limit of the token array capacity and resize if needed
788 if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
789 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100790 }
791
792 Token *t = p->tokens[p->fill];
Pablo Galindod00a4492021-04-09 01:32:25 +0100793 return initialize_token(p, t, start, end, type);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100794}
795
Pablo Galindo58bafe42021-04-09 01:17:31 +0100796
797#if defined(Py_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100798// Instrumentation to count the effectiveness of memoization.
799// The array counts the number of tokens skipped by memoization,
800// indexed by type.
801
802#define NSTATISTICS 2000
803static long memo_statistics[NSTATISTICS];
804
805void
806_PyPegen_clear_memo_statistics()
807{
808 for (int i = 0; i < NSTATISTICS; i++) {
809 memo_statistics[i] = 0;
810 }
811}
812
813PyObject *
814_PyPegen_get_memo_statistics()
815{
816 PyObject *ret = PyList_New(NSTATISTICS);
817 if (ret == NULL) {
818 return NULL;
819 }
820 for (int i = 0; i < NSTATISTICS; i++) {
821 PyObject *value = PyLong_FromLong(memo_statistics[i]);
822 if (value == NULL) {
823 Py_DECREF(ret);
824 return NULL;
825 }
826 // PyList_SetItem borrows a reference to value.
827 if (PyList_SetItem(ret, i, value) < 0) {
828 Py_DECREF(ret);
829 return NULL;
830 }
831 }
832 return ret;
833}
Pablo Galindo58bafe42021-04-09 01:17:31 +0100834#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100835
836int // bool
837_PyPegen_is_memoized(Parser *p, int type, void *pres)
838{
839 if (p->mark == p->fill) {
840 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300841 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100842 return -1;
843 }
844 }
845
846 Token *t = p->tokens[p->mark];
847
848 for (Memo *m = t->memo; m != NULL; m = m->next) {
849 if (m->type == type) {
Pablo Galindo58bafe42021-04-09 01:17:31 +0100850#if defined(PY_DEBUG)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100851 if (0 <= type && type < NSTATISTICS) {
852 long count = m->mark - p->mark;
853 // A memoized negative result counts for one.
854 if (count <= 0) {
855 count = 1;
856 }
857 memo_statistics[type] += count;
858 }
Pablo Galindo58bafe42021-04-09 01:17:31 +0100859#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100860 p->mark = m->mark;
861 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100862 return 1;
863 }
864 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100865 return 0;
866}
867
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100868int
869_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
870{
871 int mark = p->mark;
872 void *res = func(p);
873 p->mark = mark;
874 return (res != NULL) == positive;
875}
876
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100877int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100878_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
879{
880 int mark = p->mark;
881 void *res = func(p, arg);
882 p->mark = mark;
883 return (res != NULL) == positive;
884}
885
886int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100887_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
888{
889 int mark = p->mark;
890 void *res = func(p, arg);
891 p->mark = mark;
892 return (res != NULL) == positive;
893}
894
895int
896_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
897{
898 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100899 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100900 p->mark = mark;
901 return (res != NULL) == positive;
902}
903
904Token *
905_PyPegen_expect_token(Parser *p, int type)
906{
907 if (p->mark == p->fill) {
908 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300909 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100910 return NULL;
911 }
912 }
913 Token *t = p->tokens[p->mark];
914 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100915 return NULL;
916 }
917 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100918 return t;
919}
920
Pablo Galindo58fb1562021-02-02 19:54:22 +0000921Token *
922_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
923
924 if (p->error_indicator == 1) {
925 return NULL;
926 }
927
928 if (p->mark == p->fill) {
929 if (_PyPegen_fill_token(p) < 0) {
930 p->error_indicator = 1;
931 return NULL;
932 }
933 }
934 Token *t = p->tokens[p->mark];
935 if (t->type != type) {
936 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
937 return NULL;
938 }
939 p->mark += 1;
940 return t;
941}
942
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700943expr_ty
944_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
945{
946 if (p->mark == p->fill) {
947 if (_PyPegen_fill_token(p) < 0) {
948 p->error_indicator = 1;
949 return NULL;
950 }
951 }
952 Token *t = p->tokens[p->mark];
953 if (t->type != NAME) {
954 return NULL;
955 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +0300956 const char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700957 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300958 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700959 return NULL;
960 }
961 if (strcmp(s, keyword) != 0) {
962 return NULL;
963 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300964 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700965}
966
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100967Token *
968_PyPegen_get_last_nonnwhitespace_token(Parser *p)
969{
970 assert(p->mark >= 0);
971 Token *token = NULL;
972 for (int m = p->mark - 1; m >= 0; m--) {
973 token = p->tokens[m];
974 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
975 break;
976 }
977 }
978 return token;
979}
980
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700981static expr_ty
982_PyPegen_name_from_token(Parser *p, Token* t)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100983{
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100984 if (t == NULL) {
985 return NULL;
986 }
Serhiy Storchakac43317d2021-06-12 20:44:32 +0300987 const char *s = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100988 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300989 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100990 return NULL;
991 }
992 PyObject *id = _PyPegen_new_identifier(p, s);
993 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300994 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100995 return NULL;
996 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +0200997 return _PyAST_Name(id, Load, t->lineno, t->col_offset, t->end_lineno,
998 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100999}
1000
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -07001001
1002expr_ty
1003_PyPegen_name_token(Parser *p)
1004{
1005 Token *t = _PyPegen_expect_token(p, NAME);
1006 return _PyPegen_name_from_token(p, t);
1007}
1008
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001009void *
1010_PyPegen_string_token(Parser *p)
1011{
1012 return _PyPegen_expect_token(p, STRING);
1013}
1014
Pablo Galindob2802482021-04-15 21:38:45 +01001015
1016expr_ty _PyPegen_soft_keyword_token(Parser *p) {
1017 Token *t = _PyPegen_expect_token(p, NAME);
1018 if (t == NULL) {
1019 return NULL;
1020 }
1021 char *the_token;
1022 Py_ssize_t size;
1023 PyBytes_AsStringAndSize(t->bytes, &the_token, &size);
1024 for (char **keyword = p->soft_keywords; *keyword != NULL; keyword++) {
1025 if (strncmp(*keyword, the_token, size) == 0) {
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -07001026 return _PyPegen_name_from_token(p, t);
Pablo Galindob2802482021-04-15 21:38:45 +01001027 }
1028 }
1029 return NULL;
1030}
1031
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001032static PyObject *
1033parsenumber_raw(const char *s)
1034{
1035 const char *end;
1036 long x;
1037 double dx;
1038 Py_complex compl;
1039 int imflag;
1040
1041 assert(s != NULL);
1042 errno = 0;
1043 end = s + strlen(s) - 1;
1044 imflag = *end == 'j' || *end == 'J';
1045 if (s[0] == '0') {
1046 x = (long)PyOS_strtoul(s, (char **)&end, 0);
1047 if (x < 0 && errno == 0) {
1048 return PyLong_FromString(s, (char **)0, 0);
1049 }
1050 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001051 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001052 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001053 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001054 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +01001055 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001056 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +01001057 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001058 return PyLong_FromLong(x);
1059 }
1060 /* XXX Huge floats may silently fail */
1061 if (imflag) {
1062 compl.real = 0.;
1063 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +01001064 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001065 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +01001066 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001067 return PyComplex_FromCComplex(compl);
1068 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001069 dx = PyOS_string_to_double(s, NULL, NULL);
1070 if (dx == -1.0 && PyErr_Occurred()) {
1071 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001072 }
Pablo Galindofb61c422020-06-15 14:23:43 +01001073 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001074}
1075
1076static PyObject *
1077parsenumber(const char *s)
1078{
Pablo Galindofb61c422020-06-15 14:23:43 +01001079 char *dup;
1080 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001081 PyObject *res = NULL;
1082
1083 assert(s != NULL);
1084
1085 if (strchr(s, '_') == NULL) {
1086 return parsenumber_raw(s);
1087 }
1088 /* Create a duplicate without underscores. */
1089 dup = PyMem_Malloc(strlen(s) + 1);
1090 if (dup == NULL) {
1091 return PyErr_NoMemory();
1092 }
1093 end = dup;
1094 for (; *s; s++) {
1095 if (*s != '_') {
1096 *end++ = *s;
1097 }
1098 }
1099 *end = '\0';
1100 res = parsenumber_raw(dup);
1101 PyMem_Free(dup);
1102 return res;
1103}
1104
1105expr_ty
1106_PyPegen_number_token(Parser *p)
1107{
1108 Token *t = _PyPegen_expect_token(p, NUMBER);
1109 if (t == NULL) {
1110 return NULL;
1111 }
1112
Serhiy Storchakac43317d2021-06-12 20:44:32 +03001113 const char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001114 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001115 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001116 return NULL;
1117 }
1118
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001119 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1120 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -07001121 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001122 "in Python 3.6 and greater");
1123 }
1124
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001125 PyObject *c = parsenumber(num_raw);
1126
1127 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001128 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001129 return NULL;
1130 }
1131
Victor Stinner8370e072021-03-24 02:23:01 +01001132 if (_PyArena_AddPyObject(p->arena, c) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001133 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001134 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001135 return NULL;
1136 }
1137
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001138 return _PyAST_Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno,
1139 t->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001140}
1141
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001142/* Check that the source for a single input statement really is a single
1143 statement by looking at what is left in the buffer after parsing.
1144 Trailing whitespace and comments are OK. */
1145static int // bool
1146bad_single_statement(Parser *p)
1147{
Miss Islington (bot)576e38f2021-12-27 08:15:44 -08001148 char *cur = p->tok->cur;
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001149 char c = *cur;
1150
1151 for (;;) {
1152 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1153 c = *++cur;
1154 }
1155
1156 if (!c) {
1157 return 0;
1158 }
1159
1160 if (c != '#') {
1161 return 1;
1162 }
1163
1164 /* Suck up comment. */
1165 while (c && c != '\n') {
1166 c = *++cur;
1167 }
1168 }
1169}
1170
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001171void
1172_PyPegen_Parser_Free(Parser *p)
1173{
1174 Py_XDECREF(p->normalize);
1175 for (int i = 0; i < p->size; i++) {
1176 PyMem_Free(p->tokens[i]);
1177 }
1178 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001179 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001180 PyMem_Free(p);
1181}
1182
Pablo Galindo2b74c832020-04-27 18:02:07 +01001183static int
1184compute_parser_flags(PyCompilerFlags *flags)
1185{
1186 int parser_flags = 0;
1187 if (!flags) {
1188 return 0;
1189 }
1190 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1191 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1192 }
1193 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1194 parser_flags |= PyPARSE_IGNORE_COOKIE;
1195 }
1196 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1197 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1198 }
1199 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1200 parser_flags |= PyPARSE_TYPE_COMMENTS;
1201 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001202 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001203 parser_flags |= PyPARSE_ASYNC_HACKS;
1204 }
Pablo Galindo Salgado5b58db72022-02-08 12:25:15 +00001205 if (flags->cf_flags & PyCF_ALLOW_INCOMPLETE_INPUT) {
1206 parser_flags |= PyPARSE_ALLOW_INCOMPLETE_INPUT;
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 Galindo Salgado5b58db72022-02-08 12:25:15 +00001333
1334static inline int
1335_is_end_of_source(Parser *p) {
1336 int err = p->tok->done;
1337 return err == E_EOF || err == E_EOFS || err == E_EOLS;
1338}
1339
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001340void *
1341_PyPegen_run_parser(Parser *p)
1342{
1343 void *res = _PyPegen_parse(p);
Pablo Galindo Salgadodc731992021-12-20 16:23:37 +00001344 assert(p->level == 0);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001345 if (res == NULL) {
Pablo Galindo Salgado5b58db72022-02-08 12:25:15 +00001346 if ((p->flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) && _is_end_of_source(p)) {
1347 PyErr_Clear();
1348 return RAISE_SYNTAX_ERROR("incomplete input");
1349 }
Pablo Galindo Salgado4ce55a22021-10-08 00:50:10 +01001350 if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_SyntaxError)) {
1351 return NULL;
1352 }
Pablo Galindo Salgado5b58db72022-02-08 12:25:15 +00001353 // Make a second parser pass. In this pass we activate heavier and slower checks
1354 // to produce better error messages and more complete diagnostics. Extra "invalid_*"
1355 // rules will be active during parsing.
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001356 Token *last_token = p->tokens[p->fill - 1];
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001357 reset_parser_state(p);
1358 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001359 if (PyErr_Occurred()) {
Miss Islington (bot)933b5b62021-06-08 04:46:56 -07001360 // Prioritize tokenizer errors to custom syntax errors raised
1361 // on the second phase only if the errors come from the parser.
Pablo Galindo Salgado633db1c2022-01-23 03:10:37 +00001362 int is_tok_ok = (p->tok->done == E_DONE || p->tok->done == E_OK);
1363 if (is_tok_ok && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
Miss Islington (bot)756b7b92021-05-03 18:06:45 -07001364 _PyPegen_check_tokenizer_errors(p);
1365 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001366 return NULL;
1367 }
1368 if (p->fill == 0) {
1369 RAISE_SYNTAX_ERROR("error at start before reading any input");
1370 }
Pablo Galindo Salgadoc72311d2021-11-25 01:01:40 +00001371 else if (last_token->type == ERRORTOKEN && p->tok->done == E_EOF) {
Pablo Galindod6d63712021-01-19 23:59:33 +00001372 if (p->tok->level) {
1373 raise_unclosed_parentheses_error(p);
1374 } else {
1375 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1376 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001377 }
1378 else {
1379 if (p->tokens[p->fill-1]->type == INDENT) {
1380 RAISE_INDENTATION_ERROR("unexpected indent");
1381 }
1382 else if (p->tokens[p->fill-1]->type == DEDENT) {
1383 RAISE_INDENTATION_ERROR("unexpected unindent");
1384 }
1385 else {
Miss Islington (bot)07dba472021-05-21 08:29:58 -07001386 // Use the last token we found on the first pass to avoid reporting
1387 // incorrect locations for generic syntax errors just because we reached
1388 // further away when trying to find specific syntax errors in the second
1389 // pass.
1390 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(last_token, "invalid syntax");
Pablo Galindoc3f167d2021-01-20 19:11:56 +00001391 // _PyPegen_check_tokenizer_errors will override the existing
1392 // generic SyntaxError we just raised if errors are found.
1393 _PyPegen_check_tokenizer_errors(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001394 }
1395 }
1396 return NULL;
1397 }
1398
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001399 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1400 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1401 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1402 }
1403
Victor Stinnere0bf70d2021-03-18 02:46:06 +01001404 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1405#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
Pablo Galindo13322262020-07-27 23:46:59 +01001406 if (p->start_rule == Py_single_input ||
1407 p->start_rule == Py_file_input ||
1408 p->start_rule == Py_eval_input)
1409 {
Victor Stinnereec8e612021-03-18 14:57:49 +01001410 if (!_PyAST_Validate(res)) {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001411 return NULL;
1412 }
Pablo Galindo13322262020-07-27 23:46:59 +01001413 }
1414#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001415 return res;
1416}
1417
1418mod_ty
1419_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1420 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001421 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001422{
1423 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1424 if (tok == NULL) {
1425 if (PyErr_Occurred()) {
1426 raise_tokenizer_init_error(filename_ob);
1427 return NULL;
1428 }
1429 return NULL;
1430 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001431 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1432 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1433 tok->fp_interactive = 1;
1434 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001435 // This transfers the ownership to the tokenizer
1436 tok->filename = filename_ob;
1437 Py_INCREF(filename_ob);
1438
1439 // From here on we need to clean up even if there's an error
1440 mod_ty result = NULL;
1441
Pablo Galindo2b74c832020-04-27 18:02:07 +01001442 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001443 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1444 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001445 if (p == NULL) {
1446 goto error;
1447 }
1448
1449 result = _PyPegen_run_parser(p);
1450 _PyPegen_Parser_Free(p);
1451
1452error:
1453 PyTokenizer_Free(tok);
1454 return result;
1455}
1456
1457mod_ty
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001458_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001459 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001460{
1461 int exec_input = start_rule == Py_file_input;
1462
1463 struct tok_state *tok;
Pablo Galindo Salgadoe3aa9fd2021-11-17 23:17:18 +00001464 if (flags != NULL && flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001465 tok = PyTokenizer_FromUTF8(str, exec_input);
1466 } else {
1467 tok = PyTokenizer_FromString(str, exec_input);
1468 }
1469 if (tok == NULL) {
1470 if (PyErr_Occurred()) {
1471 raise_tokenizer_init_error(filename_ob);
1472 }
1473 return NULL;
1474 }
1475 // This transfers the ownership to the tokenizer
1476 tok->filename = filename_ob;
1477 Py_INCREF(filename_ob);
1478
1479 // We need to clear up from here on
1480 mod_ty result = NULL;
1481
Pablo Galindo2b74c832020-04-27 18:02:07 +01001482 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001483 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1484 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001485 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1486 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001487 if (p == NULL) {
1488 goto error;
1489 }
1490
1491 result = _PyPegen_run_parser(p);
1492 _PyPegen_Parser_Free(p);
1493
1494error:
1495 PyTokenizer_Free(tok);
1496 return result;
1497}
1498
Pablo Galindoa5634c42020-09-16 19:42:00 +01001499asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001500_PyPegen_interactive_exit(Parser *p)
1501{
1502 if (p->errcode) {
1503 *(p->errcode) = E_EOF;
1504 }
1505 return NULL;
1506}
1507
1508/* Creates a single-element asdl_seq* that contains a */
1509asdl_seq *
1510_PyPegen_singleton_seq(Parser *p, void *a)
1511{
1512 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001513 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001514 if (!seq) {
1515 return NULL;
1516 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001517 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001518 return seq;
1519}
1520
1521/* Creates a copy of seq and prepends a to it */
1522asdl_seq *
1523_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1524{
1525 assert(a != NULL);
1526 if (!seq) {
1527 return _PyPegen_singleton_seq(p, a);
1528 }
1529
Pablo Galindoa5634c42020-09-16 19:42:00 +01001530 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 +01001531 if (!new_seq) {
1532 return NULL;
1533 }
1534
Pablo Galindoa5634c42020-09-16 19:42:00 +01001535 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001536 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001537 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001538 }
1539 return new_seq;
1540}
1541
Guido van Rossumc001c092020-04-30 12:12:19 -07001542/* Creates a copy of seq and appends a to it */
1543asdl_seq *
1544_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1545{
1546 assert(a != NULL);
1547 if (!seq) {
1548 return _PyPegen_singleton_seq(p, a);
1549 }
1550
Pablo Galindoa5634c42020-09-16 19:42:00 +01001551 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 -07001552 if (!new_seq) {
1553 return NULL;
1554 }
1555
1556 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001557 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001558 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001559 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001560 return new_seq;
1561}
1562
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001563static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001564_get_flattened_seq_size(asdl_seq *seqs)
1565{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001566 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001567 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001568 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001569 size += asdl_seq_LEN(inner_seq);
1570 }
1571 return size;
1572}
1573
1574/* Flattens an asdl_seq* of asdl_seq*s */
1575asdl_seq *
1576_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1577{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001578 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001579 assert(flattened_seq_size > 0);
1580
Pablo Galindoa5634c42020-09-16 19:42:00 +01001581 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001582 if (!flattened_seq) {
1583 return NULL;
1584 }
1585
1586 int flattened_seq_idx = 0;
1587 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001588 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001589 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001590 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001591 }
1592 }
1593 assert(flattened_seq_idx == flattened_seq_size);
1594
1595 return flattened_seq;
1596}
1597
Pablo Galindoa77aac42021-04-23 14:27:05 +01001598void *
1599_PyPegen_seq_last_item(asdl_seq *seq)
1600{
1601 Py_ssize_t len = asdl_seq_LEN(seq);
1602 return asdl_seq_GET_UNTYPED(seq, len - 1);
1603}
1604
Miss Islington (bot)11f1a302021-06-24 08:34:28 -07001605void *
1606_PyPegen_seq_first_item(asdl_seq *seq)
1607{
1608 return asdl_seq_GET_UNTYPED(seq, 0);
1609}
1610
1611
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001612/* Creates a new name of the form <first_name>.<second_name> */
1613expr_ty
1614_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1615{
1616 assert(first_name != NULL && second_name != NULL);
1617 PyObject *first_identifier = first_name->v.Name.id;
1618 PyObject *second_identifier = second_name->v.Name.id;
1619
1620 if (PyUnicode_READY(first_identifier) == -1) {
1621 return NULL;
1622 }
1623 if (PyUnicode_READY(second_identifier) == -1) {
1624 return NULL;
1625 }
1626 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1627 if (!first_str) {
1628 return NULL;
1629 }
1630 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1631 if (!second_str) {
1632 return NULL;
1633 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001634 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001635
1636 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1637 if (!str) {
1638 return NULL;
1639 }
1640
1641 char *s = PyBytes_AS_STRING(str);
1642 if (!s) {
1643 return NULL;
1644 }
1645
1646 strcpy(s, first_str);
1647 s += strlen(first_str);
1648 *s++ = '.';
1649 strcpy(s, second_str);
1650 s += strlen(second_str);
1651 *s = '\0';
1652
1653 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1654 Py_DECREF(str);
1655 if (!uni) {
1656 return NULL;
1657 }
1658 PyUnicode_InternInPlace(&uni);
Victor Stinner8370e072021-03-24 02:23:01 +01001659 if (_PyArena_AddPyObject(p->arena, uni) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001660 Py_DECREF(uni);
1661 return NULL;
1662 }
1663
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001664 return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001665}
1666
1667/* Counts the total number of dots in seq's tokens */
1668int
1669_PyPegen_seq_count_dots(asdl_seq *seq)
1670{
1671 int number_of_dots = 0;
1672 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001673 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001674 switch (current_expr->type) {
1675 case ELLIPSIS:
1676 number_of_dots += 3;
1677 break;
1678 case DOT:
1679 number_of_dots += 1;
1680 break;
1681 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001682 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001683 }
1684 }
1685
1686 return number_of_dots;
1687}
1688
1689/* Creates an alias with '*' as the identifier name */
1690alias_ty
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001691_PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
1692 int end_col_offset, PyArena *arena) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001693 PyObject *str = PyUnicode_InternFromString("*");
1694 if (!str) {
1695 return NULL;
1696 }
Victor Stinner8370e072021-03-24 02:23:01 +01001697 if (_PyArena_AddPyObject(p->arena, str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001698 Py_DECREF(str);
1699 return NULL;
1700 }
Matthew Suozzo75a06f02021-04-10 16:56:28 -04001701 return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001702}
1703
1704/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001705asdl_identifier_seq *
1706_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001707{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001708 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001709 assert(len > 0);
1710
Pablo Galindoa5634c42020-09-16 19:42:00 +01001711 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001712 if (!new_seq) {
1713 return NULL;
1714 }
1715 for (Py_ssize_t i = 0; i < len; i++) {
1716 expr_ty e = asdl_seq_GET(seq, i);
1717 asdl_seq_SET(new_seq, i, e->v.Name.id);
1718 }
1719 return new_seq;
1720}
1721
1722/* Constructs a CmpopExprPair */
1723CmpopExprPair *
1724_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1725{
1726 assert(expr != NULL);
Victor Stinner8370e072021-03-24 02:23:01 +01001727 CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001728 if (!a) {
1729 return NULL;
1730 }
1731 a->cmpop = cmpop;
1732 a->expr = expr;
1733 return a;
1734}
1735
1736asdl_int_seq *
1737_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1738{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001739 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001740 assert(len > 0);
1741
1742 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1743 if (!new_seq) {
1744 return NULL;
1745 }
1746 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001747 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001748 asdl_seq_SET(new_seq, i, pair->cmpop);
1749 }
1750 return new_seq;
1751}
1752
Pablo Galindoa5634c42020-09-16 19:42:00 +01001753asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001754_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1755{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001756 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001757 assert(len > 0);
1758
Pablo Galindoa5634c42020-09-16 19:42:00 +01001759 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001760 if (!new_seq) {
1761 return NULL;
1762 }
1763 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001764 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001765 asdl_seq_SET(new_seq, i, pair->expr);
1766 }
1767 return new_seq;
1768}
1769
1770/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001771static asdl_expr_seq *
1772_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001773{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001774 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001775 if (len == 0) {
1776 return NULL;
1777 }
1778
Pablo Galindoa5634c42020-09-16 19:42:00 +01001779 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001780 if (!new_seq) {
1781 return NULL;
1782 }
1783 for (Py_ssize_t i = 0; i < len; i++) {
1784 expr_ty e = asdl_seq_GET(seq, i);
1785 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1786 }
1787 return new_seq;
1788}
1789
1790static expr_ty
1791_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1792{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001793 return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001794}
1795
1796static expr_ty
1797_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1798{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001799 return _PyAST_Tuple(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001800 _set_seq_context(p, e->v.Tuple.elts, ctx),
1801 ctx,
1802 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001803}
1804
1805static expr_ty
1806_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1807{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001808 return _PyAST_List(
Pablo Galindoa5634c42020-09-16 19:42:00 +01001809 _set_seq_context(p, e->v.List.elts, ctx),
1810 ctx,
1811 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001812}
1813
1814static expr_ty
1815_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1816{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001817 return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
1818 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001819}
1820
1821static expr_ty
1822_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1823{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001824 return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
1825 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001826}
1827
1828static expr_ty
1829_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1830{
Victor Stinnerd27f8d22021-04-07 21:34:22 +02001831 return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
1832 ctx, EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001833}
1834
1835/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1836expr_ty
1837_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1838{
1839 assert(expr != NULL);
1840
1841 expr_ty new = NULL;
1842 switch (expr->kind) {
1843 case Name_kind:
1844 new = _set_name_context(p, expr, ctx);
1845 break;
1846 case Tuple_kind:
1847 new = _set_tuple_context(p, expr, ctx);
1848 break;
1849 case List_kind:
1850 new = _set_list_context(p, expr, ctx);
1851 break;
1852 case Subscript_kind:
1853 new = _set_subscript_context(p, expr, ctx);
1854 break;
1855 case Attribute_kind:
1856 new = _set_attribute_context(p, expr, ctx);
1857 break;
1858 case Starred_kind:
1859 new = _set_starred_context(p, expr, ctx);
1860 break;
1861 default:
1862 new = expr;
1863 }
1864 return new;
1865}
1866
1867/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1868KeyValuePair *
1869_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1870{
Victor Stinner8370e072021-03-24 02:23:01 +01001871 KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001872 if (!a) {
1873 return NULL;
1874 }
1875 a->key = key;
1876 a->value = value;
1877 return a;
1878}
1879
1880/* Extracts all keys 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_keys(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->key);
1892 }
1893 return new_seq;
1894}
1895
1896/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001897asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001898_PyPegen_get_values(Parser *p, asdl_seq *seq)
1899{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001900 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001901 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001902 if (!new_seq) {
1903 return NULL;
1904 }
1905 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001906 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001907 asdl_seq_SET(new_seq, i, pair->value);
1908 }
1909 return new_seq;
1910}
1911
Nick Coghlan1e7b8582021-04-29 15:58:44 +10001912/* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
1913KeyPatternPair *
1914_PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
1915{
1916 KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
1917 if (!a) {
1918 return NULL;
1919 }
1920 a->key = key;
1921 a->pattern = pattern;
1922 return a;
1923}
1924
1925/* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
1926asdl_expr_seq *
1927_PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
1928{
1929 Py_ssize_t len = asdl_seq_LEN(seq);
1930 asdl_expr_seq *new_seq = _Py_asdl_expr_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->key);
1937 }
1938 return new_seq;
1939}
1940
1941/* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
1942asdl_pattern_seq *
1943_PyPegen_get_patterns(Parser *p, asdl_seq *seq)
1944{
1945 Py_ssize_t len = asdl_seq_LEN(seq);
1946 asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
1947 if (!new_seq) {
1948 return NULL;
1949 }
1950 for (Py_ssize_t i = 0; i < len; i++) {
1951 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
1952 asdl_seq_SET(new_seq, i, pair->pattern);
1953 }
1954 return new_seq;
1955}
1956
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001957/* Constructs a NameDefaultPair */
1958NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001959_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001960{
Victor Stinner8370e072021-03-24 02:23:01 +01001961 NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001962 if (!a) {
1963 return NULL;
1964 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001965 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001966 a->value = value;
1967 return a;
1968}
1969
1970/* Constructs a SlashWithDefault */
1971SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001972_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001973{
Victor Stinner8370e072021-03-24 02:23:01 +01001974 SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001975 if (!a) {
1976 return NULL;
1977 }
1978 a->plain_names = plain_names;
1979 a->names_with_defaults = names_with_defaults;
1980 return a;
1981}
1982
1983/* Constructs a StarEtc */
1984StarEtc *
1985_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1986{
Victor Stinner8370e072021-03-24 02:23:01 +01001987 StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001988 if (!a) {
1989 return NULL;
1990 }
1991 a->vararg = vararg;
1992 a->kwonlyargs = kwonlyargs;
1993 a->kwarg = kwarg;
1994 return a;
1995}
1996
1997asdl_seq *
1998_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1999{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002000 Py_ssize_t first_len = asdl_seq_LEN(a);
2001 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01002002 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002003 if (!new_seq) {
2004 return NULL;
2005 }
2006
2007 int k = 0;
2008 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002009 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002010 }
2011 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002012 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002013 }
2014
2015 return new_seq;
2016}
2017
Pablo Galindoa5634c42020-09-16 19:42:00 +01002018static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002019_get_names(Parser *p, asdl_seq *names_with_defaults)
2020{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002021 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01002022 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002023 if (!seq) {
2024 return NULL;
2025 }
2026 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002027 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002028 asdl_seq_SET(seq, i, pair->arg);
2029 }
2030 return seq;
2031}
2032
Pablo Galindoa5634c42020-09-16 19:42:00 +01002033static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002034_get_defaults(Parser *p, asdl_seq *names_with_defaults)
2035{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002036 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01002037 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002038 if (!seq) {
2039 return NULL;
2040 }
2041 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002042 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002043 asdl_seq_SET(seq, i, pair->value);
2044 }
2045 return seq;
2046}
2047
Pablo Galindo4f642da2021-04-09 00:48:53 +01002048static int
2049_make_posonlyargs(Parser *p,
2050 asdl_arg_seq *slash_without_default,
2051 SlashWithDefault *slash_with_default,
2052 asdl_arg_seq **posonlyargs) {
2053 if (slash_without_default != NULL) {
2054 *posonlyargs = slash_without_default;
2055 }
2056 else if (slash_with_default != NULL) {
2057 asdl_arg_seq *slash_with_default_names =
2058 _get_names(p, slash_with_default->names_with_defaults);
2059 if (!slash_with_default_names) {
2060 return -1;
2061 }
2062 *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2063 p,
2064 (asdl_seq*)slash_with_default->plain_names,
2065 (asdl_seq*)slash_with_default_names);
2066 }
2067 else {
2068 *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2069 }
2070 return *posonlyargs == NULL ? -1 : 0;
2071}
2072
2073static int
2074_make_posargs(Parser *p,
2075 asdl_arg_seq *plain_names,
2076 asdl_seq *names_with_default,
2077 asdl_arg_seq **posargs) {
2078 if (plain_names != NULL && names_with_default != NULL) {
2079 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
2080 if (!names_with_default_names) {
2081 return -1;
2082 }
2083 *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
2084 p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
2085 }
2086 else if (plain_names == NULL && names_with_default != NULL) {
2087 *posargs = _get_names(p, names_with_default);
2088 }
2089 else if (plain_names != NULL && names_with_default == NULL) {
2090 *posargs = plain_names;
2091 }
2092 else {
2093 *posargs = _Py_asdl_arg_seq_new(0, p->arena);
2094 }
2095 return *posargs == NULL ? -1 : 0;
2096}
2097
2098static int
2099_make_posdefaults(Parser *p,
2100 SlashWithDefault *slash_with_default,
2101 asdl_seq *names_with_default,
2102 asdl_expr_seq **posdefaults) {
2103 if (slash_with_default != NULL && names_with_default != NULL) {
2104 asdl_expr_seq *slash_with_default_values =
2105 _get_defaults(p, slash_with_default->names_with_defaults);
2106 if (!slash_with_default_values) {
2107 return -1;
2108 }
2109 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
2110 if (!names_with_default_values) {
2111 return -1;
2112 }
2113 *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
2114 p,
2115 (asdl_seq*)slash_with_default_values,
2116 (asdl_seq*)names_with_default_values);
2117 }
2118 else if (slash_with_default == NULL && names_with_default != NULL) {
2119 *posdefaults = _get_defaults(p, names_with_default);
2120 }
2121 else if (slash_with_default != NULL && names_with_default == NULL) {
2122 *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
2123 }
2124 else {
2125 *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2126 }
2127 return *posdefaults == NULL ? -1 : 0;
2128}
2129
2130static int
2131_make_kwargs(Parser *p, StarEtc *star_etc,
2132 asdl_arg_seq **kwonlyargs,
2133 asdl_expr_seq **kwdefaults) {
2134 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2135 *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
2136 }
2137 else {
2138 *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
2139 }
2140
2141 if (*kwonlyargs == NULL) {
2142 return -1;
2143 }
2144
2145 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
2146 *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
2147 }
2148 else {
2149 *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
2150 }
2151
2152 if (*kwdefaults == NULL) {
2153 return -1;
2154 }
2155
2156 return 0;
2157}
2158
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002159/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
2160arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002161_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
2162 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002163 asdl_seq *names_with_default, StarEtc *star_etc)
2164{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002165 asdl_arg_seq *posonlyargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002166 if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
2167 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002168 }
2169
Pablo Galindoa5634c42020-09-16 19:42:00 +01002170 asdl_arg_seq *posargs;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002171 if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
2172 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002173 }
2174
Pablo Galindoa5634c42020-09-16 19:42:00 +01002175 asdl_expr_seq *posdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002176 if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
2177 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002178 }
2179
2180 arg_ty vararg = NULL;
2181 if (star_etc != NULL && star_etc->vararg != NULL) {
2182 vararg = star_etc->vararg;
2183 }
2184
Pablo Galindoa5634c42020-09-16 19:42:00 +01002185 asdl_arg_seq *kwonlyargs;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002186 asdl_expr_seq *kwdefaults;
Pablo Galindo4f642da2021-04-09 00:48:53 +01002187 if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
2188 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002189 }
2190
2191 arg_ty kwarg = NULL;
2192 if (star_etc != NULL && star_etc->kwarg != NULL) {
2193 kwarg = star_etc->kwarg;
2194 }
2195
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002196 return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
2197 kwdefaults, kwarg, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002198}
2199
Pablo Galindo4f642da2021-04-09 00:48:53 +01002200
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002201/* Constructs an empty arguments_ty object, that gets used when a function accepts no
2202 * arguments. */
2203arguments_ty
2204_PyPegen_empty_arguments(Parser *p)
2205{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002206 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002207 if (!posonlyargs) {
2208 return NULL;
2209 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002210 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002211 if (!posargs) {
2212 return NULL;
2213 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002214 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002215 if (!posdefaults) {
2216 return NULL;
2217 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002218 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002219 if (!kwonlyargs) {
2220 return NULL;
2221 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002222 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002223 if (!kwdefaults) {
2224 return NULL;
2225 }
2226
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002227 return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
2228 kwdefaults, NULL, posdefaults, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002229}
2230
2231/* Encapsulates the value of an operator_ty into an AugOperator struct */
2232AugOperator *
2233_PyPegen_augoperator(Parser *p, operator_ty kind)
2234{
Victor Stinner8370e072021-03-24 02:23:01 +01002235 AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002236 if (!a) {
2237 return NULL;
2238 }
2239 a->kind = kind;
2240 return a;
2241}
2242
2243/* Construct a FunctionDef equivalent to function_def, but with decorators */
2244stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002245_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002246{
2247 assert(function_def != NULL);
2248 if (function_def->kind == AsyncFunctionDef_kind) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002249 return _PyAST_AsyncFunctionDef(
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002250 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2251 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2252 function_def->v.FunctionDef.type_comment, function_def->lineno,
2253 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2254 p->arena);
2255 }
2256
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002257 return _PyAST_FunctionDef(
2258 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2259 function_def->v.FunctionDef.body, decorators,
2260 function_def->v.FunctionDef.returns,
2261 function_def->v.FunctionDef.type_comment, function_def->lineno,
2262 function_def->col_offset, function_def->end_lineno,
2263 function_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002264}
2265
2266/* Construct a ClassDef equivalent to class_def, but with decorators */
2267stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002268_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002269{
2270 assert(class_def != NULL);
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002271 return _PyAST_ClassDef(
2272 class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2273 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2274 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2275 class_def->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002276}
2277
2278/* Construct a KeywordOrStarred */
2279KeywordOrStarred *
2280_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2281{
Victor Stinner8370e072021-03-24 02:23:01 +01002282 KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002283 if (!a) {
2284 return NULL;
2285 }
2286 a->element = element;
2287 a->is_keyword = is_keyword;
2288 return a;
2289}
2290
2291/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2292static int
2293_seq_number_of_starred_exprs(asdl_seq *seq)
2294{
2295 int n = 0;
2296 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002297 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002298 if (!k->is_keyword) {
2299 n++;
2300 }
2301 }
2302 return n;
2303}
2304
2305/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002306asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002307_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2308{
2309 int new_len = _seq_number_of_starred_exprs(kwargs);
2310 if (new_len == 0) {
2311 return NULL;
2312 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002313 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002314 if (!new_seq) {
2315 return NULL;
2316 }
2317
2318 int idx = 0;
2319 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002320 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002321 if (!k->is_keyword) {
2322 asdl_seq_SET(new_seq, idx++, k->element);
2323 }
2324 }
2325 return new_seq;
2326}
2327
2328/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002329asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002330_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2331{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002332 Py_ssize_t len = asdl_seq_LEN(kwargs);
2333 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002334 if (new_len == 0) {
2335 return NULL;
2336 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002337 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002338 if (!new_seq) {
2339 return NULL;
2340 }
2341
2342 int idx = 0;
2343 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002344 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002345 if (k->is_keyword) {
2346 asdl_seq_SET(new_seq, idx++, k->element);
2347 }
2348 }
2349 return new_seq;
2350}
2351
2352expr_ty
2353_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2354{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002355 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002356 assert(len > 0);
2357
Pablo Galindoa5634c42020-09-16 19:42:00 +01002358 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2359 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002360
2361 int bytesmode = 0;
2362 PyObject *bytes_str = NULL;
2363
2364 FstringParser state;
2365 _PyPegen_FstringParser_Init(&state);
2366
2367 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002368 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002369
2370 int this_bytesmode;
2371 int this_rawmode;
2372 PyObject *s;
2373 const char *fstr;
2374 Py_ssize_t fstrlen = -1;
2375
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002376 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002377 goto error;
2378 }
2379
2380 /* Check that we are not mixing bytes with unicode. */
2381 if (i != 0 && bytesmode != this_bytesmode) {
2382 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2383 Py_XDECREF(s);
2384 goto error;
2385 }
2386 bytesmode = this_bytesmode;
2387
2388 if (fstr != NULL) {
2389 assert(s == NULL && !bytesmode);
2390
2391 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2392 this_rawmode, 0, first, t, last);
2393 if (result < 0) {
2394 goto error;
2395 }
2396 }
2397 else {
2398 /* String or byte string. */
2399 assert(s != NULL && fstr == NULL);
2400 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2401
2402 if (bytesmode) {
2403 if (i == 0) {
2404 bytes_str = s;
2405 }
2406 else {
2407 PyBytes_ConcatAndDel(&bytes_str, s);
2408 if (!bytes_str) {
2409 goto error;
2410 }
2411 }
2412 }
2413 else {
2414 /* This is a regular string. Concatenate it. */
2415 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2416 goto error;
2417 }
2418 }
2419 }
2420 }
2421
2422 if (bytesmode) {
Victor Stinner8370e072021-03-24 02:23:01 +01002423 if (_PyArena_AddPyObject(p->arena, bytes_str) < 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002424 goto error;
2425 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002426 return _PyAST_Constant(bytes_str, NULL, first->lineno,
2427 first->col_offset, last->end_lineno,
2428 last->end_col_offset, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002429 }
2430
2431 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2432
2433error:
2434 Py_XDECREF(bytes_str);
2435 _PyPegen_FstringParser_Dealloc(&state);
2436 if (PyErr_Occurred()) {
2437 raise_decode_error(p);
2438 }
2439 return NULL;
2440}
Guido van Rossumc001c092020-04-30 12:12:19 -07002441
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002442expr_ty
2443_PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
2444{
2445 if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07002446 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
2447 return NULL;
2448 }
2449 return exp;
2450}
2451
2452expr_ty
2453_PyPegen_ensure_real(Parser *p, expr_ty exp)
2454{
2455 if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
2456 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
Nick Coghlan1e7b8582021-04-29 15:58:44 +10002457 return NULL;
2458 }
2459 return exp;
2460}
2461
Guido van Rossumc001c092020-04-30 12:12:19 -07002462mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002463_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2464 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002465 Py_ssize_t num = p->type_ignore_comments.num_items;
2466 if (num > 0) {
2467 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002468 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002469 if (type_ignores == NULL) {
2470 return NULL;
2471 }
2472 for (int i = 0; i < num; i++) {
2473 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2474 if (tag == NULL) {
2475 return NULL;
2476 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002477 type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
2478 tag, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002479 if (ti == NULL) {
2480 return NULL;
2481 }
2482 asdl_seq_SET(type_ignores, i, ti);
2483 }
2484 }
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002485 return _PyAST_Module(a, type_ignores, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002486}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002487
2488// Error reporting helpers
2489
2490expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002491_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002492{
2493 if (e == NULL) {
2494 return NULL;
2495 }
2496
2497#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
Pablo Galindo58bafe42021-04-09 01:17:31 +01002498 Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002499 for (Py_ssize_t i = 0; i < len; i++) {\
Pablo Galindo58bafe42021-04-09 01:17:31 +01002500 expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002501 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002502 if (child != NULL) {\
2503 return child;\
2504 }\
2505 }\
2506 } while (0)
2507
2508 // We only need to visit List and Tuple nodes recursively as those
2509 // are the only ones that can contain valid names in targets when
2510 // they are parsed as expressions. Any other kind of expression
2511 // that is a container (like Sets or Dicts) is directly invalid and
2512 // we don't need to visit it recursively.
2513
2514 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002515 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002516 VISIT_CONTAINER(e, List);
2517 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002518 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002519 VISIT_CONTAINER(e, Tuple);
2520 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002521 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002522 if (targets_type == DEL_TARGETS) {
2523 return e;
2524 }
2525 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2526 case Compare_kind:
2527 // This is needed, because the `a in b` in `for a in b` gets parsed
2528 // as a comparison, and so we need to search the left side of the comparison
2529 // for invalid targets.
2530 if (targets_type == FOR_TARGETS) {
2531 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2532 if (cmpop == In) {
2533 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2534 }
2535 return NULL;
2536 }
2537 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002538 case Name_kind:
2539 case Subscript_kind:
2540 case Attribute_kind:
2541 return NULL;
2542 default:
2543 return e;
2544 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002545}
2546
2547void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2548 int kwarg_unpacking = 0;
2549 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2550 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2551 if (!keyword->arg) {
2552 kwarg_unpacking = 1;
2553 }
2554 }
2555
2556 const char *msg = NULL;
2557 if (kwarg_unpacking) {
2558 msg = "positional argument follows keyword argument unpacking";
2559 } else {
2560 msg = "positional argument follows keyword argument";
2561 }
2562
2563 return RAISE_SYNTAX_ERROR(msg);
2564}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002565
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002566
2567static inline expr_ty
2568_PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
2569 if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
2570 return comprehension->iter;
2571 }
2572 return PyPegen_last_item(comprehension->ifs, expr_ty);
2573}
2574
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002575void *
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002576_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions)
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002577{
2578 /* The rule that calls this function is 'args for_if_clauses'.
2579 For the input f(L, x for x in y), L and x are in args and
2580 the for is parsed as a for_if_clause. We have to check if
2581 len <= 1, so that input like dict((a, b) for a, b in x)
2582 gets successfully parsed and then we pass the last
2583 argument (x in the above example) as the location of the
2584 error */
2585 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2586 if (len <= 1) {
2587 return NULL;
2588 }
2589
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002590 comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
2591
2592 return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002593 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
Miss Islington (bot)9e209d42021-09-27 07:05:20 -07002594 _PyPegen_get_last_comprehension_item(last_comprehension),
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002595 "Generator expression must be parenthesized"
2596 );
2597}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002598
2599
Pablo Galindoa5634c42020-09-16 19:42:00 +01002600expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002601 int lineno, int col_offset, int end_lineno,
2602 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002603 Py_ssize_t args_len = asdl_seq_LEN(a);
2604 Py_ssize_t total_len = args_len;
2605
2606 if (b == NULL) {
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002607 return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002608 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002609
2610 }
2611
Pablo Galindoa5634c42020-09-16 19:42:00 +01002612 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2613 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002614
2615 if (starreds) {
2616 total_len += asdl_seq_LEN(starreds);
2617 }
2618
Pablo Galindoa5634c42020-09-16 19:42:00 +01002619 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002620
2621 Py_ssize_t i = 0;
2622 for (i = 0; i < args_len; i++) {
2623 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2624 }
2625 for (; i < total_len; i++) {
2626 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2627 }
2628
Victor Stinnerd27f8d22021-04-07 21:34:22 +02002629 return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2630 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002631}