blob: a6f97929255ac244a164d1a80a187f4600657b48 [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
268static void
269raise_tokenizer_init_error(PyObject *filename)
270{
271 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
272 || PyErr_ExceptionMatches(PyExc_ValueError)
273 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
274 return;
275 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300276 PyObject *errstr = NULL;
277 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100278 PyObject *type;
279 PyObject *value;
280 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100281 PyErr_Fetch(&type, &value, &tback);
282 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300283 if (!errstr) {
284 goto error;
285 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100286
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300287 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100288 if (!tmp) {
289 goto error;
290 }
291
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300292 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100293 Py_DECREF(tmp);
294 if (!value) {
295 goto error;
296 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300297 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100298
299error:
300 Py_XDECREF(type);
301 Py_XDECREF(value);
302 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300303 Py_XDECREF(errstr);
304 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100305}
306
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100307static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308tokenizer_error(Parser *p)
309{
310 if (PyErr_Occurred()) {
311 return -1;
312 }
313
314 const char *msg = NULL;
315 PyObject* errtype = PyExc_SyntaxError;
316 switch (p->tok->done) {
317 case E_TOKEN:
318 msg = "invalid token";
319 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300321 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
322 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100323 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300324 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
325 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300326 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300327 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
328 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100329 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300330 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
331 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332 case E_INTR:
333 if (!PyErr_Occurred()) {
334 PyErr_SetNone(PyExc_KeyboardInterrupt);
335 }
336 return -1;
337 case E_NOMEM:
338 PyErr_NoMemory();
339 return -1;
340 case E_TABSPACE:
341 errtype = PyExc_TabError;
342 msg = "inconsistent use of tabs and spaces in indentation";
343 break;
344 case E_TOODEEP:
345 errtype = PyExc_IndentationError;
346 msg = "too many levels of indentation";
347 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100348 case E_LINECONT:
349 msg = "unexpected character after line continuation character";
350 break;
351 default:
352 msg = "unknown parsing error";
353 }
354
355 PyErr_Format(errtype, msg);
356 // There is no reliable column information for this error
357 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
358
359 return -1;
360}
361
362void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300363_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
364{
365 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100366 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300367 if (t->col_offset == -1) {
368 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
369 intptr_t, int);
370 } else {
371 col_offset = t->col_offset + 1;
372 }
373
374 va_list va;
375 va_start(va, errmsg);
376 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
377 col_offset, errmsg, va);
378 va_end(va);
379
380 return NULL;
381}
382
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200383static PyObject *
384get_error_line(Parser *p, Py_ssize_t lineno)
385{
386 /* If p->tok->fp == NULL, then we're parsing from a string, which means that
387 the whole source is stored in p->tok->str. If not, then we're parsing
388 from the REPL, so the source lines of the current (multi-line) statement
389 are stored in p->tok->stdin_content */
390 assert(p->tok->fp == NULL || p->tok->fp == stdin);
391
392 char *cur_line = p->tok->fp == NULL ? p->tok->str : p->tok->stdin_content;
393 for (int i = 0; i < lineno - 1; i++) {
394 cur_line = strchr(cur_line, '\n') + 1;
395 }
396
397 char *next_newline;
398 if ((next_newline = strchr(cur_line, '\n')) == NULL) { // This is the last line
399 next_newline = cur_line + strlen(cur_line);
400 }
401 return PyUnicode_DecodeUTF8(cur_line, next_newline - cur_line, "replace");
402}
403
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300404void *
405_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100406 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300407 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100408{
409 PyObject *value = NULL;
410 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300411 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100412 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300413 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100414
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300415 if (p->start_rule == Py_fstring_input) {
416 const char *fstring_msg = "f-string: ";
417 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
418
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300419 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300420 if (!new_errmsg) {
421 return (void *) PyErr_NoMemory();
422 }
423
424 // Copy both strings into new buffer
425 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
426 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
427 new_errmsg[len] = 0;
428 errmsg = new_errmsg;
429 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100430 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100431 if (!errstr) {
432 goto error;
433 }
434
435 if (p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300436 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100437 }
438
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300439 if (!error_line) {
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200440 /* PyErr_ProgramTextObject was not called or returned NULL. If it was not called,
441 then we need to find the error line from some other source, because
442 p->start_rule != Py_file_input. If it returned NULL, then it either unexpectedly
443 failed or we're parsing from a string or the REPL. There's a third edge case where
444 we're actually parsing from a file, which has an E_EOF SyntaxError and in that case
445 `PyErr_ProgramTextObject` fails because lineno points to last_file_line + 1, which
446 does not physically exist */
447 assert(p->tok->fp == NULL || p->tok->fp == stdin || p->tok->done == E_EOF);
448
449 if (p->tok->lineno == lineno) {
450 Py_ssize_t size = p->tok->inp - p->tok->buf;
451 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
452 }
453 else {
454 error_line = get_error_line(p, lineno);
455 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300456 if (!error_line) {
457 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300458 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100459 }
460
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300461 if (p->start_rule == Py_fstring_input) {
462 col_offset -= p->starting_col_offset;
463 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100464 Py_ssize_t col_number = col_offset;
465
466 if (p->tok->encoding != NULL) {
467 col_number = byte_offset_to_character_offset(error_line, col_offset);
468 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300469
470 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100471 if (!tmp) {
472 goto error;
473 }
474 value = PyTuple_Pack(2, errstr, tmp);
475 Py_DECREF(tmp);
476 if (!value) {
477 goto error;
478 }
479 PyErr_SetObject(errtype, value);
480
481 Py_DECREF(errstr);
482 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300483 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300484 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300485 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100486 return NULL;
487
488error:
489 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300490 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300491 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300492 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300493 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100494 return NULL;
495}
496
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100497#if 0
498static const char *
499token_name(int type)
500{
501 if (0 <= type && type <= N_TOKENS) {
502 return _PyParser_TokenNames[type];
503 }
504 return "<Huh?>";
505}
506#endif
507
508// Here, mark is the start of the node, while p->mark is the end.
509// If node==NULL, they should be the same.
510int
511_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
512{
513 // Insert in front
514 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
515 if (m == NULL) {
516 return -1;
517 }
518 m->type = type;
519 m->node = node;
520 m->mark = p->mark;
521 m->next = p->tokens[mark]->memo;
522 p->tokens[mark]->memo = m;
523 return 0;
524}
525
526// Like _PyPegen_insert_memo(), but updates an existing node if found.
527int
528_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
529{
530 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
531 if (m->type == type) {
532 // Update existing node.
533 m->node = node;
534 m->mark = p->mark;
535 return 0;
536 }
537 }
538 // Insert new node.
539 return _PyPegen_insert_memo(p, mark, type, node);
540}
541
542// Return dummy NAME.
543void *
544_PyPegen_dummy_name(Parser *p, ...)
545{
546 static void *cache = NULL;
547
548 if (cache != NULL) {
549 return cache;
550 }
551
552 PyObject *id = _create_dummy_identifier(p);
553 if (!id) {
554 return NULL;
555 }
556 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
557 return cache;
558}
559
560static int
561_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
562{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300563 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100564 if (name_len >= p->n_keyword_lists ||
565 p->keywords[name_len] == NULL ||
566 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100567 return NAME;
568 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100569 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100570 if (strncmp(k->str, name, name_len) == 0) {
571 return k->type;
572 }
573 }
574 return NAME;
575}
576
Guido van Rossumc001c092020-04-30 12:12:19 -0700577static int
578growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
579 assert(initial_size > 0);
580 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
581 arr->size = initial_size;
582 arr->num_items = 0;
583
584 return arr->items != NULL;
585}
586
587static int
588growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
589 if (arr->num_items >= arr->size) {
590 size_t new_size = arr->size * 2;
591 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
592 if (!new_items_array) {
593 return 0;
594 }
595 arr->items = new_items_array;
596 arr->size = new_size;
597 }
598
599 arr->items[arr->num_items].lineno = lineno;
600 arr->items[arr->num_items].comment = comment; // Take ownership
601 arr->num_items++;
602 return 1;
603}
604
605static void
606growable_comment_array_deallocate(growable_comment_array *arr) {
607 for (unsigned i = 0; i < arr->num_items; i++) {
608 PyMem_Free(arr->items[i].comment);
609 }
610 PyMem_Free(arr->items);
611}
612
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100613int
614_PyPegen_fill_token(Parser *p)
615{
Pablo Galindofb61c422020-06-15 14:23:43 +0100616 const char *start;
617 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100618 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700619
620 // Record and skip '# type: ignore' comments
621 while (type == TYPE_IGNORE) {
622 Py_ssize_t len = end - start;
623 char *tag = PyMem_Malloc(len + 1);
624 if (tag == NULL) {
625 PyErr_NoMemory();
626 return -1;
627 }
628 strncpy(tag, start, len);
629 tag[len] = '\0';
630 // Ownership of tag passes to the growable array
631 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
632 PyErr_NoMemory();
633 return -1;
634 }
635 type = PyTokenizer_Get(p->tok, &start, &end);
636 }
637
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100638 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
639 type = NEWLINE; /* Add an extra newline */
640 p->parsing_started = 0;
641
Pablo Galindob94dbd72020-04-27 18:35:58 +0100642 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100643 p->tok->pendin = -p->tok->indent;
644 p->tok->indent = 0;
645 }
646 }
647 else {
648 p->parsing_started = 1;
649 }
650
651 if (p->fill == p->size) {
652 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300653 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
654 if (new_tokens == NULL) {
655 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100656 return -1;
657 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100658 p->tokens = new_tokens;
659
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100660 for (int i = p->size; i < newsize; i++) {
661 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300662 if (p->tokens[i] == NULL) {
663 p->size = i; // Needed, in order to cleanup correctly after parser fails
664 PyErr_NoMemory();
665 return -1;
666 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100667 memset(p->tokens[i], '\0', sizeof(Token));
668 }
669 p->size = newsize;
670 }
671
672 Token *t = p->tokens[p->fill];
673 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
674 t->bytes = PyBytes_FromStringAndSize(start, end - start);
675 if (t->bytes == NULL) {
676 return -1;
677 }
678 PyArena_AddPyObject(p->arena, t->bytes);
679
680 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
681 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100682 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100683 int col_offset = -1;
684 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100685 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100686 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100687 }
688 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100689 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100690 }
691
692 t->lineno = p->starting_lineno + lineno;
693 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
694 t->end_lineno = p->starting_lineno + end_lineno;
695 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
696
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100697 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300698
699 if (type == ERRORTOKEN) {
700 if (p->tok->done == E_DECODE) {
701 return raise_decode_error(p);
702 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100703 return tokenizer_error(p);
704
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300705 }
706
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100707 return 0;
708}
709
710// Instrumentation to count the effectiveness of memoization.
711// The array counts the number of tokens skipped by memoization,
712// indexed by type.
713
714#define NSTATISTICS 2000
715static long memo_statistics[NSTATISTICS];
716
717void
718_PyPegen_clear_memo_statistics()
719{
720 for (int i = 0; i < NSTATISTICS; i++) {
721 memo_statistics[i] = 0;
722 }
723}
724
725PyObject *
726_PyPegen_get_memo_statistics()
727{
728 PyObject *ret = PyList_New(NSTATISTICS);
729 if (ret == NULL) {
730 return NULL;
731 }
732 for (int i = 0; i < NSTATISTICS; i++) {
733 PyObject *value = PyLong_FromLong(memo_statistics[i]);
734 if (value == NULL) {
735 Py_DECREF(ret);
736 return NULL;
737 }
738 // PyList_SetItem borrows a reference to value.
739 if (PyList_SetItem(ret, i, value) < 0) {
740 Py_DECREF(ret);
741 return NULL;
742 }
743 }
744 return ret;
745}
746
747int // bool
748_PyPegen_is_memoized(Parser *p, int type, void *pres)
749{
750 if (p->mark == p->fill) {
751 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300752 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100753 return -1;
754 }
755 }
756
757 Token *t = p->tokens[p->mark];
758
759 for (Memo *m = t->memo; m != NULL; m = m->next) {
760 if (m->type == type) {
761 if (0 <= type && type < NSTATISTICS) {
762 long count = m->mark - p->mark;
763 // A memoized negative result counts for one.
764 if (count <= 0) {
765 count = 1;
766 }
767 memo_statistics[type] += count;
768 }
769 p->mark = m->mark;
770 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100771 return 1;
772 }
773 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100774 return 0;
775}
776
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100777
778int
779_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
780{
781 int mark = p->mark;
782 void *res = func(p);
783 p->mark = mark;
784 return (res != NULL) == positive;
785}
786
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100787int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100788_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
789{
790 int mark = p->mark;
791 void *res = func(p, arg);
792 p->mark = mark;
793 return (res != NULL) == positive;
794}
795
796int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100797_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
798{
799 int mark = p->mark;
800 void *res = func(p, arg);
801 p->mark = mark;
802 return (res != NULL) == positive;
803}
804
805int
806_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
807{
808 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100809 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100810 p->mark = mark;
811 return (res != NULL) == positive;
812}
813
814Token *
815_PyPegen_expect_token(Parser *p, int type)
816{
817 if (p->mark == p->fill) {
818 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300819 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100820 return NULL;
821 }
822 }
823 Token *t = p->tokens[p->mark];
824 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100825 return NULL;
826 }
827 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100828 return t;
829}
830
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700831expr_ty
832_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
833{
834 if (p->mark == p->fill) {
835 if (_PyPegen_fill_token(p) < 0) {
836 p->error_indicator = 1;
837 return NULL;
838 }
839 }
840 Token *t = p->tokens[p->mark];
841 if (t->type != NAME) {
842 return NULL;
843 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300844 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700845 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300846 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700847 return NULL;
848 }
849 if (strcmp(s, keyword) != 0) {
850 return NULL;
851 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300852 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700853}
854
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100855Token *
856_PyPegen_get_last_nonnwhitespace_token(Parser *p)
857{
858 assert(p->mark >= 0);
859 Token *token = NULL;
860 for (int m = p->mark - 1; m >= 0; m--) {
861 token = p->tokens[m];
862 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
863 break;
864 }
865 }
866 return token;
867}
868
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100869expr_ty
870_PyPegen_name_token(Parser *p)
871{
872 Token *t = _PyPegen_expect_token(p, NAME);
873 if (t == NULL) {
874 return NULL;
875 }
876 char* s = PyBytes_AsString(t->bytes);
877 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300878 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100879 return NULL;
880 }
881 PyObject *id = _PyPegen_new_identifier(p, s);
882 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300883 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100884 return NULL;
885 }
886 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
887 p->arena);
888}
889
890void *
891_PyPegen_string_token(Parser *p)
892{
893 return _PyPegen_expect_token(p, STRING);
894}
895
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100896static PyObject *
897parsenumber_raw(const char *s)
898{
899 const char *end;
900 long x;
901 double dx;
902 Py_complex compl;
903 int imflag;
904
905 assert(s != NULL);
906 errno = 0;
907 end = s + strlen(s) - 1;
908 imflag = *end == 'j' || *end == 'J';
909 if (s[0] == '0') {
910 x = (long)PyOS_strtoul(s, (char **)&end, 0);
911 if (x < 0 && errno == 0) {
912 return PyLong_FromString(s, (char **)0, 0);
913 }
914 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100915 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100916 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100917 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100918 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100919 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100920 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100921 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100922 return PyLong_FromLong(x);
923 }
924 /* XXX Huge floats may silently fail */
925 if (imflag) {
926 compl.real = 0.;
927 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100928 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100929 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100930 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100931 return PyComplex_FromCComplex(compl);
932 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100933 dx = PyOS_string_to_double(s, NULL, NULL);
934 if (dx == -1.0 && PyErr_Occurred()) {
935 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100936 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100937 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100938}
939
940static PyObject *
941parsenumber(const char *s)
942{
Pablo Galindofb61c422020-06-15 14:23:43 +0100943 char *dup;
944 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100945 PyObject *res = NULL;
946
947 assert(s != NULL);
948
949 if (strchr(s, '_') == NULL) {
950 return parsenumber_raw(s);
951 }
952 /* Create a duplicate without underscores. */
953 dup = PyMem_Malloc(strlen(s) + 1);
954 if (dup == NULL) {
955 return PyErr_NoMemory();
956 }
957 end = dup;
958 for (; *s; s++) {
959 if (*s != '_') {
960 *end++ = *s;
961 }
962 }
963 *end = '\0';
964 res = parsenumber_raw(dup);
965 PyMem_Free(dup);
966 return res;
967}
968
969expr_ty
970_PyPegen_number_token(Parser *p)
971{
972 Token *t = _PyPegen_expect_token(p, NUMBER);
973 if (t == NULL) {
974 return NULL;
975 }
976
977 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100978 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300979 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100980 return NULL;
981 }
982
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300983 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
984 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700985 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300986 "in Python 3.6 and greater");
987 }
988
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100989 PyObject *c = parsenumber(num_raw);
990
991 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300992 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100993 return NULL;
994 }
995
996 if (PyArena_AddPyObject(p->arena, c) < 0) {
997 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300998 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100999 return NULL;
1000 }
1001
1002 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
1003 p->arena);
1004}
1005
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001006static int // bool
1007newline_in_string(Parser *p, const char *cur)
1008{
Pablo Galindo2e6593d2020-06-06 00:52:27 +01001009 for (const char *c = cur; c >= p->tok->buf; c--) {
1010 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001011 return 1;
1012 }
1013 }
1014 return 0;
1015}
1016
1017/* Check that the source for a single input statement really is a single
1018 statement by looking at what is left in the buffer after parsing.
1019 Trailing whitespace and comments are OK. */
1020static int // bool
1021bad_single_statement(Parser *p)
1022{
1023 const char *cur = strchr(p->tok->buf, '\n');
1024
1025 /* Newlines are allowed if preceded by a line continuation character
1026 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +00001027 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
1028 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001029 return 0;
1030 }
1031 char c = *cur;
1032
1033 for (;;) {
1034 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1035 c = *++cur;
1036 }
1037
1038 if (!c) {
1039 return 0;
1040 }
1041
1042 if (c != '#') {
1043 return 1;
1044 }
1045
1046 /* Suck up comment. */
1047 while (c && c != '\n') {
1048 c = *++cur;
1049 }
1050 }
1051}
1052
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001053void
1054_PyPegen_Parser_Free(Parser *p)
1055{
1056 Py_XDECREF(p->normalize);
1057 for (int i = 0; i < p->size; i++) {
1058 PyMem_Free(p->tokens[i]);
1059 }
1060 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001061 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001062 PyMem_Free(p);
1063}
1064
Pablo Galindo2b74c832020-04-27 18:02:07 +01001065static int
1066compute_parser_flags(PyCompilerFlags *flags)
1067{
1068 int parser_flags = 0;
1069 if (!flags) {
1070 return 0;
1071 }
1072 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1073 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1074 }
1075 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1076 parser_flags |= PyPARSE_IGNORE_COOKIE;
1077 }
1078 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1079 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1080 }
1081 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1082 parser_flags |= PyPARSE_TYPE_COMMENTS;
1083 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001084 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001085 parser_flags |= PyPARSE_ASYNC_HACKS;
1086 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001087 return parser_flags;
1088}
1089
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001090Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001091_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001092 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001093{
1094 Parser *p = PyMem_Malloc(sizeof(Parser));
1095 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001096 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001097 }
1098 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001099 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1100 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001101 p->tok = tok;
1102 p->keywords = NULL;
1103 p->n_keyword_lists = -1;
1104 p->tokens = PyMem_Malloc(sizeof(Token *));
1105 if (!p->tokens) {
1106 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001107 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001108 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001109 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001110 if (!p->tokens) {
1111 PyMem_Free(p->tokens);
1112 PyMem_Free(p);
1113 return (Parser *) PyErr_NoMemory();
1114 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001115 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1116 PyMem_Free(p->tokens[0]);
1117 PyMem_Free(p->tokens);
1118 PyMem_Free(p);
1119 return (Parser *) PyErr_NoMemory();
1120 }
1121
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001122 p->mark = 0;
1123 p->fill = 0;
1124 p->size = 1;
1125
1126 p->errcode = errcode;
1127 p->arena = arena;
1128 p->start_rule = start_rule;
1129 p->parsing_started = 0;
1130 p->normalize = NULL;
1131 p->error_indicator = 0;
1132
1133 p->starting_lineno = 0;
1134 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001135 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001136 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001137 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001138 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001139 p->call_invalid_rules = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001140
1141 return p;
1142}
1143
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001144static void
1145reset_parser_state(Parser *p)
1146{
1147 for (int i = 0; i < p->fill; i++) {
1148 p->tokens[i]->memo = NULL;
1149 }
1150 p->mark = 0;
1151 p->call_invalid_rules = 1;
1152}
1153
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001154void *
1155_PyPegen_run_parser(Parser *p)
1156{
1157 void *res = _PyPegen_parse(p);
1158 if (res == NULL) {
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001159 reset_parser_state(p);
1160 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001161 if (PyErr_Occurred()) {
1162 return NULL;
1163 }
1164 if (p->fill == 0) {
1165 RAISE_SYNTAX_ERROR("error at start before reading any input");
1166 }
1167 else if (p->tok->done == E_EOF) {
1168 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1169 }
1170 else {
1171 if (p->tokens[p->fill-1]->type == INDENT) {
1172 RAISE_INDENTATION_ERROR("unexpected indent");
1173 }
1174 else if (p->tokens[p->fill-1]->type == DEDENT) {
1175 RAISE_INDENTATION_ERROR("unexpected unindent");
1176 }
1177 else {
1178 RAISE_SYNTAX_ERROR("invalid syntax");
1179 }
1180 }
1181 return NULL;
1182 }
1183
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001184 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1185 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1186 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1187 }
1188
Pablo Galindo13322262020-07-27 23:46:59 +01001189#if defined(Py_DEBUG) && defined(Py_BUILD_CORE)
1190 if (p->start_rule == Py_single_input ||
1191 p->start_rule == Py_file_input ||
1192 p->start_rule == Py_eval_input)
1193 {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001194 if (!PyAST_Validate(res)) {
1195 return NULL;
1196 }
Pablo Galindo13322262020-07-27 23:46:59 +01001197 }
1198#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001199 return res;
1200}
1201
1202mod_ty
1203_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1204 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001205 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001206{
1207 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1208 if (tok == NULL) {
1209 if (PyErr_Occurred()) {
1210 raise_tokenizer_init_error(filename_ob);
1211 return NULL;
1212 }
1213 return NULL;
1214 }
1215 // This transfers the ownership to the tokenizer
1216 tok->filename = filename_ob;
1217 Py_INCREF(filename_ob);
1218
1219 // From here on we need to clean up even if there's an error
1220 mod_ty result = NULL;
1221
Pablo Galindo2b74c832020-04-27 18:02:07 +01001222 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001223 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1224 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001225 if (p == NULL) {
1226 goto error;
1227 }
1228
1229 result = _PyPegen_run_parser(p);
1230 _PyPegen_Parser_Free(p);
1231
1232error:
1233 PyTokenizer_Free(tok);
1234 return result;
1235}
1236
1237mod_ty
1238_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001239 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001240{
1241 FILE *fp = fopen(filename, "rb");
1242 if (fp == NULL) {
1243 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1244 return NULL;
1245 }
1246
1247 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001248 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001249
1250 fclose(fp);
1251 return result;
1252}
1253
1254mod_ty
1255_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001256 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001257{
1258 int exec_input = start_rule == Py_file_input;
1259
1260 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001261 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001262 tok = PyTokenizer_FromUTF8(str, exec_input);
1263 } else {
1264 tok = PyTokenizer_FromString(str, exec_input);
1265 }
1266 if (tok == NULL) {
1267 if (PyErr_Occurred()) {
1268 raise_tokenizer_init_error(filename_ob);
1269 }
1270 return NULL;
1271 }
1272 // This transfers the ownership to the tokenizer
1273 tok->filename = filename_ob;
1274 Py_INCREF(filename_ob);
1275
1276 // We need to clear up from here on
1277 mod_ty result = NULL;
1278
Pablo Galindo2b74c832020-04-27 18:02:07 +01001279 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001280 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1281 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001282 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1283 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001284 if (p == NULL) {
1285 goto error;
1286 }
1287
1288 result = _PyPegen_run_parser(p);
1289 _PyPegen_Parser_Free(p);
1290
1291error:
1292 PyTokenizer_Free(tok);
1293 return result;
1294}
1295
Pablo Galindoa5634c42020-09-16 19:42:00 +01001296asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001297_PyPegen_interactive_exit(Parser *p)
1298{
1299 if (p->errcode) {
1300 *(p->errcode) = E_EOF;
1301 }
1302 return NULL;
1303}
1304
1305/* Creates a single-element asdl_seq* that contains a */
1306asdl_seq *
1307_PyPegen_singleton_seq(Parser *p, void *a)
1308{
1309 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001310 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001311 if (!seq) {
1312 return NULL;
1313 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001314 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001315 return seq;
1316}
1317
1318/* Creates a copy of seq and prepends a to it */
1319asdl_seq *
1320_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1321{
1322 assert(a != NULL);
1323 if (!seq) {
1324 return _PyPegen_singleton_seq(p, a);
1325 }
1326
Pablo Galindoa5634c42020-09-16 19:42:00 +01001327 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 +01001328 if (!new_seq) {
1329 return NULL;
1330 }
1331
Pablo Galindoa5634c42020-09-16 19:42:00 +01001332 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001333 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001334 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001335 }
1336 return new_seq;
1337}
1338
Guido van Rossumc001c092020-04-30 12:12:19 -07001339/* Creates a copy of seq and appends a to it */
1340asdl_seq *
1341_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1342{
1343 assert(a != NULL);
1344 if (!seq) {
1345 return _PyPegen_singleton_seq(p, a);
1346 }
1347
Pablo Galindoa5634c42020-09-16 19:42:00 +01001348 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 -07001349 if (!new_seq) {
1350 return NULL;
1351 }
1352
1353 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001354 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001355 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001356 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001357 return new_seq;
1358}
1359
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001360static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001361_get_flattened_seq_size(asdl_seq *seqs)
1362{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001363 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001364 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001365 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001366 size += asdl_seq_LEN(inner_seq);
1367 }
1368 return size;
1369}
1370
1371/* Flattens an asdl_seq* of asdl_seq*s */
1372asdl_seq *
1373_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1374{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001375 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001376 assert(flattened_seq_size > 0);
1377
Pablo Galindoa5634c42020-09-16 19:42:00 +01001378 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001379 if (!flattened_seq) {
1380 return NULL;
1381 }
1382
1383 int flattened_seq_idx = 0;
1384 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001385 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001386 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001387 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001388 }
1389 }
1390 assert(flattened_seq_idx == flattened_seq_size);
1391
1392 return flattened_seq;
1393}
1394
1395/* Creates a new name of the form <first_name>.<second_name> */
1396expr_ty
1397_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1398{
1399 assert(first_name != NULL && second_name != NULL);
1400 PyObject *first_identifier = first_name->v.Name.id;
1401 PyObject *second_identifier = second_name->v.Name.id;
1402
1403 if (PyUnicode_READY(first_identifier) == -1) {
1404 return NULL;
1405 }
1406 if (PyUnicode_READY(second_identifier) == -1) {
1407 return NULL;
1408 }
1409 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1410 if (!first_str) {
1411 return NULL;
1412 }
1413 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1414 if (!second_str) {
1415 return NULL;
1416 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001417 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001418
1419 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1420 if (!str) {
1421 return NULL;
1422 }
1423
1424 char *s = PyBytes_AS_STRING(str);
1425 if (!s) {
1426 return NULL;
1427 }
1428
1429 strcpy(s, first_str);
1430 s += strlen(first_str);
1431 *s++ = '.';
1432 strcpy(s, second_str);
1433 s += strlen(second_str);
1434 *s = '\0';
1435
1436 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1437 Py_DECREF(str);
1438 if (!uni) {
1439 return NULL;
1440 }
1441 PyUnicode_InternInPlace(&uni);
1442 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1443 Py_DECREF(uni);
1444 return NULL;
1445 }
1446
1447 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1448}
1449
1450/* Counts the total number of dots in seq's tokens */
1451int
1452_PyPegen_seq_count_dots(asdl_seq *seq)
1453{
1454 int number_of_dots = 0;
1455 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001456 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001457 switch (current_expr->type) {
1458 case ELLIPSIS:
1459 number_of_dots += 3;
1460 break;
1461 case DOT:
1462 number_of_dots += 1;
1463 break;
1464 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001465 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001466 }
1467 }
1468
1469 return number_of_dots;
1470}
1471
1472/* Creates an alias with '*' as the identifier name */
1473alias_ty
1474_PyPegen_alias_for_star(Parser *p)
1475{
1476 PyObject *str = PyUnicode_InternFromString("*");
1477 if (!str) {
1478 return NULL;
1479 }
1480 if (PyArena_AddPyObject(p->arena, str) < 0) {
1481 Py_DECREF(str);
1482 return NULL;
1483 }
1484 return alias(str, NULL, p->arena);
1485}
1486
1487/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001488asdl_identifier_seq *
1489_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001490{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001491 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001492 assert(len > 0);
1493
Pablo Galindoa5634c42020-09-16 19:42:00 +01001494 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001495 if (!new_seq) {
1496 return NULL;
1497 }
1498 for (Py_ssize_t i = 0; i < len; i++) {
1499 expr_ty e = asdl_seq_GET(seq, i);
1500 asdl_seq_SET(new_seq, i, e->v.Name.id);
1501 }
1502 return new_seq;
1503}
1504
1505/* Constructs a CmpopExprPair */
1506CmpopExprPair *
1507_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1508{
1509 assert(expr != NULL);
1510 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1511 if (!a) {
1512 return NULL;
1513 }
1514 a->cmpop = cmpop;
1515 a->expr = expr;
1516 return a;
1517}
1518
1519asdl_int_seq *
1520_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1521{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001522 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001523 assert(len > 0);
1524
1525 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1526 if (!new_seq) {
1527 return NULL;
1528 }
1529 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001530 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001531 asdl_seq_SET(new_seq, i, pair->cmpop);
1532 }
1533 return new_seq;
1534}
1535
Pablo Galindoa5634c42020-09-16 19:42:00 +01001536asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001537_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1538{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001539 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001540 assert(len > 0);
1541
Pablo Galindoa5634c42020-09-16 19:42:00 +01001542 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001543 if (!new_seq) {
1544 return NULL;
1545 }
1546 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001547 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001548 asdl_seq_SET(new_seq, i, pair->expr);
1549 }
1550 return new_seq;
1551}
1552
1553/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001554static asdl_expr_seq *
1555_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001556{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001557 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001558 if (len == 0) {
1559 return NULL;
1560 }
1561
Pablo Galindoa5634c42020-09-16 19:42:00 +01001562 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001563 if (!new_seq) {
1564 return NULL;
1565 }
1566 for (Py_ssize_t i = 0; i < len; i++) {
1567 expr_ty e = asdl_seq_GET(seq, i);
1568 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1569 }
1570 return new_seq;
1571}
1572
1573static expr_ty
1574_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1575{
1576 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1577}
1578
1579static expr_ty
1580_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1581{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001582 return _Py_Tuple(
1583 _set_seq_context(p, e->v.Tuple.elts, ctx),
1584 ctx,
1585 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001586}
1587
1588static expr_ty
1589_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1590{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001591 return _Py_List(
1592 _set_seq_context(p, e->v.List.elts, ctx),
1593 ctx,
1594 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001595}
1596
1597static expr_ty
1598_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1599{
1600 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1601}
1602
1603static expr_ty
1604_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1605{
1606 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1607}
1608
1609static expr_ty
1610_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1611{
1612 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1613}
1614
1615/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1616expr_ty
1617_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1618{
1619 assert(expr != NULL);
1620
1621 expr_ty new = NULL;
1622 switch (expr->kind) {
1623 case Name_kind:
1624 new = _set_name_context(p, expr, ctx);
1625 break;
1626 case Tuple_kind:
1627 new = _set_tuple_context(p, expr, ctx);
1628 break;
1629 case List_kind:
1630 new = _set_list_context(p, expr, ctx);
1631 break;
1632 case Subscript_kind:
1633 new = _set_subscript_context(p, expr, ctx);
1634 break;
1635 case Attribute_kind:
1636 new = _set_attribute_context(p, expr, ctx);
1637 break;
1638 case Starred_kind:
1639 new = _set_starred_context(p, expr, ctx);
1640 break;
1641 default:
1642 new = expr;
1643 }
1644 return new;
1645}
1646
1647/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1648KeyValuePair *
1649_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1650{
1651 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1652 if (!a) {
1653 return NULL;
1654 }
1655 a->key = key;
1656 a->value = value;
1657 return a;
1658}
1659
1660/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001661asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001662_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1663{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001664 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001665 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001666 if (!new_seq) {
1667 return NULL;
1668 }
1669 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001670 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001671 asdl_seq_SET(new_seq, i, pair->key);
1672 }
1673 return new_seq;
1674}
1675
1676/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001677asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001678_PyPegen_get_values(Parser *p, asdl_seq *seq)
1679{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001680 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001681 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001682 if (!new_seq) {
1683 return NULL;
1684 }
1685 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001686 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001687 asdl_seq_SET(new_seq, i, pair->value);
1688 }
1689 return new_seq;
1690}
1691
1692/* Constructs a NameDefaultPair */
1693NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001694_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001695{
1696 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1697 if (!a) {
1698 return NULL;
1699 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001700 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001701 a->value = value;
1702 return a;
1703}
1704
1705/* Constructs a SlashWithDefault */
1706SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001707_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001708{
1709 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1710 if (!a) {
1711 return NULL;
1712 }
1713 a->plain_names = plain_names;
1714 a->names_with_defaults = names_with_defaults;
1715 return a;
1716}
1717
1718/* Constructs a StarEtc */
1719StarEtc *
1720_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1721{
1722 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1723 if (!a) {
1724 return NULL;
1725 }
1726 a->vararg = vararg;
1727 a->kwonlyargs = kwonlyargs;
1728 a->kwarg = kwarg;
1729 return a;
1730}
1731
1732asdl_seq *
1733_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1734{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001735 Py_ssize_t first_len = asdl_seq_LEN(a);
1736 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001737 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001738 if (!new_seq) {
1739 return NULL;
1740 }
1741
1742 int k = 0;
1743 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001744 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001745 }
1746 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001747 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001748 }
1749
1750 return new_seq;
1751}
1752
Pablo Galindoa5634c42020-09-16 19:42:00 +01001753static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001754_get_names(Parser *p, asdl_seq *names_with_defaults)
1755{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001756 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001757 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001758 if (!seq) {
1759 return NULL;
1760 }
1761 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001762 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001763 asdl_seq_SET(seq, i, pair->arg);
1764 }
1765 return seq;
1766}
1767
Pablo Galindoa5634c42020-09-16 19:42:00 +01001768static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001769_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1770{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001771 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001772 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001773 if (!seq) {
1774 return NULL;
1775 }
1776 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001777 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001778 asdl_seq_SET(seq, i, pair->value);
1779 }
1780 return seq;
1781}
1782
1783/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1784arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001785_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
1786 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001787 asdl_seq *names_with_default, StarEtc *star_etc)
1788{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001789 asdl_arg_seq *posonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001790 if (slash_without_default != NULL) {
1791 posonlyargs = slash_without_default;
1792 }
1793 else if (slash_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001794 asdl_arg_seq *slash_with_default_names =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001795 _get_names(p, slash_with_default->names_with_defaults);
1796 if (!slash_with_default_names) {
1797 return NULL;
1798 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001799 posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1800 p,
1801 (asdl_seq*)slash_with_default->plain_names,
1802 (asdl_seq*)slash_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001803 if (!posonlyargs) {
1804 return NULL;
1805 }
1806 }
1807 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001808 posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001809 if (!posonlyargs) {
1810 return NULL;
1811 }
1812 }
1813
Pablo Galindoa5634c42020-09-16 19:42:00 +01001814 asdl_arg_seq *posargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001815 if (plain_names != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001816 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001817 if (!names_with_default_names) {
1818 return NULL;
1819 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001820 posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1821 p,
1822 (asdl_seq*)plain_names,
1823 (asdl_seq*)names_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001824 if (!posargs) {
1825 return NULL;
1826 }
1827 }
1828 else if (plain_names == NULL && names_with_default != NULL) {
1829 posargs = _get_names(p, names_with_default);
1830 if (!posargs) {
1831 return NULL;
1832 }
1833 }
1834 else if (plain_names != NULL && names_with_default == NULL) {
1835 posargs = plain_names;
1836 }
1837 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001838 posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001839 if (!posargs) {
1840 return NULL;
1841 }
1842 }
1843
Pablo Galindoa5634c42020-09-16 19:42:00 +01001844 asdl_expr_seq *posdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001845 if (slash_with_default != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001846 asdl_expr_seq *slash_with_default_values =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001847 _get_defaults(p, slash_with_default->names_with_defaults);
1848 if (!slash_with_default_values) {
1849 return NULL;
1850 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001851 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001852 if (!names_with_default_values) {
1853 return NULL;
1854 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001855 posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
1856 p,
1857 (asdl_seq*)slash_with_default_values,
1858 (asdl_seq*)names_with_default_values);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001859 if (!posdefaults) {
1860 return NULL;
1861 }
1862 }
1863 else if (slash_with_default == NULL && names_with_default != NULL) {
1864 posdefaults = _get_defaults(p, names_with_default);
1865 if (!posdefaults) {
1866 return NULL;
1867 }
1868 }
1869 else if (slash_with_default != NULL && names_with_default == NULL) {
1870 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1871 if (!posdefaults) {
1872 return NULL;
1873 }
1874 }
1875 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001876 posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001877 if (!posdefaults) {
1878 return NULL;
1879 }
1880 }
1881
1882 arg_ty vararg = NULL;
1883 if (star_etc != NULL && star_etc->vararg != NULL) {
1884 vararg = star_etc->vararg;
1885 }
1886
Pablo Galindoa5634c42020-09-16 19:42:00 +01001887 asdl_arg_seq *kwonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001888 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1889 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1890 if (!kwonlyargs) {
1891 return NULL;
1892 }
1893 }
1894 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001895 kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001896 if (!kwonlyargs) {
1897 return NULL;
1898 }
1899 }
1900
Pablo Galindoa5634c42020-09-16 19:42:00 +01001901 asdl_expr_seq *kwdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001902 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1903 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1904 if (!kwdefaults) {
1905 return NULL;
1906 }
1907 }
1908 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001909 kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001910 if (!kwdefaults) {
1911 return NULL;
1912 }
1913 }
1914
1915 arg_ty kwarg = NULL;
1916 if (star_etc != NULL && star_etc->kwarg != NULL) {
1917 kwarg = star_etc->kwarg;
1918 }
1919
1920 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1921 posdefaults, p->arena);
1922}
1923
1924/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1925 * arguments. */
1926arguments_ty
1927_PyPegen_empty_arguments(Parser *p)
1928{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001929 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001930 if (!posonlyargs) {
1931 return NULL;
1932 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001933 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001934 if (!posargs) {
1935 return NULL;
1936 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001937 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001938 if (!posdefaults) {
1939 return NULL;
1940 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001941 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001942 if (!kwonlyargs) {
1943 return NULL;
1944 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001945 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001946 if (!kwdefaults) {
1947 return NULL;
1948 }
1949
Batuhan Taskaya02a16032020-10-10 20:14:59 +03001950 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, posdefaults,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001951 p->arena);
1952}
1953
1954/* Encapsulates the value of an operator_ty into an AugOperator struct */
1955AugOperator *
1956_PyPegen_augoperator(Parser *p, operator_ty kind)
1957{
1958 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1959 if (!a) {
1960 return NULL;
1961 }
1962 a->kind = kind;
1963 return a;
1964}
1965
1966/* Construct a FunctionDef equivalent to function_def, but with decorators */
1967stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001968_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001969{
1970 assert(function_def != NULL);
1971 if (function_def->kind == AsyncFunctionDef_kind) {
1972 return _Py_AsyncFunctionDef(
1973 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1974 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1975 function_def->v.FunctionDef.type_comment, function_def->lineno,
1976 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1977 p->arena);
1978 }
1979
1980 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1981 function_def->v.FunctionDef.body, decorators,
1982 function_def->v.FunctionDef.returns,
1983 function_def->v.FunctionDef.type_comment, function_def->lineno,
1984 function_def->col_offset, function_def->end_lineno,
1985 function_def->end_col_offset, p->arena);
1986}
1987
1988/* Construct a ClassDef equivalent to class_def, but with decorators */
1989stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001990_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001991{
1992 assert(class_def != NULL);
1993 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1994 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1995 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1996 class_def->end_col_offset, p->arena);
1997}
1998
1999/* Construct a KeywordOrStarred */
2000KeywordOrStarred *
2001_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
2002{
2003 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
2004 if (!a) {
2005 return NULL;
2006 }
2007 a->element = element;
2008 a->is_keyword = is_keyword;
2009 return a;
2010}
2011
2012/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
2013static int
2014_seq_number_of_starred_exprs(asdl_seq *seq)
2015{
2016 int n = 0;
2017 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002018 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002019 if (!k->is_keyword) {
2020 n++;
2021 }
2022 }
2023 return n;
2024}
2025
2026/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002027asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002028_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
2029{
2030 int new_len = _seq_number_of_starred_exprs(kwargs);
2031 if (new_len == 0) {
2032 return NULL;
2033 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002034 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002035 if (!new_seq) {
2036 return NULL;
2037 }
2038
2039 int idx = 0;
2040 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002041 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002042 if (!k->is_keyword) {
2043 asdl_seq_SET(new_seq, idx++, k->element);
2044 }
2045 }
2046 return new_seq;
2047}
2048
2049/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002050asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002051_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2052{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002053 Py_ssize_t len = asdl_seq_LEN(kwargs);
2054 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002055 if (new_len == 0) {
2056 return NULL;
2057 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002058 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002059 if (!new_seq) {
2060 return NULL;
2061 }
2062
2063 int idx = 0;
2064 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002065 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002066 if (k->is_keyword) {
2067 asdl_seq_SET(new_seq, idx++, k->element);
2068 }
2069 }
2070 return new_seq;
2071}
2072
2073expr_ty
2074_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2075{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002076 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002077 assert(len > 0);
2078
Pablo Galindoa5634c42020-09-16 19:42:00 +01002079 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2080 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002081
2082 int bytesmode = 0;
2083 PyObject *bytes_str = NULL;
2084
2085 FstringParser state;
2086 _PyPegen_FstringParser_Init(&state);
2087
2088 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002089 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002090
2091 int this_bytesmode;
2092 int this_rawmode;
2093 PyObject *s;
2094 const char *fstr;
2095 Py_ssize_t fstrlen = -1;
2096
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002097 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002098 goto error;
2099 }
2100
2101 /* Check that we are not mixing bytes with unicode. */
2102 if (i != 0 && bytesmode != this_bytesmode) {
2103 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2104 Py_XDECREF(s);
2105 goto error;
2106 }
2107 bytesmode = this_bytesmode;
2108
2109 if (fstr != NULL) {
2110 assert(s == NULL && !bytesmode);
2111
2112 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2113 this_rawmode, 0, first, t, last);
2114 if (result < 0) {
2115 goto error;
2116 }
2117 }
2118 else {
2119 /* String or byte string. */
2120 assert(s != NULL && fstr == NULL);
2121 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2122
2123 if (bytesmode) {
2124 if (i == 0) {
2125 bytes_str = s;
2126 }
2127 else {
2128 PyBytes_ConcatAndDel(&bytes_str, s);
2129 if (!bytes_str) {
2130 goto error;
2131 }
2132 }
2133 }
2134 else {
2135 /* This is a regular string. Concatenate it. */
2136 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2137 goto error;
2138 }
2139 }
2140 }
2141 }
2142
2143 if (bytesmode) {
2144 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2145 goto error;
2146 }
2147 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2148 last->end_col_offset, p->arena);
2149 }
2150
2151 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2152
2153error:
2154 Py_XDECREF(bytes_str);
2155 _PyPegen_FstringParser_Dealloc(&state);
2156 if (PyErr_Occurred()) {
2157 raise_decode_error(p);
2158 }
2159 return NULL;
2160}
Guido van Rossumc001c092020-04-30 12:12:19 -07002161
2162mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002163_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2164 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002165 Py_ssize_t num = p->type_ignore_comments.num_items;
2166 if (num > 0) {
2167 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002168 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002169 if (type_ignores == NULL) {
2170 return NULL;
2171 }
2172 for (int i = 0; i < num; i++) {
2173 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2174 if (tag == NULL) {
2175 return NULL;
2176 }
2177 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2178 if (ti == NULL) {
2179 return NULL;
2180 }
2181 asdl_seq_SET(type_ignores, i, ti);
2182 }
2183 }
2184 return Module(a, type_ignores, p->arena);
2185}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002186
2187// Error reporting helpers
2188
2189expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002190_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002191{
2192 if (e == NULL) {
2193 return NULL;
2194 }
2195
2196#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2197 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2198 for (Py_ssize_t i = 0; i < len; i++) {\
2199 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002200 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002201 if (child != NULL) {\
2202 return child;\
2203 }\
2204 }\
2205 } while (0)
2206
2207 // We only need to visit List and Tuple nodes recursively as those
2208 // are the only ones that can contain valid names in targets when
2209 // they are parsed as expressions. Any other kind of expression
2210 // that is a container (like Sets or Dicts) is directly invalid and
2211 // we don't need to visit it recursively.
2212
2213 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002214 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002215 VISIT_CONTAINER(e, List);
2216 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002217 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002218 VISIT_CONTAINER(e, Tuple);
2219 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002220 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002221 if (targets_type == DEL_TARGETS) {
2222 return e;
2223 }
2224 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2225 case Compare_kind:
2226 // This is needed, because the `a in b` in `for a in b` gets parsed
2227 // as a comparison, and so we need to search the left side of the comparison
2228 // for invalid targets.
2229 if (targets_type == FOR_TARGETS) {
2230 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2231 if (cmpop == In) {
2232 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2233 }
2234 return NULL;
2235 }
2236 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002237 case Name_kind:
2238 case Subscript_kind:
2239 case Attribute_kind:
2240 return NULL;
2241 default:
2242 return e;
2243 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002244}
2245
2246void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2247 int kwarg_unpacking = 0;
2248 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2249 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2250 if (!keyword->arg) {
2251 kwarg_unpacking = 1;
2252 }
2253 }
2254
2255 const char *msg = NULL;
2256 if (kwarg_unpacking) {
2257 msg = "positional argument follows keyword argument unpacking";
2258 } else {
2259 msg = "positional argument follows keyword argument";
2260 }
2261
2262 return RAISE_SYNTAX_ERROR(msg);
2263}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002264
2265void *
2266_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2267{
2268 /* The rule that calls this function is 'args for_if_clauses'.
2269 For the input f(L, x for x in y), L and x are in args and
2270 the for is parsed as a for_if_clause. We have to check if
2271 len <= 1, so that input like dict((a, b) for a, b in x)
2272 gets successfully parsed and then we pass the last
2273 argument (x in the above example) as the location of the
2274 error */
2275 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2276 if (len <= 1) {
2277 return NULL;
2278 }
2279
2280 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2281 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2282 "Generator expression must be parenthesized"
2283 );
2284}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002285
2286
Pablo Galindoa5634c42020-09-16 19:42:00 +01002287expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002288 int lineno, int col_offset, int end_lineno,
2289 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002290 Py_ssize_t args_len = asdl_seq_LEN(a);
2291 Py_ssize_t total_len = args_len;
2292
2293 if (b == NULL) {
Pablo Galindo315a61f2020-09-03 15:29:32 +01002294 return _Py_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2295 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002296
2297 }
2298
Pablo Galindoa5634c42020-09-16 19:42:00 +01002299 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2300 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002301
2302 if (starreds) {
2303 total_len += asdl_seq_LEN(starreds);
2304 }
2305
Pablo Galindoa5634c42020-09-16 19:42:00 +01002306 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002307
2308 Py_ssize_t i = 0;
2309 for (i = 0; i < args_len; i++) {
2310 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2311 }
2312 for (; i < total_len; i++) {
2313 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2314 }
2315
Pablo Galindo315a61f2020-09-03 15:29:32 +01002316 return _Py_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2317 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002318}