blob: 6c279806021057ba34f6e2c6a1c38db10756be9f [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;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100330 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300331 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
332 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100333 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300334 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
335 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300336 case E_EOF:
Pablo Galindod6d63712021-01-19 23:59:33 +0000337 if (p->tok->level) {
338 raise_unclosed_parentheses_error(p);
339 } else {
340 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
341 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300342 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100343 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300344 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
345 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100346 case E_INTR:
347 if (!PyErr_Occurred()) {
348 PyErr_SetNone(PyExc_KeyboardInterrupt);
349 }
350 return -1;
351 case E_NOMEM:
352 PyErr_NoMemory();
353 return -1;
354 case E_TABSPACE:
355 errtype = PyExc_TabError;
356 msg = "inconsistent use of tabs and spaces in indentation";
357 break;
358 case E_TOODEEP:
359 errtype = PyExc_IndentationError;
360 msg = "too many levels of indentation";
361 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100362 case E_LINECONT:
363 msg = "unexpected character after line continuation character";
364 break;
365 default:
366 msg = "unknown parsing error";
367 }
368
369 PyErr_Format(errtype, msg);
370 // There is no reliable column information for this error
371 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
372
373 return -1;
374}
375
376void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300377_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
378{
379 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100380 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300381 if (t->col_offset == -1) {
382 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
383 intptr_t, int);
384 } else {
385 col_offset = t->col_offset + 1;
386 }
387
388 va_list va;
389 va_start(va, errmsg);
390 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
391 col_offset, errmsg, va);
392 va_end(va);
393
394 return NULL;
395}
396
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200397static PyObject *
398get_error_line(Parser *p, Py_ssize_t lineno)
399{
400 /* If p->tok->fp == NULL, then we're parsing from a string, which means that
401 the whole source is stored in p->tok->str. If not, then we're parsing
402 from the REPL, so the source lines of the current (multi-line) statement
403 are stored in p->tok->stdin_content */
404 assert(p->tok->fp == NULL || p->tok->fp == stdin);
405
406 char *cur_line = p->tok->fp == NULL ? p->tok->str : p->tok->stdin_content;
407 for (int i = 0; i < lineno - 1; i++) {
408 cur_line = strchr(cur_line, '\n') + 1;
409 }
410
411 char *next_newline;
412 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
413 next_newline = cur_line + strlen(cur_line);
414 }
415 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
416}
417
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300418void *
419_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100420 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300421 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100422{
423 PyObject *value = NULL;
424 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300425 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100426 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300427 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100428
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300429 if (p->start_rule == Py_fstring_input) {
430 const char *fstring_msg = "f-string: ";
431 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
432
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300433 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300434 if (!new_errmsg) {
435 return (void *) PyErr_NoMemory();
436 }
437
438 // Copy both strings into new buffer
439 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
440 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
441 new_errmsg[len] = 0;
442 errmsg = new_errmsg;
443 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100444 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100445 if (!errstr) {
446 goto error;
447 }
448
449 if (p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300450 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100451 }
452
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300453 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200454 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
455 then we need to find the error line from some other source, because
456 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
457 failed or we're parsing from a string or the REPL. There's a third edge case where
458 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
459 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
460 does not physically exist */
461 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
462
463 if (p->tok->lineno == lineno) {
464 Py_ssize_t size = p->tok->inp - p->tok->buf;
465 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
466 }
467 else {
468 error_line = get_error_line(p, lineno);
469 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300470 if (!error_line) {
471 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300472 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100473 }
474
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300475 if (p->start_rule == Py_fstring_input) {
476 col_offset -= p->starting_col_offset;
477 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100478 Py_ssize_t col_number = col_offset;
479
480 if (p->tok->encoding != NULL) {
481 col_number = byte_offset_to_character_offset(error_line, col_offset);
482 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300483
484 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100485 if (!tmp) {
486 goto error;
487 }
488 value = PyTuple_Pack(2, errstr, tmp);
489 Py_DECREF(tmp);
490 if (!value) {
491 goto error;
492 }
493 PyErr_SetObject(errtype, value);
494
495 Py_DECREF(errstr);
496 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300497 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300498 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300499 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100500 return NULL;
501
502error:
503 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300504 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300505 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300506 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300507 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100508 return NULL;
509}
510
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100511#if 0
512static const char *
513token_name(int type)
514{
515 if (0 <= type && type <= N_TOKENS) {
516 return _PyParser_TokenNames[type];
517 }
518 return "<Huh?>";
519}
520#endif
521
522// Here, mark is the start of the node, while p->mark is the end.
523// If node==NULL, they should be the same.
524int
525_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
526{
527 // Insert in front
528 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
529 if (m == NULL) {
530 return -1;
531 }
532 m->type = type;
533 m->node = node;
534 m->mark = p->mark;
535 m->next = p->tokens[mark]->memo;
536 p->tokens[mark]->memo = m;
537 return 0;
538}
539
540// Like _PyPegen_insert_memo(), but updates an existing node if found.
541int
542_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
543{
544 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
545 if (m->type == type) {
546 // Update existing node.
547 m->node = node;
548 m->mark = p->mark;
549 return 0;
550 }
551 }
552 // Insert new node.
553 return _PyPegen_insert_memo(p, mark, type, node);
554}
555
556// Return dummy NAME.
557void *
558_PyPegen_dummy_name(Parser *p, ...)
559{
560 static void *cache = NULL;
561
562 if (cache != NULL) {
563 return cache;
564 }
565
566 PyObject *id = _create_dummy_identifier(p);
567 if (!id) {
568 return NULL;
569 }
570 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
571 return cache;
572}
573
574static int
575_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
576{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300577 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100578 if (name_len >= p->n_keyword_lists ||
579 p->keywords[name_len] == NULL ||
580 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100581 return NAME;
582 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100583 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100584 if (strncmp(k->str, name, name_len) == 0) {
585 return k->type;
586 }
587 }
588 return NAME;
589}
590
Guido van Rossumc001c092020-04-30 12:12:19 -0700591static int
592growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
593 assert(initial_size > 0);
594 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
595 arr->size = initial_size;
596 arr->num_items = 0;
597
598 return arr->items != NULL;
599}
600
601static int
602growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
603 if (arr->num_items >= arr->size) {
604 size_t new_size = arr->size * 2;
605 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
606 if (!new_items_array) {
607 return 0;
608 }
609 arr->items = new_items_array;
610 arr->size = new_size;
611 }
612
613 arr->items[arr->num_items].lineno = lineno;
614 arr->items[arr->num_items].comment = comment; // Take ownership
615 arr->num_items++;
616 return 1;
617}
618
619static void
620growable_comment_array_deallocate(growable_comment_array *arr) {
621 for (unsigned i = 0; i < arr->num_items; i++) {
622 PyMem_Free(arr->items[i].comment);
623 }
624 PyMem_Free(arr->items);
625}
626
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100627int
628_PyPegen_fill_token(Parser *p)
629{
Pablo Galindofb61c422020-06-15 14:23:43 +0100630 const char *start;
631 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100632 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700633
634 // Record and skip '# type: ignore' comments
635 while (type == TYPE_IGNORE) {
636 Py_ssize_t len = end - start;
637 char *tag = PyMem_Malloc(len + 1);
638 if (tag == NULL) {
639 PyErr_NoMemory();
640 return -1;
641 }
642 strncpy(tag, start, len);
643 tag[len] = '\0';
644 // Ownership of tag passes to the growable array
645 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
646 PyErr_NoMemory();
647 return -1;
648 }
649 type = PyTokenizer_Get(p->tok, &start, &end);
650 }
651
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100652 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
653 type = NEWLINE; /* Add an extra newline */
654 p->parsing_started = 0;
655
Pablo Galindob94dbd72020-04-27 18:35:58 +0100656 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100657 p->tok->pendin = -p->tok->indent;
658 p->tok->indent = 0;
659 }
660 }
661 else {
662 p->parsing_started = 1;
663 }
664
665 if (p->fill == p->size) {
666 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300667 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
668 if (new_tokens == NULL) {
669 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100670 return -1;
671 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100672 p->tokens = new_tokens;
673
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100674 for (int i = p->size; i < newsize; i++) {
675 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300676 if (p->tokens[i] == NULL) {
677 p->size = i; // Needed, in order to cleanup correctly after parser fails
678 PyErr_NoMemory();
679 return -1;
680 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100681 memset(p->tokens[i], '\0', sizeof(Token));
682 }
683 p->size = newsize;
684 }
685
686 Token *t = p->tokens[p->fill];
687 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
688 t->bytes = PyBytes_FromStringAndSize(start, end - start);
689 if (t->bytes == NULL) {
690 return -1;
691 }
692 PyArena_AddPyObject(p->arena, t->bytes);
693
694 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
695 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100696 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100697 int col_offset = -1;
698 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100699 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100700 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100701 }
702 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100703 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100704 }
705
706 t->lineno = p->starting_lineno + lineno;
707 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
708 t->end_lineno = p->starting_lineno + end_lineno;
709 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
710
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100711 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300712
713 if (type == ERRORTOKEN) {
714 if (p->tok->done == E_DECODE) {
715 return raise_decode_error(p);
716 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100717 return tokenizer_error(p);
718
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300719 }
720
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100721 return 0;
722}
723
724// Instrumentation to count the effectiveness of memoization.
725// The array counts the number of tokens skipped by memoization,
726// indexed by type.
727
728#define NSTATISTICS 2000
729static long memo_statistics[NSTATISTICS];
730
731void
732_PyPegen_clear_memo_statistics()
733{
734 for (int i = 0; i < NSTATISTICS; i++) {
735 memo_statistics[i] = 0;
736 }
737}
738
739PyObject *
740_PyPegen_get_memo_statistics()
741{
742 PyObject *ret = PyList_New(NSTATISTICS);
743 if (ret == NULL) {
744 return NULL;
745 }
746 for (int i = 0; i < NSTATISTICS; i++) {
747 PyObject *value = PyLong_FromLong(memo_statistics[i]);
748 if (value == NULL) {
749 Py_DECREF(ret);
750 return NULL;
751 }
752 // PyList_SetItem borrows a reference to value.
753 if (PyList_SetItem(ret, i, value) < 0) {
754 Py_DECREF(ret);
755 return NULL;
756 }
757 }
758 return ret;
759}
760
761int // bool
762_PyPegen_is_memoized(Parser *p, int type, void *pres)
763{
764 if (p->mark == p->fill) {
765 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300766 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100767 return -1;
768 }
769 }
770
771 Token *t = p->tokens[p->mark];
772
773 for (Memo *m = t->memo; m != NULL; m = m->next) {
774 if (m->type == type) {
775 if (0 <= type && type < NSTATISTICS) {
776 long count = m->mark - p->mark;
777 // A memoized negative result counts for one.
778 if (count <= 0) {
779 count = 1;
780 }
781 memo_statistics[type] += count;
782 }
783 p->mark = m->mark;
784 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100785 return 1;
786 }
787 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100788 return 0;
789}
790
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100791
792int
793_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
794{
795 int mark = p->mark;
796 void *res = func(p);
797 p->mark = mark;
798 return (res != NULL) == positive;
799}
800
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100801int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100802_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
803{
804 int mark = p->mark;
805 void *res = func(p, arg);
806 p->mark = mark;
807 return (res != NULL) == positive;
808}
809
810int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100811_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
812{
813 int mark = p->mark;
814 void *res = func(p, arg);
815 p->mark = mark;
816 return (res != NULL) == positive;
817}
818
819int
820_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
821{
822 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100823 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100824 p->mark = mark;
825 return (res != NULL) == positive;
826}
827
828Token *
829_PyPegen_expect_token(Parser *p, int type)
830{
831 if (p->mark == p->fill) {
832 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300833 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100834 return NULL;
835 }
836 }
837 Token *t = p->tokens[p->mark];
838 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100839 return NULL;
840 }
841 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100842 return t;
843}
844
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700845expr_ty
846_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
847{
848 if (p->mark == p->fill) {
849 if (_PyPegen_fill_token(p) < 0) {
850 p->error_indicator = 1;
851 return NULL;
852 }
853 }
854 Token *t = p->tokens[p->mark];
855 if (t->type != NAME) {
856 return NULL;
857 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300858 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700859 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300860 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700861 return NULL;
862 }
863 if (strcmp(s, keyword) != 0) {
864 return NULL;
865 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300866 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700867}
868
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100869Token *
870_PyPegen_get_last_nonnwhitespace_token(Parser *p)
871{
872 assert(p->mark >= 0);
873 Token *token = NULL;
874 for (int m = p->mark - 1; m >= 0; m--) {
875 token = p->tokens[m];
876 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
877 break;
878 }
879 }
880 return token;
881}
882
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100883expr_ty
884_PyPegen_name_token(Parser *p)
885{
886 Token *t = _PyPegen_expect_token(p, NAME);
887 if (t == NULL) {
888 return NULL;
889 }
890 char* s = PyBytes_AsString(t->bytes);
891 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300892 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100893 return NULL;
894 }
895 PyObject *id = _PyPegen_new_identifier(p, s);
896 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300897 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100898 return NULL;
899 }
900 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
901 p->arena);
902}
903
904void *
905_PyPegen_string_token(Parser *p)
906{
907 return _PyPegen_expect_token(p, STRING);
908}
909
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100910static PyObject *
911parsenumber_raw(const char *s)
912{
913 const char *end;
914 long x;
915 double dx;
916 Py_complex compl;
917 int imflag;
918
919 assert(s != NULL);
920 errno = 0;
921 end = s + strlen(s) - 1;
922 imflag = *end == 'j' || *end == 'J';
923 if (s[0] == '0') {
924 x = (long)PyOS_strtoul(s, (char **)&end, 0);
925 if (x < 0 && errno == 0) {
926 return PyLong_FromString(s, (char **)0, 0);
927 }
928 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100929 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100930 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100931 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100932 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100933 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100934 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100935 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100936 return PyLong_FromLong(x);
937 }
938 /* XXX Huge floats may silently fail */
939 if (imflag) {
940 compl.real = 0.;
941 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100942 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100943 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100944 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100945 return PyComplex_FromCComplex(compl);
946 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100947 dx = PyOS_string_to_double(s, NULL, NULL);
948 if (dx == -1.0 && PyErr_Occurred()) {
949 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100950 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100951 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100952}
953
954static PyObject *
955parsenumber(const char *s)
956{
Pablo Galindofb61c422020-06-15 14:23:43 +0100957 char *dup;
958 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100959 PyObject *res = NULL;
960
961 assert(s != NULL);
962
963 if (strchr(s, '_') == NULL) {
964 return parsenumber_raw(s);
965 }
966 /* Create a duplicate without underscores. */
967 dup = PyMem_Malloc(strlen(s) + 1);
968 if (dup == NULL) {
969 return PyErr_NoMemory();
970 }
971 end = dup;
972 for (; *s; s++) {
973 if (*s != '_') {
974 *end++ = *s;
975 }
976 }
977 *end = '\0';
978 res = parsenumber_raw(dup);
979 PyMem_Free(dup);
980 return res;
981}
982
983expr_ty
984_PyPegen_number_token(Parser *p)
985{
986 Token *t = _PyPegen_expect_token(p, NUMBER);
987 if (t == NULL) {
988 return NULL;
989 }
990
991 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100992 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300993 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100994 return NULL;
995 }
996
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300997 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
998 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700999 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001000 "in Python 3.6 and greater");
1001 }
1002
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001003 PyObject *c = parsenumber(num_raw);
1004
1005 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001006 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001007 return NULL;
1008 }
1009
1010 if (PyArena_AddPyObject(p->arena, c) < 0) {
1011 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +03001012 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001013 return NULL;
1014 }
1015
1016 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
1017 p->arena);
1018}
1019
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001020static int // bool
1021newline_in_string(Parser *p, const char *cur)
1022{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001023 for (const char *c = cur; c >= p->tok->buf; c--) {
1024 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001025 return 1;
1026 }
1027 }
1028 return 0;
1029}
1030
1031/* Check that the source for a single input statement really is a single
1032 statement by looking at what is left in the buffer after parsing.
1033 Trailing whitespace and comments are OK. */
1034static int // bool
1035bad_single_statement(Parser *p)
1036{
1037 const char *cur = strchr(p->tok->buf, '\n');
1038
1039 /* Newlines are allowed if preceded by a line continuation character
1040 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001041 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1042 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001043 return 0;
1044 }
1045 char c = *cur;
1046
1047 for (;;) {
1048 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1049 c = *++cur;
1050 }
1051
1052 if (!c) {
1053 return 0;
1054 }
1055
1056 if (c != '#') {
1057 return 1;
1058 }
1059
1060 /* Suck up comment. */
1061 while (c && c != '\n') {
1062 c = *++cur;
1063 }
1064 }
1065}
1066
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001067void
1068_PyPegen_Parser_Free(Parser *p)
1069{
1070 Py_XDECREF(p->normalize);
1071 for (int i = 0; i < p->size; i++) {
1072 PyMem_Free(p->tokens[i]);
1073 }
1074 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001075 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001076 PyMem_Free(p);
1077}
1078
Pablo Galindo2b74c832020-04-27 18:02:07 +01001079static int
1080compute_parser_flags(PyCompilerFlags *flags)
1081{
1082 int parser_flags = 0;
1083 if (!flags) {
1084 return 0;
1085 }
1086 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1087 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1088 }
1089 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1090 parser_flags |= PyPARSE_IGNORE_COOKIE;
1091 }
1092 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1093 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1094 }
1095 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1096 parser_flags |= PyPARSE_TYPE_COMMENTS;
1097 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001098 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001099 parser_flags |= PyPARSE_ASYNC_HACKS;
1100 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001101 return parser_flags;
1102}
1103
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001104Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001105_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001106 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001107{
1108 Parser *p = PyMem_Malloc(sizeof(Parser));
1109 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001110 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001111 }
1112 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001113 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1114 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001115 p->tok = tok;
1116 p->keywords = NULL;
1117 p->n_keyword_lists = -1;
1118 p->tokens = PyMem_Malloc(sizeof(Token *));
1119 if (!p->tokens) {
1120 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001121 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001122 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001123 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001124 if (!p->tokens) {
1125 PyMem_Free(p->tokens);
1126 PyMem_Free(p);
1127 return (Parser *) PyErr_NoMemory();
1128 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001129 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1130 PyMem_Free(p->tokens[0]);
1131 PyMem_Free(p->tokens);
1132 PyMem_Free(p);
1133 return (Parser *) PyErr_NoMemory();
1134 }
1135
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001136 p->mark = 0;
1137 p->fill = 0;
1138 p->size = 1;
1139
1140 p->errcode = errcode;
1141 p->arena = arena;
1142 p->start_rule = start_rule;
1143 p->parsing_started = 0;
1144 p->normalize = NULL;
1145 p->error_indicator = 0;
1146
1147 p->starting_lineno = 0;
1148 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001149 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001150 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001151 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001152 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001153 p->call_invalid_rules = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001154
1155 return p;
1156}
1157
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001158static void
1159reset_parser_state(Parser *p)
1160{
1161 for (int i = 0; i < p->fill; i++) {
1162 p->tokens[i]->memo = NULL;
1163 }
1164 p->mark = 0;
1165 p->call_invalid_rules = 1;
1166}
1167
Pablo Galindod6d63712021-01-19 23:59:33 +00001168static int
1169_PyPegen_check_tokenizer_errors(Parser *p) {
1170 // Tokenize the whole input to see if there are any tokenization
1171 // errors such as mistmatching parentheses. These will get priority
1172 // over generic syntax errors only if the line number of the error is
1173 // before the one that we had for the generic error.
1174
1175 // We don't want to tokenize to the end for interactive input
1176 if (p->tok->prompt != NULL) {
1177 return 0;
1178 }
1179
1180
1181 Token *current_token = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
1182 Py_ssize_t current_err_line = current_token->lineno;
1183
1184 // Save the tokenizer state to restore them later in case we found nothing
1185 struct tok_state saved_tok;
1186 memcpy(&saved_tok, p->tok, sizeof(struct tok_state));
1187
1188 for (;;) {
1189 const char *start;
1190 const char *end;
1191 switch (PyTokenizer_Get(p->tok, &start, &end)) {
1192 case ERRORTOKEN:
1193 if (p->tok->level != 0) {
1194 int error_lineno = p->tok->parenlinenostack[p->tok->level-1];
1195 if (current_err_line > error_lineno) {
1196 raise_unclosed_parentheses_error(p);
1197 return -1;
1198 }
1199 }
1200 break;
1201 case ENDMARKER:
1202 break;
1203 default:
1204 continue;
1205 }
1206 break;
1207 }
1208
1209 // Restore the tokenizer state
1210 memcpy(p->tok, &saved_tok, sizeof(struct tok_state));
1211 return 0;
1212}
1213
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001214void *
1215_PyPegen_run_parser(Parser *p)
1216{
1217 void *res = _PyPegen_parse(p);
1218 if (res == NULL) {
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001219 reset_parser_state(p);
1220 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001221 if (PyErr_Occurred()) {
1222 return NULL;
1223 }
1224 if (p->fill == 0) {
1225 RAISE_SYNTAX_ERROR("error at start before reading any input");
1226 }
Pablo Galindod6d63712021-01-19 23:59:33 +00001227 else if (p->tok->done == E_EOF) {
1228 if (p->tok->level) {
1229 raise_unclosed_parentheses_error(p);
1230 } else {
1231 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1232 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001233 }
1234 else {
1235 if (p->tokens[p->fill-1]->type == INDENT) {
1236 RAISE_INDENTATION_ERROR("unexpected indent");
1237 }
1238 else if (p->tokens[p->fill-1]->type == DEDENT) {
1239 RAISE_INDENTATION_ERROR("unexpected unindent");
1240 }
1241 else {
Pablo Galindod6d63712021-01-19 23:59:33 +00001242 if (_PyPegen_check_tokenizer_errors(p)) {
1243 return NULL;
1244 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001245 RAISE_SYNTAX_ERROR("invalid syntax");
1246 }
1247 }
1248 return NULL;
1249 }
1250
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001251 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1252 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1253 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1254 }
1255
Pablo Galindo13322262020-07-27 23:46:59 +01001256#if defined(Py_DEBUG) && defined(Py_BUILD_CORE)
1257 if (p->start_rule == Py_single_input ||
1258 p->start_rule == Py_file_input ||
1259 p->start_rule == Py_eval_input)
1260 {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001261 if (!PyAST_Validate(res)) {
1262 return NULL;
1263 }
Pablo Galindo13322262020-07-27 23:46:59 +01001264 }
1265#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001266 return res;
1267}
1268
1269mod_ty
1270_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1271 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001272 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001273{
1274 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1275 if (tok == NULL) {
1276 if (PyErr_Occurred()) {
1277 raise_tokenizer_init_error(filename_ob);
1278 return NULL;
1279 }
1280 return NULL;
1281 }
1282 // This transfers the ownership to the tokenizer
1283 tok->filename = filename_ob;
1284 Py_INCREF(filename_ob);
1285
1286 // From here on we need to clean up even if there's an error
1287 mod_ty result = NULL;
1288
Pablo Galindo2b74c832020-04-27 18:02:07 +01001289 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001290 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1291 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001292 if (p == NULL) {
1293 goto error;
1294 }
1295
1296 result = _PyPegen_run_parser(p);
1297 _PyPegen_Parser_Free(p);
1298
1299error:
1300 PyTokenizer_Free(tok);
1301 return result;
1302}
1303
1304mod_ty
1305_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001306 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001307{
1308 FILE *fp = fopen(filename, "rb");
1309 if (fp == NULL) {
1310 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1311 return NULL;
1312 }
1313
1314 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001315 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001316
1317 fclose(fp);
1318 return result;
1319}
1320
1321mod_ty
1322_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001323 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001324{
1325 int exec_input = start_rule == Py_file_input;
1326
1327 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001328 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001329 tok = PyTokenizer_FromUTF8(str, exec_input);
1330 } else {
1331 tok = PyTokenizer_FromString(str, exec_input);
1332 }
1333 if (tok == NULL) {
1334 if (PyErr_Occurred()) {
1335 raise_tokenizer_init_error(filename_ob);
1336 }
1337 return NULL;
1338 }
1339 // This transfers the ownership to the tokenizer
1340 tok->filename = filename_ob;
1341 Py_INCREF(filename_ob);
1342
1343 // We need to clear up from here on
1344 mod_ty result = NULL;
1345
Pablo Galindo2b74c832020-04-27 18:02:07 +01001346 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001347 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1348 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001349 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1350 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001351 if (p == NULL) {
1352 goto error;
1353 }
1354
1355 result = _PyPegen_run_parser(p);
1356 _PyPegen_Parser_Free(p);
1357
1358error:
1359 PyTokenizer_Free(tok);
1360 return result;
1361}
1362
Pablo Galindoa5634c42020-09-16 19:42:00 +01001363asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001364_PyPegen_interactive_exit(Parser *p)
1365{
1366 if (p->errcode) {
1367 *(p->errcode) = E_EOF;
1368 }
1369 return NULL;
1370}
1371
1372/* Creates a single-element asdl_seq* that contains a */
1373asdl_seq *
1374_PyPegen_singleton_seq(Parser *p, void *a)
1375{
1376 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001377 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001378 if (!seq) {
1379 return NULL;
1380 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001381 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001382 return seq;
1383}
1384
1385/* Creates a copy of seq and prepends a to it */
1386asdl_seq *
1387_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1388{
1389 assert(a != NULL);
1390 if (!seq) {
1391 return _PyPegen_singleton_seq(p, a);
1392 }
1393
Pablo Galindoa5634c42020-09-16 19:42:00 +01001394 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 +01001395 if (!new_seq) {
1396 return NULL;
1397 }
1398
Pablo Galindoa5634c42020-09-16 19:42:00 +01001399 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001400 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001401 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001402 }
1403 return new_seq;
1404}
1405
Guido van Rossumc001c092020-04-30 12:12:19 -07001406/* Creates a copy of seq and appends a to it */
1407asdl_seq *
1408_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1409{
1410 assert(a != NULL);
1411 if (!seq) {
1412 return _PyPegen_singleton_seq(p, a);
1413 }
1414
Pablo Galindoa5634c42020-09-16 19:42:00 +01001415 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 -07001416 if (!new_seq) {
1417 return NULL;
1418 }
1419
1420 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001421 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001422 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001423 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001424 return new_seq;
1425}
1426
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001427static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001428_get_flattened_seq_size(asdl_seq *seqs)
1429{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001430 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001431 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001432 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001433 size += asdl_seq_LEN(inner_seq);
1434 }
1435 return size;
1436}
1437
1438/* Flattens an asdl_seq* of asdl_seq*s */
1439asdl_seq *
1440_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1441{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001442 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001443 assert(flattened_seq_size > 0);
1444
Pablo Galindoa5634c42020-09-16 19:42:00 +01001445 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001446 if (!flattened_seq) {
1447 return NULL;
1448 }
1449
1450 int flattened_seq_idx = 0;
1451 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001452 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001453 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001454 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001455 }
1456 }
1457 assert(flattened_seq_idx == flattened_seq_size);
1458
1459 return flattened_seq;
1460}
1461
1462/* Creates a new name of the form <first_name>.<second_name> */
1463expr_ty
1464_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1465{
1466 assert(first_name != NULL && second_name != NULL);
1467 PyObject *first_identifier = first_name->v.Name.id;
1468 PyObject *second_identifier = second_name->v.Name.id;
1469
1470 if (PyUnicode_READY(first_identifier) == -1) {
1471 return NULL;
1472 }
1473 if (PyUnicode_READY(second_identifier) == -1) {
1474 return NULL;
1475 }
1476 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1477 if (!first_str) {
1478 return NULL;
1479 }
1480 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1481 if (!second_str) {
1482 return NULL;
1483 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001484 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001485
1486 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1487 if (!str) {
1488 return NULL;
1489 }
1490
1491 char *s = PyBytes_AS_STRING(str);
1492 if (!s) {
1493 return NULL;
1494 }
1495
1496 strcpy(s, first_str);
1497 s += strlen(first_str);
1498 *s++ = '.';
1499 strcpy(s, second_str);
1500 s += strlen(second_str);
1501 *s = '\0';
1502
1503 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1504 Py_DECREF(str);
1505 if (!uni) {
1506 return NULL;
1507 }
1508 PyUnicode_InternInPlace(&uni);
1509 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1510 Py_DECREF(uni);
1511 return NULL;
1512 }
1513
1514 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1515}
1516
1517/* Counts the total number of dots in seq's tokens */
1518int
1519_PyPegen_seq_count_dots(asdl_seq *seq)
1520{
1521 int number_of_dots = 0;
1522 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001523 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001524 switch (current_expr->type) {
1525 case ELLIPSIS:
1526 number_of_dots += 3;
1527 break;
1528 case DOT:
1529 number_of_dots += 1;
1530 break;
1531 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001532 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001533 }
1534 }
1535
1536 return number_of_dots;
1537}
1538
1539/* Creates an alias with '*' as the identifier name */
1540alias_ty
1541_PyPegen_alias_for_star(Parser *p)
1542{
1543 PyObject *str = PyUnicode_InternFromString("*");
1544 if (!str) {
1545 return NULL;
1546 }
1547 if (PyArena_AddPyObject(p->arena, str) < 0) {
1548 Py_DECREF(str);
1549 return NULL;
1550 }
1551 return alias(str, NULL, p->arena);
1552}
1553
1554/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001555asdl_identifier_seq *
1556_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001557{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001558 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001559 assert(len > 0);
1560
Pablo Galindoa5634c42020-09-16 19:42:00 +01001561 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001562 if (!new_seq) {
1563 return NULL;
1564 }
1565 for (Py_ssize_t i = 0; i < len; i++) {
1566 expr_ty e = asdl_seq_GET(seq, i);
1567 asdl_seq_SET(new_seq, i, e->v.Name.id);
1568 }
1569 return new_seq;
1570}
1571
1572/* Constructs a CmpopExprPair */
1573CmpopExprPair *
1574_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1575{
1576 assert(expr != NULL);
1577 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1578 if (!a) {
1579 return NULL;
1580 }
1581 a->cmpop = cmpop;
1582 a->expr = expr;
1583 return a;
1584}
1585
1586asdl_int_seq *
1587_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1588{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001589 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001590 assert(len > 0);
1591
1592 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1593 if (!new_seq) {
1594 return NULL;
1595 }
1596 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001597 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001598 asdl_seq_SET(new_seq, i, pair->cmpop);
1599 }
1600 return new_seq;
1601}
1602
Pablo Galindoa5634c42020-09-16 19:42:00 +01001603asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001604_PyPegen_get_exprs(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
Pablo Galindoa5634c42020-09-16 19:42:00 +01001609 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001610 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->expr);
1616 }
1617 return new_seq;
1618}
1619
1620/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001621static asdl_expr_seq *
1622_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001623{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001624 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001625 if (len == 0) {
1626 return NULL;
1627 }
1628
Pablo Galindoa5634c42020-09-16 19:42:00 +01001629 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001630 if (!new_seq) {
1631 return NULL;
1632 }
1633 for (Py_ssize_t i = 0; i < len; i++) {
1634 expr_ty e = asdl_seq_GET(seq, i);
1635 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1636 }
1637 return new_seq;
1638}
1639
1640static expr_ty
1641_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1642{
1643 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1644}
1645
1646static expr_ty
1647_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1648{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001649 return _Py_Tuple(
1650 _set_seq_context(p, e->v.Tuple.elts, ctx),
1651 ctx,
1652 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001653}
1654
1655static expr_ty
1656_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1657{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001658 return _Py_List(
1659 _set_seq_context(p, e->v.List.elts, ctx),
1660 ctx,
1661 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001662}
1663
1664static expr_ty
1665_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1666{
1667 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1668}
1669
1670static expr_ty
1671_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1672{
1673 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1674}
1675
1676static expr_ty
1677_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1678{
1679 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1680}
1681
1682/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1683expr_ty
1684_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1685{
1686 assert(expr != NULL);
1687
1688 expr_ty new = NULL;
1689 switch (expr->kind) {
1690 case Name_kind:
1691 new = _set_name_context(p, expr, ctx);
1692 break;
1693 case Tuple_kind:
1694 new = _set_tuple_context(p, expr, ctx);
1695 break;
1696 case List_kind:
1697 new = _set_list_context(p, expr, ctx);
1698 break;
1699 case Subscript_kind:
1700 new = _set_subscript_context(p, expr, ctx);
1701 break;
1702 case Attribute_kind:
1703 new = _set_attribute_context(p, expr, ctx);
1704 break;
1705 case Starred_kind:
1706 new = _set_starred_context(p, expr, ctx);
1707 break;
1708 default:
1709 new = expr;
1710 }
1711 return new;
1712}
1713
1714/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1715KeyValuePair *
1716_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1717{
1718 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1719 if (!a) {
1720 return NULL;
1721 }
1722 a->key = key;
1723 a->value = value;
1724 return a;
1725}
1726
1727/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001728asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001729_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1730{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001731 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001732 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001733 if (!new_seq) {
1734 return NULL;
1735 }
1736 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001737 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001738 asdl_seq_SET(new_seq, i, pair->key);
1739 }
1740 return new_seq;
1741}
1742
1743/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001744asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001745_PyPegen_get_values(Parser *p, asdl_seq *seq)
1746{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001747 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001748 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001749 if (!new_seq) {
1750 return NULL;
1751 }
1752 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001753 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001754 asdl_seq_SET(new_seq, i, pair->value);
1755 }
1756 return new_seq;
1757}
1758
1759/* Constructs a NameDefaultPair */
1760NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001761_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001762{
1763 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1764 if (!a) {
1765 return NULL;
1766 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001767 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001768 a->value = value;
1769 return a;
1770}
1771
1772/* Constructs a SlashWithDefault */
1773SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001774_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001775{
1776 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1777 if (!a) {
1778 return NULL;
1779 }
1780 a->plain_names = plain_names;
1781 a->names_with_defaults = names_with_defaults;
1782 return a;
1783}
1784
1785/* Constructs a StarEtc */
1786StarEtc *
1787_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1788{
1789 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1790 if (!a) {
1791 return NULL;
1792 }
1793 a->vararg = vararg;
1794 a->kwonlyargs = kwonlyargs;
1795 a->kwarg = kwarg;
1796 return a;
1797}
1798
1799asdl_seq *
1800_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1801{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001802 Py_ssize_t first_len = asdl_seq_LEN(a);
1803 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001804 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001805 if (!new_seq) {
1806 return NULL;
1807 }
1808
1809 int k = 0;
1810 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001811 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001812 }
1813 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001814 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001815 }
1816
1817 return new_seq;
1818}
1819
Pablo Galindoa5634c42020-09-16 19:42:00 +01001820static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001821_get_names(Parser *p, asdl_seq *names_with_defaults)
1822{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001823 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001824 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001825 if (!seq) {
1826 return NULL;
1827 }
1828 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001829 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001830 asdl_seq_SET(seq, i, pair->arg);
1831 }
1832 return seq;
1833}
1834
Pablo Galindoa5634c42020-09-16 19:42:00 +01001835static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001836_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1837{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001838 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001839 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001840 if (!seq) {
1841 return NULL;
1842 }
1843 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001844 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001845 asdl_seq_SET(seq, i, pair->value);
1846 }
1847 return seq;
1848}
1849
1850/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1851arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001852_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
1853 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001854 asdl_seq *names_with_default, StarEtc *star_etc)
1855{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001856 asdl_arg_seq *posonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001857 if (slash_without_default != NULL) {
1858 posonlyargs = slash_without_default;
1859 }
1860 else if (slash_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001861 asdl_arg_seq *slash_with_default_names =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001862 _get_names(p, slash_with_default->names_with_defaults);
1863 if (!slash_with_default_names) {
1864 return NULL;
1865 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001866 posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1867 p,
1868 (asdl_seq*)slash_with_default->plain_names,
1869 (asdl_seq*)slash_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001870 if (!posonlyargs) {
1871 return NULL;
1872 }
1873 }
1874 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001875 posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001876 if (!posonlyargs) {
1877 return NULL;
1878 }
1879 }
1880
Pablo Galindoa5634c42020-09-16 19:42:00 +01001881 asdl_arg_seq *posargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001882 if (plain_names != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001883 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001884 if (!names_with_default_names) {
1885 return NULL;
1886 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001887 posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1888 p,
1889 (asdl_seq*)plain_names,
1890 (asdl_seq*)names_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001891 if (!posargs) {
1892 return NULL;
1893 }
1894 }
1895 else if (plain_names == NULL && names_with_default != NULL) {
1896 posargs = _get_names(p, names_with_default);
1897 if (!posargs) {
1898 return NULL;
1899 }
1900 }
1901 else if (plain_names != NULL && names_with_default == NULL) {
1902 posargs = plain_names;
1903 }
1904 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001905 posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001906 if (!posargs) {
1907 return NULL;
1908 }
1909 }
1910
Pablo Galindoa5634c42020-09-16 19:42:00 +01001911 asdl_expr_seq *posdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001912 if (slash_with_default != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001913 asdl_expr_seq *slash_with_default_values =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001914 _get_defaults(p, slash_with_default->names_with_defaults);
1915 if (!slash_with_default_values) {
1916 return NULL;
1917 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001918 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001919 if (!names_with_default_values) {
1920 return NULL;
1921 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001922 posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
1923 p,
1924 (asdl_seq*)slash_with_default_values,
1925 (asdl_seq*)names_with_default_values);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001926 if (!posdefaults) {
1927 return NULL;
1928 }
1929 }
1930 else if (slash_with_default == NULL && names_with_default != NULL) {
1931 posdefaults = _get_defaults(p, names_with_default);
1932 if (!posdefaults) {
1933 return NULL;
1934 }
1935 }
1936 else if (slash_with_default != NULL && names_with_default == NULL) {
1937 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1938 if (!posdefaults) {
1939 return NULL;
1940 }
1941 }
1942 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001943 posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001944 if (!posdefaults) {
1945 return NULL;
1946 }
1947 }
1948
1949 arg_ty vararg = NULL;
1950 if (star_etc != NULL && star_etc->vararg != NULL) {
1951 vararg = star_etc->vararg;
1952 }
1953
Pablo Galindoa5634c42020-09-16 19:42:00 +01001954 asdl_arg_seq *kwonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001955 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1956 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1957 if (!kwonlyargs) {
1958 return NULL;
1959 }
1960 }
1961 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001962 kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001963 if (!kwonlyargs) {
1964 return NULL;
1965 }
1966 }
1967
Pablo Galindoa5634c42020-09-16 19:42:00 +01001968 asdl_expr_seq *kwdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001969 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1970 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1971 if (!kwdefaults) {
1972 return NULL;
1973 }
1974 }
1975 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001976 kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001977 if (!kwdefaults) {
1978 return NULL;
1979 }
1980 }
1981
1982 arg_ty kwarg = NULL;
1983 if (star_etc != NULL && star_etc->kwarg != NULL) {
1984 kwarg = star_etc->kwarg;
1985 }
1986
1987 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1988 posdefaults, p->arena);
1989}
1990
1991/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1992 * arguments. */
1993arguments_ty
1994_PyPegen_empty_arguments(Parser *p)
1995{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001996 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001997 if (!posonlyargs) {
1998 return NULL;
1999 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002000 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002001 if (!posargs) {
2002 return NULL;
2003 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002004 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002005 if (!posdefaults) {
2006 return NULL;
2007 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002008 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002009 if (!kwonlyargs) {
2010 return NULL;
2011 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002012 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002013 if (!kwdefaults) {
2014 return NULL;
2015 }
2016
Batuhan Taskaya02a16032020-10-10 20:14:59 +03002017 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, posdefaults,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002018 p->arena);
2019}
2020
2021/* Encapsulates the value of an operator_ty into an AugOperator struct */
2022AugOperator *
2023_PyPegen_augoperator(Parser *p, operator_ty kind)
2024{
2025 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
2026 if (!a) {
2027 return NULL;
2028 }
2029 a->kind = kind;
2030 return a;
2031}
2032
2033/* Construct a FunctionDef equivalent to function_def, but with decorators */
2034stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002035_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002036{
2037 assert(function_def != NULL);
2038 if (function_def->kind == AsyncFunctionDef_kind) {
2039 return _Py_AsyncFunctionDef(
2040 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2041 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
2042 function_def->v.FunctionDef.type_comment, function_def->lineno,
2043 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
2044 p->arena);
2045 }
2046
2047 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
2048 function_def->v.FunctionDef.body, decorators,
2049 function_def->v.FunctionDef.returns,
2050 function_def->v.FunctionDef.type_comment, function_def->lineno,
2051 function_def->col_offset, function_def->end_lineno,
2052 function_def->end_col_offset, p->arena);
2053}
2054
2055/* Construct a ClassDef equivalent to class_def, but with decorators */
2056stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002057_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002058{
2059 assert(class_def != NULL);
2060 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
2061 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
2062 class_def->lineno, class_def->col_offset, class_def->end_lineno,
2063 class_def->end_col_offset, p->arena);
2064}
2065
2066/* Construct a KeywordOrStarred */
2067KeywordOrStarred *
2068_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2069{
2070 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
2071 if (!a) {
2072 return NULL;
2073 }
2074 a->element = element;
2075 a->is_keyword = is_keyword;
2076 return a;
2077}
2078
2079/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2080static int
2081_seq_number_of_starred_exprs(asdl_seq *seq)
2082{
2083 int n = 0;
2084 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002085 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002086 if (!k->is_keyword) {
2087 n++;
2088 }
2089 }
2090 return n;
2091}
2092
2093/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002094asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002095_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2096{
2097 int new_len = _seq_number_of_starred_exprs(kwargs);
2098 if (new_len == 0) {
2099 return NULL;
2100 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002101 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002102 if (!new_seq) {
2103 return NULL;
2104 }
2105
2106 int idx = 0;
2107 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002108 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002109 if (!k->is_keyword) {
2110 asdl_seq_SET(new_seq, idx++, k->element);
2111 }
2112 }
2113 return new_seq;
2114}
2115
2116/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002117asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002118_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2119{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002120 Py_ssize_t len = asdl_seq_LEN(kwargs);
2121 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002122 if (new_len == 0) {
2123 return NULL;
2124 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002125 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002126 if (!new_seq) {
2127 return NULL;
2128 }
2129
2130 int idx = 0;
2131 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002132 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002133 if (k->is_keyword) {
2134 asdl_seq_SET(new_seq, idx++, k->element);
2135 }
2136 }
2137 return new_seq;
2138}
2139
2140expr_ty
2141_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2142{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002143 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002144 assert(len > 0);
2145
Pablo Galindoa5634c42020-09-16 19:42:00 +01002146 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2147 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002148
2149 int bytesmode = 0;
2150 PyObject *bytes_str = NULL;
2151
2152 FstringParser state;
2153 _PyPegen_FstringParser_Init(&state);
2154
2155 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002156 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002157
2158 int this_bytesmode;
2159 int this_rawmode;
2160 PyObject *s;
2161 const char *fstr;
2162 Py_ssize_t fstrlen = -1;
2163
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002164 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002165 goto error;
2166 }
2167
2168 /* Check that we are not mixing bytes with unicode. */
2169 if (i != 0 && bytesmode != this_bytesmode) {
2170 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2171 Py_XDECREF(s);
2172 goto error;
2173 }
2174 bytesmode = this_bytesmode;
2175
2176 if (fstr != NULL) {
2177 assert(s == NULL && !bytesmode);
2178
2179 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2180 this_rawmode, 0, first, t, last);
2181 if (result < 0) {
2182 goto error;
2183 }
2184 }
2185 else {
2186 /* String or byte string. */
2187 assert(s != NULL && fstr == NULL);
2188 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2189
2190 if (bytesmode) {
2191 if (i == 0) {
2192 bytes_str = s;
2193 }
2194 else {
2195 PyBytes_ConcatAndDel(&bytes_str, s);
2196 if (!bytes_str) {
2197 goto error;
2198 }
2199 }
2200 }
2201 else {
2202 /* This is a regular string. Concatenate it. */
2203 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2204 goto error;
2205 }
2206 }
2207 }
2208 }
2209
2210 if (bytesmode) {
2211 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2212 goto error;
2213 }
2214 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2215 last->end_col_offset, p->arena);
2216 }
2217
2218 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2219
2220error:
2221 Py_XDECREF(bytes_str);
2222 _PyPegen_FstringParser_Dealloc(&state);
2223 if (PyErr_Occurred()) {
2224 raise_decode_error(p);
2225 }
2226 return NULL;
2227}
Guido van Rossumc001c092020-04-30 12:12:19 -07002228
2229mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002230_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2231 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002232 Py_ssize_t num = p->type_ignore_comments.num_items;
2233 if (num > 0) {
2234 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002235 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002236 if (type_ignores == NULL) {
2237 return NULL;
2238 }
2239 for (int i = 0; i < num; i++) {
2240 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2241 if (tag == NULL) {
2242 return NULL;
2243 }
2244 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2245 if (ti == NULL) {
2246 return NULL;
2247 }
2248 asdl_seq_SET(type_ignores, i, ti);
2249 }
2250 }
2251 return Module(a, type_ignores, p->arena);
2252}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002253
2254// Error reporting helpers
2255
2256expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002257_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002258{
2259 if (e == NULL) {
2260 return NULL;
2261 }
2262
2263#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2264 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2265 for (Py_ssize_t i = 0; i < len; i++) {\
2266 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002267 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002268 if (child != NULL) {\
2269 return child;\
2270 }\
2271 }\
2272 } while (0)
2273
2274 // We only need to visit List and Tuple nodes recursively as those
2275 // are the only ones that can contain valid names in targets when
2276 // they are parsed as expressions. Any other kind of expression
2277 // that is a container (like Sets or Dicts) is directly invalid and
2278 // we don't need to visit it recursively.
2279
2280 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002281 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002282 VISIT_CONTAINER(e, List);
2283 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002284 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002285 VISIT_CONTAINER(e, Tuple);
2286 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002287 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002288 if (targets_type == DEL_TARGETS) {
2289 return e;
2290 }
2291 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2292 case Compare_kind:
2293 // This is needed, because the `a in b` in `for a in b` gets parsed
2294 // as a comparison, and so we need to search the left side of the comparison
2295 // for invalid targets.
2296 if (targets_type == FOR_TARGETS) {
2297 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2298 if (cmpop == In) {
2299 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2300 }
2301 return NULL;
2302 }
2303 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002304 case Name_kind:
2305 case Subscript_kind:
2306 case Attribute_kind:
2307 return NULL;
2308 default:
2309 return e;
2310 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002311}
2312
2313void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2314 int kwarg_unpacking = 0;
2315 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2316 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2317 if (!keyword->arg) {
2318 kwarg_unpacking = 1;
2319 }
2320 }
2321
2322 const char *msg = NULL;
2323 if (kwarg_unpacking) {
2324 msg = "positional argument follows keyword argument unpacking";
2325 } else {
2326 msg = "positional argument follows keyword argument";
2327 }
2328
2329 return RAISE_SYNTAX_ERROR(msg);
2330}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002331
2332void *
2333_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2334{
2335 /* The rule that calls this function is 'args for_if_clauses'.
2336 For the input f(L, x for x in y), L and x are in args and
2337 the for is parsed as a for_if_clause. We have to check if
2338 len <= 1, so that input like dict((a, b) for a, b in x)
2339 gets successfully parsed and then we pass the last
2340 argument (x in the above example) as the location of the
2341 error */
2342 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2343 if (len <= 1) {
2344 return NULL;
2345 }
2346
2347 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2348 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2349 "Generator expression must be parenthesized"
2350 );
2351}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002352
2353
Pablo Galindoa5634c42020-09-16 19:42:00 +01002354expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002355 int lineno, int col_offset, int end_lineno,
2356 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002357 Py_ssize_t args_len = asdl_seq_LEN(a);
2358 Py_ssize_t total_len = args_len;
2359
2360 if (b == NULL) {
Pablo Galindo315a61f2020-09-03 15:29:32 +01002361 return _Py_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2362 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002363
2364 }
2365
Pablo Galindoa5634c42020-09-16 19:42:00 +01002366 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2367 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002368
2369 if (starreds) {
2370 total_len += asdl_seq_LEN(starreds);
2371 }
2372
Pablo Galindoa5634c42020-09-16 19:42:00 +01002373 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002374
2375 Py_ssize_t i = 0;
2376 for (i = 0; i < args_len; i++) {
2377 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2378 }
2379 for (; i < total_len; i++) {
2380 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2381 }
2382
Pablo Galindo315a61f2020-09-03 15:29:32 +01002383 return _Py_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2384 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002385}