blob: 84bdf8dd3f89e244db1e652cfbf74590a8b1082b [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01003#include "tokenizer.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004
5#include "pegen.h"
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01006#include "string_parser.h"
Pablo Galindo13322262020-07-27 23:46:59 +01007#include "ast.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01008
Guido van Rossumc001c092020-04-30 12:12:19 -07009PyObject *
10_PyPegen_new_type_comment(Parser *p, char *s)
11{
12 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
13 if (res == NULL) {
14 return NULL;
15 }
16 if (PyArena_AddPyObject(p->arena, res) < 0) {
17 Py_DECREF(res);
18 return NULL;
19 }
20 return res;
21}
22
23arg_ty
24_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
25{
26 if (tc == NULL) {
27 return a;
28 }
29 char *bytes = PyBytes_AsString(tc->bytes);
30 if (bytes == NULL) {
31 return NULL;
32 }
33 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
34 if (tco == NULL) {
35 return NULL;
36 }
37 return arg(a->arg, a->annotation, tco,
38 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
39 p->arena);
40}
41
Pablo Galindoc5fc1562020-04-22 23:29:27 +010042static int
43init_normalization(Parser *p)
44{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030045 if (p->normalize) {
46 return 1;
47 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010048 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
49 if (!m)
50 {
51 return 0;
52 }
53 p->normalize = PyObject_GetAttrString(m, "normalize");
54 Py_DECREF(m);
55 if (!p->normalize)
56 {
57 return 0;
58 }
59 return 1;
60}
61
Pablo Galindo2b74c832020-04-27 18:02:07 +010062/* Checks if the NOTEQUAL token is valid given the current parser flags
630 indicates success and nonzero indicates failure (an exception may be set) */
64int
Pablo Galindo06f8c332020-10-30 23:48:42 +000065_PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010066 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindofb61c422020-06-15 14:23:43 +010070 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010071 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
Pablo Galindofb61c422020-06-15 14:23:43 +010073 }
74 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010075 return strcmp(tok_str, "!=");
76 }
77 return 0;
78}
79
Pablo Galindoc5fc1562020-04-22 23:29:27 +010080PyObject *
81_PyPegen_new_identifier(Parser *p, char *n)
82{
83 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
84 if (!id) {
85 goto error;
86 }
87 /* PyUnicode_DecodeUTF8 should always return a ready string. */
88 assert(PyUnicode_IS_READY(id));
89 /* Check whether there are non-ASCII characters in the
90 identifier; if so, normalize to NFKC. */
91 if (!PyUnicode_IS_ASCII(id))
92 {
93 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030094 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010095 {
96 Py_DECREF(id);
97 goto error;
98 }
99 PyObject *form = PyUnicode_InternFromString("NFKC");
100 if (form == NULL)
101 {
102 Py_DECREF(id);
103 goto error;
104 }
105 PyObject *args[2] = {form, id};
106 id2 = _PyObject_FastCall(p->normalize, args, 2);
107 Py_DECREF(id);
108 Py_DECREF(form);
109 if (!id2) {
110 goto error;
111 }
112 if (!PyUnicode_Check(id2))
113 {
114 PyErr_Format(PyExc_TypeError,
115 "unicodedata.normalize() must return a string, not "
116 "%.200s",
117 _PyType_Name(Py_TYPE(id2)));
118 Py_DECREF(id2);
119 goto error;
120 }
121 id = id2;
122 }
123 PyUnicode_InternInPlace(&id);
124 if (PyArena_AddPyObject(p->arena, id) < 0)
125 {
126 Py_DECREF(id);
127 goto error;
128 }
129 return id;
130
131error:
132 p->error_indicator = 1;
133 return NULL;
134}
135
136static PyObject *
137_create_dummy_identifier(Parser *p)
138{
139 return _PyPegen_new_identifier(p, "");
140}
141
142static inline Py_ssize_t
Pablo Galindo51c58962020-06-16 16:49:43 +0100143byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100144{
145 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300146 if (!str) {
147 return 0;
148 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100149 assert(col_offset >= 0 && (unsigned long)col_offset <= strlen(str));
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300150 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100151 if (!text) {
152 return 0;
153 }
154 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
155 Py_DECREF(text);
156 return size;
157}
158
159const char *
160_PyPegen_get_expr_name(expr_ty e)
161{
Pablo Galindo9f495902020-06-08 02:57:00 +0100162 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100163 switch (e->kind) {
164 case Attribute_kind:
165 return "attribute";
166 case Subscript_kind:
167 return "subscript";
168 case Starred_kind:
169 return "starred";
170 case Name_kind:
171 return "name";
172 case List_kind:
173 return "list";
174 case Tuple_kind:
175 return "tuple";
176 case Lambda_kind:
177 return "lambda";
178 case Call_kind:
179 return "function call";
180 case BoolOp_kind:
181 case BinOp_kind:
182 case UnaryOp_kind:
183 return "operator";
184 case GeneratorExp_kind:
185 return "generator expression";
186 case Yield_kind:
187 case YieldFrom_kind:
188 return "yield expression";
189 case Await_kind:
190 return "await expression";
191 case ListComp_kind:
192 return "list comprehension";
193 case SetComp_kind:
194 return "set comprehension";
195 case DictComp_kind:
196 return "dict comprehension";
197 case Dict_kind:
198 return "dict display";
199 case Set_kind:
200 return "set display";
201 case JoinedStr_kind:
202 case FormattedValue_kind:
203 return "f-string expression";
204 case Constant_kind: {
205 PyObject *value = e->v.Constant.value;
206 if (value == Py_None) {
207 return "None";
208 }
209 if (value == Py_False) {
210 return "False";
211 }
212 if (value == Py_True) {
213 return "True";
214 }
215 if (value == Py_Ellipsis) {
216 return "Ellipsis";
217 }
218 return "literal";
219 }
220 case Compare_kind:
221 return "comparison";
222 case IfExp_kind:
223 return "conditional expression";
224 case NamedExpr_kind:
225 return "named expression";
226 default:
227 PyErr_Format(PyExc_SystemError,
228 "unexpected expression in assignment %d (line %d)",
229 e->kind, e->lineno);
230 return NULL;
231 }
232}
233
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300234static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100235raise_decode_error(Parser *p)
236{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300237 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100238 const char *errtype = NULL;
239 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
240 errtype = "unicode error";
241 }
242 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
243 errtype = "value error";
244 }
245 if (errtype) {
Pablo Galindofb61c422020-06-15 14:23:43 +0100246 PyObject *type;
247 PyObject *value;
248 PyObject *tback;
249 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100250 PyErr_Fetch(&type, &value, &tback);
251 errstr = PyObject_Str(value);
252 if (errstr) {
253 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
254 Py_DECREF(errstr);
255 }
256 else {
257 PyErr_Clear();
258 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
259 }
260 Py_XDECREF(type);
261 Py_XDECREF(value);
262 Py_XDECREF(tback);
263 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300264
265 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100266}
267
Pablo Galindod6d63712021-01-19 23:59:33 +0000268static inline void
269raise_unclosed_parentheses_error(Parser *p) {
270 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
271 int error_col = p->tok->parencolstack[p->tok->level-1];
272 RAISE_ERROR_KNOWN_LOCATION(p, PyExc_SyntaxError,
273 error_lineno, error_col,
274 "'%c' was never closed",
275 p->tok->parenstack[p->tok->level-1]);
276}
277
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100278static void
279raise_tokenizer_init_error(PyObject *filename)
280{
281 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
282 || PyErr_ExceptionMatches(PyExc_ValueError)
283 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
284 return;
285 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300286 PyObject *errstr = NULL;
287 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100288 PyObject *type;
289 PyObject *value;
290 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100291 PyErr_Fetch(&type, &value, &tback);
292 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300293 if (!errstr) {
294 goto error;
295 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100296
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300297 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100298 if (!tmp) {
299 goto error;
300 }
301
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300302 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100303 Py_DECREF(tmp);
304 if (!value) {
305 goto error;
306 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300307 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308
309error:
310 Py_XDECREF(type);
311 Py_XDECREF(value);
312 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300313 Py_XDECREF(errstr);
314 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100315}
316
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100317static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100318tokenizer_error(Parser *p)
319{
320 if (PyErr_Occurred()) {
321 return -1;
322 }
323
324 const char *msg = NULL;
325 PyObject* errtype = PyExc_SyntaxError;
326 switch (p->tok->done) {
327 case E_TOKEN:
328 msg = "invalid token";
329 break;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300330 case E_EOF:
Pablo Galindod6d63712021-01-19 23:59:33 +0000331 if (p->tok->level) {
332 raise_unclosed_parentheses_error(p);
333 } else {
334 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
335 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300336 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100337 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300338 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
339 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100340 case E_INTR:
341 if (!PyErr_Occurred()) {
342 PyErr_SetNone(PyExc_KeyboardInterrupt);
343 }
344 return -1;
345 case E_NOMEM:
346 PyErr_NoMemory();
347 return -1;
348 case E_TABSPACE:
349 errtype = PyExc_TabError;
350 msg = "inconsistent use of tabs and spaces in indentation";
351 break;
352 case E_TOODEEP:
353 errtype = PyExc_IndentationError;
354 msg = "too many levels of indentation";
355 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100356 case E_LINECONT:
357 msg = "unexpected character after line continuation character";
358 break;
359 default:
360 msg = "unknown parsing error";
361 }
362
363 PyErr_Format(errtype, msg);
364 // There is no reliable column information for this error
365 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
366
367 return -1;
368}
369
370void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300371_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
372{
373 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100374 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300375 if (t->col_offset == -1) {
376 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
377 intptr_t, int);
378 } else {
379 col_offset = t->col_offset + 1;
380 }
381
382 va_list va;
383 va_start(va, errmsg);
384 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
385 col_offset, errmsg, va);
386 va_end(va);
387
388 return NULL;
389}
390
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200391static PyObject *
392get_error_line(Parser *p, Py_ssize_t lineno)
393{
394 /* If p->tok->fp == NULL, then we're parsing from a string, which means that
395 the whole source is stored in p->tok->str. If not, then we're parsing
396 from the REPL, so the source lines of the current (multi-line) statement
397 are stored in p->tok->stdin_content */
398 assert(p->tok->fp == NULL || p->tok->fp == stdin);
399
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100400 char *cur_line = p->tok->fp_interactive ? p->tok->interactive_src_start : p->tok->str;
401
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200402 for (int i = 0; i < lineno - 1; i++) {
403 cur_line = strchr(cur_line, '\n') + 1;
404 }
405
406 char *next_newline;
407 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
408 next_newline = cur_line + strlen(cur_line);
409 }
410 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
411}
412
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300413void *
414_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100415 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300416 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100417{
418 PyObject *value = NULL;
419 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300420 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100421 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300422 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100423
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300424 if (p->start_rule == Py_fstring_input) {
425 const char *fstring_msg = "f-string: ";
426 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
427
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300428 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300429 if (!new_errmsg) {
430 return (void *) PyErr_NoMemory();
431 }
432
433 // Copy both strings into new buffer
434 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
435 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
436 new_errmsg[len] = 0;
437 errmsg = new_errmsg;
438 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100439 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100440 if (!errstr) {
441 goto error;
442 }
443
Pablo Galindocd8dcbc2021-03-14 04:38:40 +0100444 if (p->tok->fp_interactive) {
445 error_line = get_error_line(p, lineno);
446 }
447 else if (p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300448 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100449 }
450
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300451 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200452 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
453 then we need to find the error line from some other source, because
454 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
455 failed or we're parsing from a string or the REPL. There's a third edge case where
456 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
457 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
458 does not physically exist */
459 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
460
Pablo Galindo40901512021-01-31 22:48:23 +0000461 if (p->tok->lineno <= lineno) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200462 Py_ssize_t size = p->tok->inp - p->tok->buf;
463 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
464 }
465 else {
466 error_line = get_error_line(p, lineno);
467 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300468 if (!error_line) {
469 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300470 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100471 }
472
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300473 if (p->start_rule == Py_fstring_input) {
474 col_offset -= p->starting_col_offset;
475 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100476 Py_ssize_t col_number = col_offset;
477
478 if (p->tok->encoding != NULL) {
479 col_number = byte_offset_to_character_offset(error_line, col_offset);
480 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300481
482 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100483 if (!tmp) {
484 goto error;
485 }
486 value = PyTuple_Pack(2, errstr, tmp);
487 Py_DECREF(tmp);
488 if (!value) {
489 goto error;
490 }
491 PyErr_SetObject(errtype, value);
492
493 Py_DECREF(errstr);
494 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300495 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300496 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300497 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100498 return NULL;
499
500error:
501 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300502 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300503 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300504 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300505 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100506 return NULL;
507}
508
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100509#if 0
510static const char *
511token_name(int type)
512{
513 if (0 <= type && type <= N_TOKENS) {
514 return _PyParser_TokenNames[type];
515 }
516 return "<Huh?>";
517}
518#endif
519
520// Here, mark is the start of the node, while p->mark is the end.
521// If node==NULL, they should be the same.
522int
523_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
524{
525 // Insert in front
526 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
527 if (m == NULL) {
528 return -1;
529 }
530 m->type = type;
531 m->node = node;
532 m->mark = p->mark;
533 m->next = p->tokens[mark]->memo;
534 p->tokens[mark]->memo = m;
535 return 0;
536}
537
538// Like _PyPegen_insert_memo(), but updates an existing node if found.
539int
540_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
541{
542 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
543 if (m->type == type) {
544 // Update existing node.
545 m->node = node;
546 m->mark = p->mark;
547 return 0;
548 }
549 }
550 // Insert new node.
551 return _PyPegen_insert_memo(p, mark, type, node);
552}
553
554// Return dummy NAME.
555void *
556_PyPegen_dummy_name(Parser *p, ...)
557{
558 static void *cache = NULL;
559
560 if (cache != NULL) {
561 return cache;
562 }
563
564 PyObject *id = _create_dummy_identifier(p);
565 if (!id) {
566 return NULL;
567 }
568 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
569 return cache;
570}
571
572static int
573_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
574{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300575 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100576 if (name_len >= p->n_keyword_lists ||
577 p->keywords[name_len] == NULL ||
578 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100579 return NAME;
580 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100581 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100582 if (strncmp(k->str, name, name_len) == 0) {
583 return k->type;
584 }
585 }
586 return NAME;
587}
588
Guido van Rossumc001c092020-04-30 12:12:19 -0700589static int
590growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
591 assert(initial_size > 0);
592 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
593 arr->size = initial_size;
594 arr->num_items = 0;
595
596 return arr->items != NULL;
597}
598
599static int
600growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
601 if (arr->num_items >= arr->size) {
602 size_t new_size = arr->size * 2;
603 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
604 if (!new_items_array) {
605 return 0;
606 }
607 arr->items = new_items_array;
608 arr->size = new_size;
609 }
610
611 arr->items[arr->num_items].lineno = lineno;
612 arr->items[arr->num_items].comment = comment; // Take ownership
613 arr->num_items++;
614 return 1;
615}
616
617static void
618growable_comment_array_deallocate(growable_comment_array *arr) {
619 for (unsigned i = 0; i < arr->num_items; i++) {
620 PyMem_Free(arr->items[i].comment);
621 }
622 PyMem_Free(arr->items);
623}
624
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100625int
626_PyPegen_fill_token(Parser *p)
627{
Pablo Galindofb61c422020-06-15 14:23:43 +0100628 const char *start;
629 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100630 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700631
632 // Record and skip '# type: ignore' comments
633 while (type == TYPE_IGNORE) {
634 Py_ssize_t len = end - start;
635 char *tag = PyMem_Malloc(len + 1);
636 if (tag == NULL) {
637 PyErr_NoMemory();
638 return -1;
639 }
640 strncpy(tag, start, len);
641 tag[len] = '\0';
642 // Ownership of tag passes to the growable array
643 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
644 PyErr_NoMemory();
645 return -1;
646 }
647 type = PyTokenizer_Get(p->tok, &start, &end);
648 }
649
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100650 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
651 type = NEWLINE; /* Add an extra newline */
652 p->parsing_started = 0;
653
Pablo Galindob94dbd72020-04-27 18:35:58 +0100654 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100655 p->tok->pendin = -p->tok->indent;
656 p->tok->indent = 0;
657 }
658 }
659 else {
660 p->parsing_started = 1;
661 }
662
663 if (p->fill == p->size) {
664 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300665 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
666 if (new_tokens == NULL) {
667 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100668 return -1;
669 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100670 p->tokens = new_tokens;
671
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100672 for (int i = p->size; i < newsize; i++) {
673 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300674 if (p->tokens[i] == NULL) {
675 p->size = i; // Needed, in order to cleanup correctly after parser fails
676 PyErr_NoMemory();
677 return -1;
678 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100679 memset(p->tokens[i], '\0', sizeof(Token));
680 }
681 p->size = newsize;
682 }
683
684 Token *t = p->tokens[p->fill];
685 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
686 t->bytes = PyBytes_FromStringAndSize(start, end - start);
687 if (t->bytes == NULL) {
688 return -1;
689 }
690 PyArena_AddPyObject(p->arena, t->bytes);
691
692 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
693 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100694 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100695 int col_offset = -1;
696 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100697 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100698 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100699 }
700 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100701 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100702 }
703
704 t->lineno = p->starting_lineno + lineno;
705 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
706 t->end_lineno = p->starting_lineno + end_lineno;
707 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
708
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100709 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300710
711 if (type == ERRORTOKEN) {
712 if (p->tok->done == E_DECODE) {
713 return raise_decode_error(p);
714 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100715 return tokenizer_error(p);
716
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300717 }
718
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100719 return 0;
720}
721
722// Instrumentation to count the effectiveness of memoization.
723// The array counts the number of tokens skipped by memoization,
724// indexed by type.
725
726#define NSTATISTICS 2000
727static long memo_statistics[NSTATISTICS];
728
729void
730_PyPegen_clear_memo_statistics()
731{
732 for (int i = 0; i < NSTATISTICS; i++) {
733 memo_statistics[i] = 0;
734 }
735}
736
737PyObject *
738_PyPegen_get_memo_statistics()
739{
740 PyObject *ret = PyList_New(NSTATISTICS);
741 if (ret == NULL) {
742 return NULL;
743 }
744 for (int i = 0; i < NSTATISTICS; i++) {
745 PyObject *value = PyLong_FromLong(memo_statistics[i]);
746 if (value == NULL) {
747 Py_DECREF(ret);
748 return NULL;
749 }
750 // PyList_SetItem borrows a reference to value.
751 if (PyList_SetItem(ret, i, value) < 0) {
752 Py_DECREF(ret);
753 return NULL;
754 }
755 }
756 return ret;
757}
758
759int // bool
760_PyPegen_is_memoized(Parser *p, int type, void *pres)
761{
762 if (p->mark == p->fill) {
763 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300764 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100765 return -1;
766 }
767 }
768
769 Token *t = p->tokens[p->mark];
770
771 for (Memo *m = t->memo; m != NULL; m = m->next) {
772 if (m->type == type) {
773 if (0 <= type && type < NSTATISTICS) {
774 long count = m->mark - p->mark;
775 // A memoized negative result counts for one.
776 if (count <= 0) {
777 count = 1;
778 }
779 memo_statistics[type] += count;
780 }
781 p->mark = m->mark;
782 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100783 return 1;
784 }
785 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100786 return 0;
787}
788
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100789int
790_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
791{
792 int mark = p->mark;
793 void *res = func(p);
794 p->mark = mark;
795 return (res != NULL) == positive;
796}
797
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100798int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100799_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
800{
801 int mark = p->mark;
802 void *res = func(p, arg);
803 p->mark = mark;
804 return (res != NULL) == positive;
805}
806
807int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100808_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
809{
810 int mark = p->mark;
811 void *res = func(p, arg);
812 p->mark = mark;
813 return (res != NULL) == positive;
814}
815
816int
817_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
818{
819 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100820 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100821 p->mark = mark;
822 return (res != NULL) == positive;
823}
824
825Token *
826_PyPegen_expect_token(Parser *p, int type)
827{
828 if (p->mark == p->fill) {
829 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300830 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100831 return NULL;
832 }
833 }
834 Token *t = p->tokens[p->mark];
835 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100836 return NULL;
837 }
838 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100839 return t;
840}
841
Pablo Galindo58fb1562021-02-02 19:54:22 +0000842Token *
843_PyPegen_expect_forced_token(Parser *p, int type, const char* expected) {
844
845 if (p->error_indicator == 1) {
846 return NULL;
847 }
848
849 if (p->mark == p->fill) {
850 if (_PyPegen_fill_token(p) < 0) {
851 p->error_indicator = 1;
852 return NULL;
853 }
854 }
855 Token *t = p->tokens[p->mark];
856 if (t->type != type) {
857 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(t, "expected '%s'", expected);
858 return NULL;
859 }
860 p->mark += 1;
861 return t;
862}
863
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700864expr_ty
865_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
866{
867 if (p->mark == p->fill) {
868 if (_PyPegen_fill_token(p) < 0) {
869 p->error_indicator = 1;
870 return NULL;
871 }
872 }
873 Token *t = p->tokens[p->mark];
874 if (t->type != NAME) {
875 return NULL;
876 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300877 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700878 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300879 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700880 return NULL;
881 }
882 if (strcmp(s, keyword) != 0) {
883 return NULL;
884 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300885 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700886}
887
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100888Token *
889_PyPegen_get_last_nonnwhitespace_token(Parser *p)
890{
891 assert(p->mark >= 0);
892 Token *token = NULL;
893 for (int m = p->mark - 1; m >= 0; m--) {
894 token = p->tokens[m];
895 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
896 break;
897 }
898 }
899 return token;
900}
901
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100902expr_ty
903_PyPegen_name_token(Parser *p)
904{
905 Token *t = _PyPegen_expect_token(p, NAME);
906 if (t == NULL) {
907 return NULL;
908 }
909 char* s = PyBytes_AsString(t->bytes);
910 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300911 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100912 return NULL;
913 }
914 PyObject *id = _PyPegen_new_identifier(p, s);
915 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300916 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100917 return NULL;
918 }
919 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
920 p->arena);
921}
922
923void *
924_PyPegen_string_token(Parser *p)
925{
926 return _PyPegen_expect_token(p, STRING);
927}
928
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100929static PyObject *
930parsenumber_raw(const char *s)
931{
932 const char *end;
933 long x;
934 double dx;
935 Py_complex compl;
936 int imflag;
937
938 assert(s != NULL);
939 errno = 0;
940 end = s + strlen(s) - 1;
941 imflag = *end == 'j' || *end == 'J';
942 if (s[0] == '0') {
943 x = (long)PyOS_strtoul(s, (char **)&end, 0);
944 if (x < 0 && errno == 0) {
945 return PyLong_FromString(s, (char **)0, 0);
946 }
947 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100948 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100949 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100950 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100951 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100952 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100953 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100954 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100955 return PyLong_FromLong(x);
956 }
957 /* XXX Huge floats may silently fail */
958 if (imflag) {
959 compl.real = 0.;
960 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100961 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100962 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100963 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100964 return PyComplex_FromCComplex(compl);
965 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100966 dx = PyOS_string_to_double(s, NULL, NULL);
967 if (dx == -1.0 && PyErr_Occurred()) {
968 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100969 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100970 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100971}
972
973static PyObject *
974parsenumber(const char *s)
975{
Pablo Galindofb61c422020-06-15 14:23:43 +0100976 char *dup;
977 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100978 PyObject *res = NULL;
979
980 assert(s != NULL);
981
982 if (strchr(s, '_') == NULL) {
983 return parsenumber_raw(s);
984 }
985 /* Create a duplicate without underscores. */
986 dup = PyMem_Malloc(strlen(s) + 1);
987 if (dup == NULL) {
988 return PyErr_NoMemory();
989 }
990 end = dup;
991 for (; *s; s++) {
992 if (*s != '_') {
993 *end++ = *s;
994 }
995 }
996 *end = '\0';
997 res = parsenumber_raw(dup);
998 PyMem_Free(dup);
999 return res;
1000}
1001
1002expr_ty
1003_PyPegen_number_token(Parser *p)
1004{
1005 Token *t = _PyPegen_expect_token(p, NUMBER);
1006 if (t == NULL) {
1007 return NULL;
1008 }
1009
1010 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001011 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001012 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001013 return NULL;
1014 }
1015
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001016 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
1017 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -07001018 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001019 "in Python 3.6 and greater");
1020 }
1021
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001022 PyObject *c = parsenumber(num_raw);
1023
1024 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001025 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001026 return NULL;
1027 }
1028
1029 if (PyArena_AddPyObject(p->arena, c) < 0) {
1030 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001031 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001032 return NULL;
1033 }
1034
1035 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
1036 p->arena);
1037}
1038
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001039static int // bool
1040newline_in_string(Parser *p, const char *cur)
1041{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001042 for (const char *c = cur; c >= p->tok->buf; c--) {
1043 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001044 return 1;
1045 }
1046 }
1047 return 0;
1048}
1049
1050/* Check that the source for a single input statement really is a single
1051 statement by looking at what is left in the buffer after parsing.
1052 Trailing whitespace and comments are OK. */
1053static int // bool
1054bad_single_statement(Parser *p)
1055{
1056 const char *cur = strchr(p->tok->buf, '\n');
1057
1058 /* Newlines are allowed if preceded by a line continuation character
1059 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001060 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1061 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001062 return 0;
1063 }
1064 char c = *cur;
1065
1066 for (;;) {
1067 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1068 c = *++cur;
1069 }
1070
1071 if (!c) {
1072 return 0;
1073 }
1074
1075 if (c != '#') {
1076 return 1;
1077 }
1078
1079 /* Suck up comment. */
1080 while (c && c != '\n') {
1081 c = *++cur;
1082 }
1083 }
1084}
1085
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001086void
1087_PyPegen_Parser_Free(Parser *p)
1088{
1089 Py_XDECREF(p->normalize);
1090 for (int i = 0; i < p->size; i++) {
1091 PyMem_Free(p->tokens[i]);
1092 }
1093 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001094 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001095 PyMem_Free(p);
1096}
1097
Pablo Galindo2b74c832020-04-27 18:02:07 +01001098static int
1099compute_parser_flags(PyCompilerFlags *flags)
1100{
1101 int parser_flags = 0;
1102 if (!flags) {
1103 return 0;
1104 }
1105 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1106 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1107 }
1108 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1109 parser_flags |= PyPARSE_IGNORE_COOKIE;
1110 }
1111 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1112 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1113 }
1114 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1115 parser_flags |= PyPARSE_TYPE_COMMENTS;
1116 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001117 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001118 parser_flags |= PyPARSE_ASYNC_HACKS;
1119 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001120 return parser_flags;
1121}
1122
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001123Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001124_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001125 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001126{
1127 Parser *p = PyMem_Malloc(sizeof(Parser));
1128 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001129 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001130 }
1131 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001132 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1133 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001134 p->tok = tok;
1135 p->keywords = NULL;
1136 p->n_keyword_lists = -1;
1137 p->tokens = PyMem_Malloc(sizeof(Token *));
1138 if (!p->tokens) {
1139 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001140 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001141 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001142 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001143 if (!p->tokens) {
1144 PyMem_Free(p->tokens);
1145 PyMem_Free(p);
1146 return (Parser *) PyErr_NoMemory();
1147 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001148 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1149 PyMem_Free(p->tokens[0]);
1150 PyMem_Free(p->tokens);
1151 PyMem_Free(p);
1152 return (Parser *) PyErr_NoMemory();
1153 }
1154
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001155 p->mark = 0;
1156 p->fill = 0;
1157 p->size = 1;
1158
1159 p->errcode = errcode;
1160 p->arena = arena;
1161 p->start_rule = start_rule;
1162 p->parsing_started = 0;
1163 p->normalize = NULL;
1164 p->error_indicator = 0;
1165
1166 p->starting_lineno = 0;
1167 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001168 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001169 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001170 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001171 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001172 p->call_invalid_rules = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001173
1174 return p;
1175}
1176
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001177static void
1178reset_parser_state(Parser *p)
1179{
1180 for (int i = 0; i < p->fill; i++) {
1181 p->tokens[i]->memo = NULL;
1182 }
1183 p->mark = 0;
1184 p->call_invalid_rules = 1;
1185}
1186
Pablo Galindod6d63712021-01-19 23:59:33 +00001187static int
1188_PyPegen_check_tokenizer_errors(Parser *p) {
1189 // Tokenize the whole input to see if there are any tokenization
1190 // errors such as mistmatching parentheses. These will get priority
1191 // over generic syntax errors only if the line number of the error is
1192 // before the one that we had for the generic error.
1193
1194 // We don't want to tokenize to the end for interactive input
1195 if (p->tok->prompt != NULL) {
1196 return 0;
1197 }
1198
Pablo Galindod6d63712021-01-19 23:59:33 +00001199 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1200 Py_ssize_t current_err_line = current_token->lineno;
1201
Pablo Galindod6d63712021-01-19 23:59:33 +00001202 for (;;) {
1203 const char *start;
1204 const char *end;
1205 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1206 case ERRORTOKEN:
1207 if (p->tok->level != 0) {
1208 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1209 if (current_err_line > error_lineno) {
1210 raise_unclosed_parentheses_error(p);
1211 return -1;
1212 }
1213 }
1214 break;
1215 case ENDMARKER:
1216 break;
1217 default:
1218 continue;
1219 }
1220 break;
1221 }
1222
Pablo Galindod6d63712021-01-19 23:59:33 +00001223 return 0;
1224}
1225
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001226void *
1227_PyPegen_run_parser(Parser *p)
1228{
1229 void *res = _PyPegen_parse(p);
1230 if (res == NULL) {
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001231 reset_parser_state(p);
1232 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001233 if (PyErr_Occurred()) {
1234 return NULL;
1235 }
1236 if (p->fill == 0) {
1237 RAISE_SYNTAX_ERROR("error at start before reading any input");
1238 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001239 else if (p->tok->done == E_EOF) {
Pablo Galindod6d63712021-01-19 23:59:33 +00001240 if (p->tok->level) {
1241 raise_unclosed_parentheses_error(p);
1242 } else {
1243 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1244 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001245 }
1246 else {
1247 if (p->tokens[p->fill-1]->type == INDENT) {
1248 RAISE_INDENTATION_ERROR("unexpected indent");
1249 }
1250 else if (p->tokens[p->fill-1]->type == DEDENT) {
1251 RAISE_INDENTATION_ERROR("unexpected unindent");
1252 }
1253 else {
1254 RAISE_SYNTAX_ERROR("invalid syntax");
Pablo Galindoc3f167d2021-01-20 19:11:56 +00001255 // _PyPegen_check_tokenizer_errors will override the existing
1256 // generic SyntaxError we just raised if errors are found.
1257 _PyPegen_check_tokenizer_errors(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001258 }
1259 }
1260 return NULL;
1261 }
1262
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001263 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1264 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1265 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1266 }
1267
Victor Stinnere0bf70d2021-03-18 02:46:06 +01001268 // test_peg_generator defines _Py_TEST_PEGEN to not call PyAST_Validate()
1269#if defined(Py_DEBUG) && !defined(_Py_TEST_PEGEN)
Pablo Galindo13322262020-07-27 23:46:59 +01001270 if (p->start_rule == Py_single_input ||
1271 p->start_rule == Py_file_input ||
1272 p->start_rule == Py_eval_input)
1273 {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001274 if (!PyAST_Validate(res)) {
1275 return NULL;
1276 }
Pablo Galindo13322262020-07-27 23:46:59 +01001277 }
1278#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001279 return res;
1280}
1281
1282mod_ty
1283_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1284 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001285 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001286{
1287 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1288 if (tok == NULL) {
1289 if (PyErr_Occurred()) {
1290 raise_tokenizer_init_error(filename_ob);
1291 return NULL;
1292 }
1293 return NULL;
1294 }
Pablo Galindocd8dcbc2021-03-14 04:38:40 +01001295 if (!tok->fp || ps1 != NULL || ps2 != NULL ||
1296 PyUnicode_CompareWithASCIIString(filename_ob, "<stdin>") == 0) {
1297 tok->fp_interactive = 1;
1298 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001299 // This transfers the ownership to the tokenizer
1300 tok->filename = filename_ob;
1301 Py_INCREF(filename_ob);
1302
1303 // From here on we need to clean up even if there's an error
1304 mod_ty result = NULL;
1305
Pablo Galindo2b74c832020-04-27 18:02:07 +01001306 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001307 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1308 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001309 if (p == NULL) {
1310 goto error;
1311 }
1312
1313 result = _PyPegen_run_parser(p);
1314 _PyPegen_Parser_Free(p);
1315
1316error:
1317 PyTokenizer_Free(tok);
1318 return result;
1319}
1320
1321mod_ty
1322_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001323 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001324{
1325 FILE *fp = fopen(filename, "rb");
1326 if (fp == NULL) {
1327 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1328 return NULL;
1329 }
1330
1331 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001332 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001333
1334 fclose(fp);
1335 return result;
1336}
1337
1338mod_ty
1339_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001340 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001341{
1342 int exec_input = start_rule == Py_file_input;
1343
1344 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001345 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001346 tok = PyTokenizer_FromUTF8(str, exec_input);
1347 } else {
1348 tok = PyTokenizer_FromString(str, exec_input);
1349 }
1350 if (tok == NULL) {
1351 if (PyErr_Occurred()) {
1352 raise_tokenizer_init_error(filename_ob);
1353 }
1354 return NULL;
1355 }
1356 // This transfers the ownership to the tokenizer
1357 tok->filename = filename_ob;
1358 Py_INCREF(filename_ob);
1359
1360 // We need to clear up from here on
1361 mod_ty result = NULL;
1362
Pablo Galindo2b74c832020-04-27 18:02:07 +01001363 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001364 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1365 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001366 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1367 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001368 if (p == NULL) {
1369 goto error;
1370 }
1371
1372 result = _PyPegen_run_parser(p);
1373 _PyPegen_Parser_Free(p);
1374
1375error:
1376 PyTokenizer_Free(tok);
1377 return result;
1378}
1379
Pablo Galindoa5634c42020-09-16 19:42:00 +01001380asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001381_PyPegen_interactive_exit(Parser *p)
1382{
1383 if (p->errcode) {
1384 *(p->errcode) = E_EOF;
1385 }
1386 return NULL;
1387}
1388
1389/* Creates a single-element asdl_seq* that contains a */
1390asdl_seq *
1391_PyPegen_singleton_seq(Parser *p, void *a)
1392{
1393 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001394 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001395 if (!seq) {
1396 return NULL;
1397 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001398 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001399 return seq;
1400}
1401
1402/* Creates a copy of seq and prepends a to it */
1403asdl_seq *
1404_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1405{
1406 assert(a != NULL);
1407 if (!seq) {
1408 return _PyPegen_singleton_seq(p, a);
1409 }
1410
Pablo Galindoa5634c42020-09-16 19:42:00 +01001411 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 +01001412 if (!new_seq) {
1413 return NULL;
1414 }
1415
Pablo Galindoa5634c42020-09-16 19:42:00 +01001416 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001417 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001418 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001419 }
1420 return new_seq;
1421}
1422
Guido van Rossumc001c092020-04-30 12:12:19 -07001423/* Creates a copy of seq and appends a to it */
1424asdl_seq *
1425_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1426{
1427 assert(a != NULL);
1428 if (!seq) {
1429 return _PyPegen_singleton_seq(p, a);
1430 }
1431
Pablo Galindoa5634c42020-09-16 19:42:00 +01001432 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 -07001433 if (!new_seq) {
1434 return NULL;
1435 }
1436
1437 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001438 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001439 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001440 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001441 return new_seq;
1442}
1443
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001444static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001445_get_flattened_seq_size(asdl_seq *seqs)
1446{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001447 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001448 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001449 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001450 size += asdl_seq_LEN(inner_seq);
1451 }
1452 return size;
1453}
1454
1455/* Flattens an asdl_seq* of asdl_seq*s */
1456asdl_seq *
1457_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1458{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001459 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001460 assert(flattened_seq_size > 0);
1461
Pablo Galindoa5634c42020-09-16 19:42:00 +01001462 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001463 if (!flattened_seq) {
1464 return NULL;
1465 }
1466
1467 int flattened_seq_idx = 0;
1468 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001469 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001470 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001471 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001472 }
1473 }
1474 assert(flattened_seq_idx == flattened_seq_size);
1475
1476 return flattened_seq;
1477}
1478
1479/* Creates a new name of the form <first_name>.<second_name> */
1480expr_ty
1481_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1482{
1483 assert(first_name != NULL && second_name != NULL);
1484 PyObject *first_identifier = first_name->v.Name.id;
1485 PyObject *second_identifier = second_name->v.Name.id;
1486
1487 if (PyUnicode_READY(first_identifier) == -1) {
1488 return NULL;
1489 }
1490 if (PyUnicode_READY(second_identifier) == -1) {
1491 return NULL;
1492 }
1493 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1494 if (!first_str) {
1495 return NULL;
1496 }
1497 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1498 if (!second_str) {
1499 return NULL;
1500 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001501 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001502
1503 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1504 if (!str) {
1505 return NULL;
1506 }
1507
1508 char *s = PyBytes_AS_STRING(str);
1509 if (!s) {
1510 return NULL;
1511 }
1512
1513 strcpy(s, first_str);
1514 s += strlen(first_str);
1515 *s++ = '.';
1516 strcpy(s, second_str);
1517 s += strlen(second_str);
1518 *s = '\0';
1519
1520 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1521 Py_DECREF(str);
1522 if (!uni) {
1523 return NULL;
1524 }
1525 PyUnicode_InternInPlace(&uni);
1526 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1527 Py_DECREF(uni);
1528 return NULL;
1529 }
1530
1531 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1532}
1533
1534/* Counts the total number of dots in seq's tokens */
1535int
1536_PyPegen_seq_count_dots(asdl_seq *seq)
1537{
1538 int number_of_dots = 0;
1539 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001540 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001541 switch (current_expr->type) {
1542 case ELLIPSIS:
1543 number_of_dots += 3;
1544 break;
1545 case DOT:
1546 number_of_dots += 1;
1547 break;
1548 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001549 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001550 }
1551 }
1552
1553 return number_of_dots;
1554}
1555
1556/* Creates an alias with '*' as the identifier name */
1557alias_ty
1558_PyPegen_alias_for_star(Parser *p)
1559{
1560 PyObject *str = PyUnicode_InternFromString("*");
1561 if (!str) {
1562 return NULL;
1563 }
1564 if (PyArena_AddPyObject(p->arena, str) < 0) {
1565 Py_DECREF(str);
1566 return NULL;
1567 }
1568 return alias(str, NULL, p->arena);
1569}
1570
1571/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001572asdl_identifier_seq *
1573_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001574{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001575 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001576 assert(len > 0);
1577
Pablo Galindoa5634c42020-09-16 19:42:00 +01001578 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001579 if (!new_seq) {
1580 return NULL;
1581 }
1582 for (Py_ssize_t i = 0; i < len; i++) {
1583 expr_ty e = asdl_seq_GET(seq, i);
1584 asdl_seq_SET(new_seq, i, e->v.Name.id);
1585 }
1586 return new_seq;
1587}
1588
1589/* Constructs a CmpopExprPair */
1590CmpopExprPair *
1591_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1592{
1593 assert(expr != NULL);
1594 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1595 if (!a) {
1596 return NULL;
1597 }
1598 a->cmpop = cmpop;
1599 a->expr = expr;
1600 return a;
1601}
1602
1603asdl_int_seq *
1604_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1605{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001606 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001607 assert(len > 0);
1608
1609 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1610 if (!new_seq) {
1611 return NULL;
1612 }
1613 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001614 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001615 asdl_seq_SET(new_seq, i, pair->cmpop);
1616 }
1617 return new_seq;
1618}
1619
Pablo Galindoa5634c42020-09-16 19:42:00 +01001620asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001621_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1622{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001623 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001624 assert(len > 0);
1625
Pablo Galindoa5634c42020-09-16 19:42:00 +01001626 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001627 if (!new_seq) {
1628 return NULL;
1629 }
1630 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001631 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001632 asdl_seq_SET(new_seq, i, pair->expr);
1633 }
1634 return new_seq;
1635}
1636
1637/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001638static asdl_expr_seq *
1639_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001640{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001641 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001642 if (len == 0) {
1643 return NULL;
1644 }
1645
Pablo Galindoa5634c42020-09-16 19:42:00 +01001646 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001647 if (!new_seq) {
1648 return NULL;
1649 }
1650 for (Py_ssize_t i = 0; i < len; i++) {
1651 expr_ty e = asdl_seq_GET(seq, i);
1652 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1653 }
1654 return new_seq;
1655}
1656
1657static expr_ty
1658_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1659{
1660 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1661}
1662
1663static expr_ty
1664_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1665{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001666 return _Py_Tuple(
1667 _set_seq_context(p, e->v.Tuple.elts, ctx),
1668 ctx,
1669 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001670}
1671
1672static expr_ty
1673_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1674{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001675 return _Py_List(
1676 _set_seq_context(p, e->v.List.elts, ctx),
1677 ctx,
1678 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001679}
1680
1681static expr_ty
1682_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1683{
1684 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1685}
1686
1687static expr_ty
1688_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1689{
1690 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1691}
1692
1693static expr_ty
1694_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1695{
1696 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1697}
1698
1699/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1700expr_ty
1701_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1702{
1703 assert(expr != NULL);
1704
1705 expr_ty new = NULL;
1706 switch (expr->kind) {
1707 case Name_kind:
1708 new = _set_name_context(p, expr, ctx);
1709 break;
1710 case Tuple_kind:
1711 new = _set_tuple_context(p, expr, ctx);
1712 break;
1713 case List_kind:
1714 new = _set_list_context(p, expr, ctx);
1715 break;
1716 case Subscript_kind:
1717 new = _set_subscript_context(p, expr, ctx);
1718 break;
1719 case Attribute_kind:
1720 new = _set_attribute_context(p, expr, ctx);
1721 break;
1722 case Starred_kind:
1723 new = _set_starred_context(p, expr, ctx);
1724 break;
1725 default:
1726 new = expr;
1727 }
1728 return new;
1729}
1730
1731/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1732KeyValuePair *
1733_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1734{
1735 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1736 if (!a) {
1737 return NULL;
1738 }
1739 a->key = key;
1740 a->value = value;
1741 return a;
1742}
1743
1744/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001745asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001746_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1747{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001748 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001749 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001750 if (!new_seq) {
1751 return NULL;
1752 }
1753 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001754 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001755 asdl_seq_SET(new_seq, i, pair->key);
1756 }
1757 return new_seq;
1758}
1759
1760/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001761asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001762_PyPegen_get_values(Parser *p, asdl_seq *seq)
1763{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001764 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001765 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001766 if (!new_seq) {
1767 return NULL;
1768 }
1769 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001770 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001771 asdl_seq_SET(new_seq, i, pair->value);
1772 }
1773 return new_seq;
1774}
1775
1776/* Constructs a NameDefaultPair */
1777NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001778_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001779{
1780 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1781 if (!a) {
1782 return NULL;
1783 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001784 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001785 a->value = value;
1786 return a;
1787}
1788
1789/* Constructs a SlashWithDefault */
1790SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001791_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001792{
1793 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1794 if (!a) {
1795 return NULL;
1796 }
1797 a->plain_names = plain_names;
1798 a->names_with_defaults = names_with_defaults;
1799 return a;
1800}
1801
1802/* Constructs a StarEtc */
1803StarEtc *
1804_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1805{
1806 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1807 if (!a) {
1808 return NULL;
1809 }
1810 a->vararg = vararg;
1811 a->kwonlyargs = kwonlyargs;
1812 a->kwarg = kwarg;
1813 return a;
1814}
1815
1816asdl_seq *
1817_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1818{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001819 Py_ssize_t first_len = asdl_seq_LEN(a);
1820 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001821 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001822 if (!new_seq) {
1823 return NULL;
1824 }
1825
1826 int k = 0;
1827 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001828 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001829 }
1830 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001831 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001832 }
1833
1834 return new_seq;
1835}
1836
Pablo Galindoa5634c42020-09-16 19:42:00 +01001837static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001838_get_names(Parser *p, asdl_seq *names_with_defaults)
1839{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001840 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001841 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001842 if (!seq) {
1843 return NULL;
1844 }
1845 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001846 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001847 asdl_seq_SET(seq, i, pair->arg);
1848 }
1849 return seq;
1850}
1851
Pablo Galindoa5634c42020-09-16 19:42:00 +01001852static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001853_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1854{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001855 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001856 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001857 if (!seq) {
1858 return NULL;
1859 }
1860 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001861 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001862 asdl_seq_SET(seq, i, pair->value);
1863 }
1864 return seq;
1865}
1866
1867/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1868arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001869_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
1870 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001871 asdl_seq *names_with_default, StarEtc *star_etc)
1872{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001873 asdl_arg_seq *posonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001874 if (slash_without_default != NULL) {
1875 posonlyargs = slash_without_default;
1876 }
1877 else if (slash_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001878 asdl_arg_seq *slash_with_default_names =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001879 _get_names(p, slash_with_default->names_with_defaults);
1880 if (!slash_with_default_names) {
1881 return NULL;
1882 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001883 posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1884 p,
1885 (asdl_seq*)slash_with_default->plain_names,
1886 (asdl_seq*)slash_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001887 if (!posonlyargs) {
1888 return NULL;
1889 }
1890 }
1891 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001892 posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001893 if (!posonlyargs) {
1894 return NULL;
1895 }
1896 }
1897
Pablo Galindoa5634c42020-09-16 19:42:00 +01001898 asdl_arg_seq *posargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001899 if (plain_names != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001900 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001901 if (!names_with_default_names) {
1902 return NULL;
1903 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001904 posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1905 p,
1906 (asdl_seq*)plain_names,
1907 (asdl_seq*)names_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001908 if (!posargs) {
1909 return NULL;
1910 }
1911 }
1912 else if (plain_names == NULL && names_with_default != NULL) {
1913 posargs = _get_names(p, names_with_default);
1914 if (!posargs) {
1915 return NULL;
1916 }
1917 }
1918 else if (plain_names != NULL && names_with_default == NULL) {
1919 posargs = plain_names;
1920 }
1921 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001922 posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001923 if (!posargs) {
1924 return NULL;
1925 }
1926 }
1927
Pablo Galindoa5634c42020-09-16 19:42:00 +01001928 asdl_expr_seq *posdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001929 if (slash_with_default != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001930 asdl_expr_seq *slash_with_default_values =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001931 _get_defaults(p, slash_with_default->names_with_defaults);
1932 if (!slash_with_default_values) {
1933 return NULL;
1934 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001935 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001936 if (!names_with_default_values) {
1937 return NULL;
1938 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001939 posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
1940 p,
1941 (asdl_seq*)slash_with_default_values,
1942 (asdl_seq*)names_with_default_values);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001943 if (!posdefaults) {
1944 return NULL;
1945 }
1946 }
1947 else if (slash_with_default == NULL && names_with_default != NULL) {
1948 posdefaults = _get_defaults(p, names_with_default);
1949 if (!posdefaults) {
1950 return NULL;
1951 }
1952 }
1953 else if (slash_with_default != NULL && names_with_default == NULL) {
1954 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1955 if (!posdefaults) {
1956 return NULL;
1957 }
1958 }
1959 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001960 posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001961 if (!posdefaults) {
1962 return NULL;
1963 }
1964 }
1965
1966 arg_ty vararg = NULL;
1967 if (star_etc != NULL && star_etc->vararg != NULL) {
1968 vararg = star_etc->vararg;
1969 }
1970
Pablo Galindoa5634c42020-09-16 19:42:00 +01001971 asdl_arg_seq *kwonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001972 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1973 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1974 if (!kwonlyargs) {
1975 return NULL;
1976 }
1977 }
1978 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001979 kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001980 if (!kwonlyargs) {
1981 return NULL;
1982 }
1983 }
1984
Pablo Galindoa5634c42020-09-16 19:42:00 +01001985 asdl_expr_seq *kwdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001986 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1987 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1988 if (!kwdefaults) {
1989 return NULL;
1990 }
1991 }
1992 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001993 kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001994 if (!kwdefaults) {
1995 return NULL;
1996 }
1997 }
1998
1999 arg_ty kwarg = NULL;
2000 if (star_etc != NULL && star_etc->kwarg != NULL) {
2001 kwarg = star_etc->kwarg;
2002 }
2003
2004 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
2005 posdefaults, p->arena);
2006}
2007
2008/* Constructs an empty arguments_ty object, that gets used when a function accepts no
2009 * arguments. */
2010arguments_ty
2011_PyPegen_empty_arguments(Parser *p)
2012{
Pablo Galindoa5634c42020-09-16 19:42:00 +01002013 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002014 if (!posonlyargs) {
2015 return NULL;
2016 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002017 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002018 if (!posargs) {
2019 return NULL;
2020 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002021 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002022 if (!posdefaults) {
2023 return NULL;
2024 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002025 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002026 if (!kwonlyargs) {
2027 return NULL;
2028 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002029 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002030 if (!kwdefaults) {
2031 return NULL;
2032 }
2033
Batuhan Taskaya02a16032020-10-10 20:14:59 +03002034 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, posdefaults,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002035 p->arena);
2036}
2037
2038/* Encapsulates the value of an operator_ty into an AugOperator struct */
2039AugOperator *
2040_PyPegen_augoperator(Parser *p, operator_ty kind)
2041{
2042 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
2043 if (!a) {
2044 return NULL;
2045 }
2046 a->kind = kind;
2047 return a;
2048}
2049
2050/* Construct a FunctionDef equivalent to function_def, but with decorators */
2051stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002052_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002053{
2054 assert(function_def != NULL);
2055 if (function_def->kind == AsyncFunctionDef_kind) {
2056 return _Py_AsyncFunctionDef(
2057 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2058 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2059 function_def->v.FunctionDef.type_comment, function_def->lineno,
2060 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2061 p->arena);
2062 }
2063
2064 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2065 function_def->v.FunctionDef.body, decorators,
2066 function_def->v.FunctionDef.returns,
2067 function_def->v.FunctionDef.type_comment, function_def->lineno,
2068 function_def->col_offset, function_def->end_lineno,
2069 function_def->end_col_offset, p->arena);
2070}
2071
2072/* Construct a ClassDef equivalent to class_def, but with decorators */
2073stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002074_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002075{
2076 assert(class_def != NULL);
2077 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2078 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2079 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2080 class_def->end_col_offset, p->arena);
2081}
2082
2083/* Construct a KeywordOrStarred */
2084KeywordOrStarred *
2085_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2086{
2087 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
2088 if (!a) {
2089 return NULL;
2090 }
2091 a->element = element;
2092 a->is_keyword = is_keyword;
2093 return a;
2094}
2095
2096/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2097static int
2098_seq_number_of_starred_exprs(asdl_seq *seq)
2099{
2100 int n = 0;
2101 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002102 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002103 if (!k->is_keyword) {
2104 n++;
2105 }
2106 }
2107 return n;
2108}
2109
2110/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002111asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002112_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2113{
2114 int new_len = _seq_number_of_starred_exprs(kwargs);
2115 if (new_len == 0) {
2116 return NULL;
2117 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002118 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002119 if (!new_seq) {
2120 return NULL;
2121 }
2122
2123 int idx = 0;
2124 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002125 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002126 if (!k->is_keyword) {
2127 asdl_seq_SET(new_seq, idx++, k->element);
2128 }
2129 }
2130 return new_seq;
2131}
2132
2133/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002134asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002135_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2136{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002137 Py_ssize_t len = asdl_seq_LEN(kwargs);
2138 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002139 if (new_len == 0) {
2140 return NULL;
2141 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002142 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002143 if (!new_seq) {
2144 return NULL;
2145 }
2146
2147 int idx = 0;
2148 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002149 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002150 if (k->is_keyword) {
2151 asdl_seq_SET(new_seq, idx++, k->element);
2152 }
2153 }
2154 return new_seq;
2155}
2156
2157expr_ty
2158_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2159{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002160 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002161 assert(len > 0);
2162
Pablo Galindoa5634c42020-09-16 19:42:00 +01002163 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2164 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002165
2166 int bytesmode = 0;
2167 PyObject *bytes_str = NULL;
2168
2169 FstringParser state;
2170 _PyPegen_FstringParser_Init(&state);
2171
2172 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002173 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002174
2175 int this_bytesmode;
2176 int this_rawmode;
2177 PyObject *s;
2178 const char *fstr;
2179 Py_ssize_t fstrlen = -1;
2180
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002181 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002182 goto error;
2183 }
2184
2185 /* Check that we are not mixing bytes with unicode. */
2186 if (i != 0 && bytesmode != this_bytesmode) {
2187 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2188 Py_XDECREF(s);
2189 goto error;
2190 }
2191 bytesmode = this_bytesmode;
2192
2193 if (fstr != NULL) {
2194 assert(s == NULL && !bytesmode);
2195
2196 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2197 this_rawmode, 0, first, t, last);
2198 if (result < 0) {
2199 goto error;
2200 }
2201 }
2202 else {
2203 /* String or byte string. */
2204 assert(s != NULL && fstr == NULL);
2205 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2206
2207 if (bytesmode) {
2208 if (i == 0) {
2209 bytes_str = s;
2210 }
2211 else {
2212 PyBytes_ConcatAndDel(&bytes_str, s);
2213 if (!bytes_str) {
2214 goto error;
2215 }
2216 }
2217 }
2218 else {
2219 /* This is a regular string. Concatenate it. */
2220 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2221 goto error;
2222 }
2223 }
2224 }
2225 }
2226
2227 if (bytesmode) {
2228 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2229 goto error;
2230 }
2231 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2232 last->end_col_offset, p->arena);
2233 }
2234
2235 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2236
2237error:
2238 Py_XDECREF(bytes_str);
2239 _PyPegen_FstringParser_Dealloc(&state);
2240 if (PyErr_Occurred()) {
2241 raise_decode_error(p);
2242 }
2243 return NULL;
2244}
Guido van Rossumc001c092020-04-30 12:12:19 -07002245
2246mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002247_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2248 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002249 Py_ssize_t num = p->type_ignore_comments.num_items;
2250 if (num > 0) {
2251 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002252 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002253 if (type_ignores == NULL) {
2254 return NULL;
2255 }
2256 for (int i = 0; i < num; i++) {
2257 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2258 if (tag == NULL) {
2259 return NULL;
2260 }
2261 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2262 if (ti == NULL) {
2263 return NULL;
2264 }
2265 asdl_seq_SET(type_ignores, i, ti);
2266 }
2267 }
2268 return Module(a, type_ignores, p->arena);
2269}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002270
2271// Error reporting helpers
2272
2273expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002274_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002275{
2276 if (e == NULL) {
2277 return NULL;
2278 }
2279
2280#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2281 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2282 for (Py_ssize_t i = 0; i < len; i++) {\
2283 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002284 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002285 if (child != NULL) {\
2286 return child;\
2287 }\
2288 }\
2289 } while (0)
2290
2291 // We only need to visit List and Tuple nodes recursively as those
2292 // are the only ones that can contain valid names in targets when
2293 // they are parsed as expressions. Any other kind of expression
2294 // that is a container (like Sets or Dicts) is directly invalid and
2295 // we don't need to visit it recursively.
2296
2297 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002298 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002299 VISIT_CONTAINER(e, List);
2300 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002301 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002302 VISIT_CONTAINER(e, Tuple);
2303 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002304 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002305 if (targets_type == DEL_TARGETS) {
2306 return e;
2307 }
2308 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2309 case Compare_kind:
2310 // This is needed, because the `a in b` in `for a in b` gets parsed
2311 // as a comparison, and so we need to search the left side of the comparison
2312 // for invalid targets.
2313 if (targets_type == FOR_TARGETS) {
2314 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2315 if (cmpop == In) {
2316 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2317 }
2318 return NULL;
2319 }
2320 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002321 case Name_kind:
2322 case Subscript_kind:
2323 case Attribute_kind:
2324 return NULL;
2325 default:
2326 return e;
2327 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002328}
2329
2330void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2331 int kwarg_unpacking = 0;
2332 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2333 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2334 if (!keyword->arg) {
2335 kwarg_unpacking = 1;
2336 }
2337 }
2338
2339 const char *msg = NULL;
2340 if (kwarg_unpacking) {
2341 msg = "positional argument follows keyword argument unpacking";
2342 } else {
2343 msg = "positional argument follows keyword argument";
2344 }
2345
2346 return RAISE_SYNTAX_ERROR(msg);
2347}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002348
2349void *
2350_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2351{
2352 /* The rule that calls this function is 'args for_if_clauses'.
2353 For the input f(L, x for x in y), L and x are in args and
2354 the for is parsed as a for_if_clause. We have to check if
2355 len <= 1, so that input like dict((a, b) for a, b in x)
2356 gets successfully parsed and then we pass the last
2357 argument (x in the above example) as the location of the
2358 error */
2359 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2360 if (len <= 1) {
2361 return NULL;
2362 }
2363
2364 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2365 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2366 "Generator expression must be parenthesized"
2367 );
2368}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002369
2370
Pablo Galindoa5634c42020-09-16 19:42:00 +01002371expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002372 int lineno, int col_offset, int end_lineno,
2373 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002374 Py_ssize_t args_len = asdl_seq_LEN(a);
2375 Py_ssize_t total_len = args_len;
2376
2377 if (b == NULL) {
Pablo Galindo315a61f2020-09-03 15:29:32 +01002378 return _Py_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2379 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002380
2381 }
2382
Pablo Galindoa5634c42020-09-16 19:42:00 +01002383 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2384 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002385
2386 if (starreds) {
2387 total_len += asdl_seq_LEN(starreds);
2388 }
2389
Pablo Galindoa5634c42020-09-16 19:42:00 +01002390 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002391
2392 Py_ssize_t i = 0;
2393 for (i = 0; i < args_len; i++) {
2394 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2395 }
2396 for (; i < total_len; i++) {
2397 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2398 }
2399
Pablo Galindo315a61f2020-09-03 15:29:32 +01002400 return _Py_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2401 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002402}