blob: 216edd810e246f2214ac9dcc69380e8061330257 [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
65_PyPegen_check_barry_as_flufl(Parser *p) {
66 Token *t = p->tokens[p->fill - 1];
67 assert(t->bytes != NULL);
68 assert(t->type == NOTEQUAL);
69
70 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindofb61c422020-06-15 14:23:43 +010071 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010072 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
73 return -1;
Pablo Galindofb61c422020-06-15 14:23:43 +010074 }
75 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010076 return strcmp(tok_str, "!=");
77 }
78 return 0;
79}
80
Pablo Galindoc5fc1562020-04-22 23:29:27 +010081PyObject *
82_PyPegen_new_identifier(Parser *p, char *n)
83{
84 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
85 if (!id) {
86 goto error;
87 }
88 /* PyUnicode_DecodeUTF8 should always return a ready string. */
89 assert(PyUnicode_IS_READY(id));
90 /* Check whether there are non-ASCII characters in the
91 identifier; if so, normalize to NFKC. */
92 if (!PyUnicode_IS_ASCII(id))
93 {
94 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030095 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010096 {
97 Py_DECREF(id);
98 goto error;
99 }
100 PyObject *form = PyUnicode_InternFromString("NFKC");
101 if (form == NULL)
102 {
103 Py_DECREF(id);
104 goto error;
105 }
106 PyObject *args[2] = {form, id};
107 id2 = _PyObject_FastCall(p->normalize, args, 2);
108 Py_DECREF(id);
109 Py_DECREF(form);
110 if (!id2) {
111 goto error;
112 }
113 if (!PyUnicode_Check(id2))
114 {
115 PyErr_Format(PyExc_TypeError,
116 "unicodedata.normalize() must return a string, not "
117 "%.200s",
118 _PyType_Name(Py_TYPE(id2)));
119 Py_DECREF(id2);
120 goto error;
121 }
122 id = id2;
123 }
124 PyUnicode_InternInPlace(&id);
125 if (PyArena_AddPyObject(p->arena, id) < 0)
126 {
127 Py_DECREF(id);
128 goto error;
129 }
130 return id;
131
132error:
133 p->error_indicator = 1;
134 return NULL;
135}
136
137static PyObject *
138_create_dummy_identifier(Parser *p)
139{
140 return _PyPegen_new_identifier(p, "");
141}
142
143static inline Py_ssize_t
Pablo Galindo51c58962020-06-16 16:49:43 +0100144byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100145{
146 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300147 if (!str) {
148 return 0;
149 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100150 assert(col_offset >= 0 && (unsigned long)col_offset <= strlen(str));
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300151 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100152 if (!text) {
153 return 0;
154 }
155 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
156 Py_DECREF(text);
157 return size;
158}
159
160const char *
161_PyPegen_get_expr_name(expr_ty e)
162{
Pablo Galindo9f495902020-06-08 02:57:00 +0100163 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100164 switch (e->kind) {
165 case Attribute_kind:
166 return "attribute";
167 case Subscript_kind:
168 return "subscript";
169 case Starred_kind:
170 return "starred";
171 case Name_kind:
172 return "name";
173 case List_kind:
174 return "list";
175 case Tuple_kind:
176 return "tuple";
177 case Lambda_kind:
178 return "lambda";
179 case Call_kind:
180 return "function call";
181 case BoolOp_kind:
182 case BinOp_kind:
183 case UnaryOp_kind:
184 return "operator";
185 case GeneratorExp_kind:
186 return "generator expression";
187 case Yield_kind:
188 case YieldFrom_kind:
189 return "yield expression";
190 case Await_kind:
191 return "await expression";
192 case ListComp_kind:
193 return "list comprehension";
194 case SetComp_kind:
195 return "set comprehension";
196 case DictComp_kind:
197 return "dict comprehension";
198 case Dict_kind:
199 return "dict display";
200 case Set_kind:
201 return "set display";
202 case JoinedStr_kind:
203 case FormattedValue_kind:
204 return "f-string expression";
205 case Constant_kind: {
206 PyObject *value = e->v.Constant.value;
207 if (value == Py_None) {
208 return "None";
209 }
210 if (value == Py_False) {
211 return "False";
212 }
213 if (value == Py_True) {
214 return "True";
215 }
216 if (value == Py_Ellipsis) {
217 return "Ellipsis";
218 }
219 return "literal";
220 }
221 case Compare_kind:
222 return "comparison";
223 case IfExp_kind:
224 return "conditional expression";
225 case NamedExpr_kind:
226 return "named expression";
227 default:
228 PyErr_Format(PyExc_SystemError,
229 "unexpected expression in assignment %d (line %d)",
230 e->kind, e->lineno);
231 return NULL;
232 }
233}
234
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300235static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100236raise_decode_error(Parser *p)
237{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300238 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100239 const char *errtype = NULL;
240 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
241 errtype = "unicode error";
242 }
243 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
244 errtype = "value error";
245 }
246 if (errtype) {
Pablo Galindofb61c422020-06-15 14:23:43 +0100247 PyObject *type;
248 PyObject *value;
249 PyObject *tback;
250 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100251 PyErr_Fetch(&type, &value, &tback);
252 errstr = PyObject_Str(value);
253 if (errstr) {
254 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
255 Py_DECREF(errstr);
256 }
257 else {
258 PyErr_Clear();
259 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
260 }
261 Py_XDECREF(type);
262 Py_XDECREF(value);
263 Py_XDECREF(tback);
264 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300265
266 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100267}
268
269static void
270raise_tokenizer_init_error(PyObject *filename)
271{
272 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
273 || PyErr_ExceptionMatches(PyExc_ValueError)
274 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
275 return;
276 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300277 PyObject *errstr = NULL;
278 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100279 PyObject *type;
280 PyObject *value;
281 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100282 PyErr_Fetch(&type, &value, &tback);
283 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300284 if (!errstr) {
285 goto error;
286 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100287
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300288 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100289 if (!tmp) {
290 goto error;
291 }
292
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300293 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100294 Py_DECREF(tmp);
295 if (!value) {
296 goto error;
297 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300298 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100299
300error:
301 Py_XDECREF(type);
302 Py_XDECREF(value);
303 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300304 Py_XDECREF(errstr);
305 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100306}
307
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100309tokenizer_error(Parser *p)
310{
311 if (PyErr_Occurred()) {
312 return -1;
313 }
314
315 const char *msg = NULL;
316 PyObject* errtype = PyExc_SyntaxError;
317 switch (p->tok->done) {
318 case E_TOKEN:
319 msg = "invalid token";
320 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100321 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300322 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
323 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100324 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300325 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
326 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300327 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300328 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
329 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100330 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300331 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
332 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100333 case E_INTR:
334 if (!PyErr_Occurred()) {
335 PyErr_SetNone(PyExc_KeyboardInterrupt);
336 }
337 return -1;
338 case E_NOMEM:
339 PyErr_NoMemory();
340 return -1;
341 case E_TABSPACE:
342 errtype = PyExc_TabError;
343 msg = "inconsistent use of tabs and spaces in indentation";
344 break;
345 case E_TOODEEP:
346 errtype = PyExc_IndentationError;
347 msg = "too many levels of indentation";
348 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100349 case E_LINECONT:
350 msg = "unexpected character after line continuation character";
351 break;
352 default:
353 msg = "unknown parsing error";
354 }
355
356 PyErr_Format(errtype, msg);
357 // There is no reliable column information for this error
358 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
359
360 return -1;
361}
362
363void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300364_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
365{
366 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100367 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300368 if (t->col_offset == -1) {
369 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
370 intptr_t, int);
371 } else {
372 col_offset = t->col_offset + 1;
373 }
374
375 va_list va;
376 va_start(va, errmsg);
377 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
378 col_offset, errmsg, va);
379 va_end(va);
380
381 return NULL;
382}
383
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300384void *
385_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100386 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300387 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100388{
389 PyObject *value = NULL;
390 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300391 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100392 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300393 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100394
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300395 if (p->start_rule == Py_fstring_input) {
396 const char *fstring_msg = "f-string: ";
397 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
398
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300399 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300400 if (!new_errmsg) {
401 return (void *) PyErr_NoMemory();
402 }
403
404 // Copy both strings into new buffer
405 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
406 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
407 new_errmsg[len] = 0;
408 errmsg = new_errmsg;
409 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100410 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100411 if (!errstr) {
412 goto error;
413 }
414
415 if (p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300416 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100417 }
418
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300419 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100420 Py_ssize_t size = p->tok->inp - p->tok->buf;
Pablo Galindobcc30362020-05-14 21:11:48 +0100421 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300422 if (!error_line) {
423 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300424 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100425 }
426
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300427 if (p->start_rule == Py_fstring_input) {
428 col_offset -= p->starting_col_offset;
429 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100430 Py_ssize_t col_number = col_offset;
431
432 if (p->tok->encoding != NULL) {
433 col_number = byte_offset_to_character_offset(error_line, col_offset);
434 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300435
436 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100437 if (!tmp) {
438 goto error;
439 }
440 value = PyTuple_Pack(2, errstr, tmp);
441 Py_DECREF(tmp);
442 if (!value) {
443 goto error;
444 }
445 PyErr_SetObject(errtype, value);
446
447 Py_DECREF(errstr);
448 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300449 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300450 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300451 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100452 return NULL;
453
454error:
455 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300456 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300457 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300458 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300459 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100460 return NULL;
461}
462
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100463#if 0
464static const char *
465token_name(int type)
466{
467 if (0 <= type && type <= N_TOKENS) {
468 return _PyParser_TokenNames[type];
469 }
470 return "<Huh?>";
471}
472#endif
473
474// Here, mark is the start of the node, while p->mark is the end.
475// If node==NULL, they should be the same.
476int
477_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
478{
479 // Insert in front
480 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
481 if (m == NULL) {
482 return -1;
483 }
484 m->type = type;
485 m->node = node;
486 m->mark = p->mark;
487 m->next = p->tokens[mark]->memo;
488 p->tokens[mark]->memo = m;
489 return 0;
490}
491
492// Like _PyPegen_insert_memo(), but updates an existing node if found.
493int
494_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
495{
496 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
497 if (m->type == type) {
498 // Update existing node.
499 m->node = node;
500 m->mark = p->mark;
501 return 0;
502 }
503 }
504 // Insert new node.
505 return _PyPegen_insert_memo(p, mark, type, node);
506}
507
508// Return dummy NAME.
509void *
510_PyPegen_dummy_name(Parser *p, ...)
511{
512 static void *cache = NULL;
513
514 if (cache != NULL) {
515 return cache;
516 }
517
518 PyObject *id = _create_dummy_identifier(p);
519 if (!id) {
520 return NULL;
521 }
522 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
523 return cache;
524}
525
526static int
527_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
528{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300529 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100530 if (name_len >= p->n_keyword_lists ||
531 p->keywords[name_len] == NULL ||
532 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100533 return NAME;
534 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100535 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100536 if (strncmp(k->str, name, name_len) == 0) {
537 return k->type;
538 }
539 }
540 return NAME;
541}
542
Guido van Rossumc001c092020-04-30 12:12:19 -0700543static int
544growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
545 assert(initial_size > 0);
546 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
547 arr->size = initial_size;
548 arr->num_items = 0;
549
550 return arr->items != NULL;
551}
552
553static int
554growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
555 if (arr->num_items >= arr->size) {
556 size_t new_size = arr->size * 2;
557 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
558 if (!new_items_array) {
559 return 0;
560 }
561 arr->items = new_items_array;
562 arr->size = new_size;
563 }
564
565 arr->items[arr->num_items].lineno = lineno;
566 arr->items[arr->num_items].comment = comment; // Take ownership
567 arr->num_items++;
568 return 1;
569}
570
571static void
572growable_comment_array_deallocate(growable_comment_array *arr) {
573 for (unsigned i = 0; i < arr->num_items; i++) {
574 PyMem_Free(arr->items[i].comment);
575 }
576 PyMem_Free(arr->items);
577}
578
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100579int
580_PyPegen_fill_token(Parser *p)
581{
Pablo Galindofb61c422020-06-15 14:23:43 +0100582 const char *start;
583 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100584 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700585
586 // Record and skip '# type: ignore' comments
587 while (type == TYPE_IGNORE) {
588 Py_ssize_t len = end - start;
589 char *tag = PyMem_Malloc(len + 1);
590 if (tag == NULL) {
591 PyErr_NoMemory();
592 return -1;
593 }
594 strncpy(tag, start, len);
595 tag[len] = '\0';
596 // Ownership of tag passes to the growable array
597 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
598 PyErr_NoMemory();
599 return -1;
600 }
601 type = PyTokenizer_Get(p->tok, &start, &end);
602 }
603
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100604 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
605 type = NEWLINE; /* Add an extra newline */
606 p->parsing_started = 0;
607
Pablo Galindob94dbd72020-04-27 18:35:58 +0100608 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100609 p->tok->pendin = -p->tok->indent;
610 p->tok->indent = 0;
611 }
612 }
613 else {
614 p->parsing_started = 1;
615 }
616
617 if (p->fill == p->size) {
618 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300619 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
620 if (new_tokens == NULL) {
621 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100622 return -1;
623 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100624 p->tokens = new_tokens;
625
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100626 for (int i = p->size; i < newsize; i++) {
627 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300628 if (p->tokens[i] == NULL) {
629 p->size = i; // Needed, in order to cleanup correctly after parser fails
630 PyErr_NoMemory();
631 return -1;
632 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100633 memset(p->tokens[i], '\0', sizeof(Token));
634 }
635 p->size = newsize;
636 }
637
638 Token *t = p->tokens[p->fill];
639 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
640 t->bytes = PyBytes_FromStringAndSize(start, end - start);
641 if (t->bytes == NULL) {
642 return -1;
643 }
644 PyArena_AddPyObject(p->arena, t->bytes);
645
646 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
647 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100648 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100649 int col_offset = -1;
650 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100651 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100652 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100653 }
654 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100655 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100656 }
657
658 t->lineno = p->starting_lineno + lineno;
659 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
660 t->end_lineno = p->starting_lineno + end_lineno;
661 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
662
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100663 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300664
665 if (type == ERRORTOKEN) {
666 if (p->tok->done == E_DECODE) {
667 return raise_decode_error(p);
668 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100669 return tokenizer_error(p);
670
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300671 }
672
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100673 return 0;
674}
675
676// Instrumentation to count the effectiveness of memoization.
677// The array counts the number of tokens skipped by memoization,
678// indexed by type.
679
680#define NSTATISTICS 2000
681static long memo_statistics[NSTATISTICS];
682
683void
684_PyPegen_clear_memo_statistics()
685{
686 for (int i = 0; i < NSTATISTICS; i++) {
687 memo_statistics[i] = 0;
688 }
689}
690
691PyObject *
692_PyPegen_get_memo_statistics()
693{
694 PyObject *ret = PyList_New(NSTATISTICS);
695 if (ret == NULL) {
696 return NULL;
697 }
698 for (int i = 0; i < NSTATISTICS; i++) {
699 PyObject *value = PyLong_FromLong(memo_statistics[i]);
700 if (value == NULL) {
701 Py_DECREF(ret);
702 return NULL;
703 }
704 // PyList_SetItem borrows a reference to value.
705 if (PyList_SetItem(ret, i, value) < 0) {
706 Py_DECREF(ret);
707 return NULL;
708 }
709 }
710 return ret;
711}
712
713int // bool
714_PyPegen_is_memoized(Parser *p, int type, void *pres)
715{
716 if (p->mark == p->fill) {
717 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300718 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100719 return -1;
720 }
721 }
722
723 Token *t = p->tokens[p->mark];
724
725 for (Memo *m = t->memo; m != NULL; m = m->next) {
726 if (m->type == type) {
727 if (0 <= type && type < NSTATISTICS) {
728 long count = m->mark - p->mark;
729 // A memoized negative result counts for one.
730 if (count <= 0) {
731 count = 1;
732 }
733 memo_statistics[type] += count;
734 }
735 p->mark = m->mark;
736 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100737 return 1;
738 }
739 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100740 return 0;
741}
742
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100743
744int
745_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
746{
747 int mark = p->mark;
748 void *res = func(p);
749 p->mark = mark;
750 return (res != NULL) == positive;
751}
752
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100753int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100754_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
755{
756 int mark = p->mark;
757 void *res = func(p, arg);
758 p->mark = mark;
759 return (res != NULL) == positive;
760}
761
762int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100763_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
764{
765 int mark = p->mark;
766 void *res = func(p, arg);
767 p->mark = mark;
768 return (res != NULL) == positive;
769}
770
771int
772_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
773{
774 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100775 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100776 p->mark = mark;
777 return (res != NULL) == positive;
778}
779
780Token *
781_PyPegen_expect_token(Parser *p, int type)
782{
783 if (p->mark == p->fill) {
784 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300785 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100786 return NULL;
787 }
788 }
789 Token *t = p->tokens[p->mark];
790 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100791 return NULL;
792 }
793 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100794 return t;
795}
796
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700797expr_ty
798_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
799{
800 if (p->mark == p->fill) {
801 if (_PyPegen_fill_token(p) < 0) {
802 p->error_indicator = 1;
803 return NULL;
804 }
805 }
806 Token *t = p->tokens[p->mark];
807 if (t->type != NAME) {
808 return NULL;
809 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300810 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700811 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300812 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700813 return NULL;
814 }
815 if (strcmp(s, keyword) != 0) {
816 return NULL;
817 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300818 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700819}
820
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100821Token *
822_PyPegen_get_last_nonnwhitespace_token(Parser *p)
823{
824 assert(p->mark >= 0);
825 Token *token = NULL;
826 for (int m = p->mark - 1; m >= 0; m--) {
827 token = p->tokens[m];
828 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
829 break;
830 }
831 }
832 return token;
833}
834
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100835expr_ty
836_PyPegen_name_token(Parser *p)
837{
838 Token *t = _PyPegen_expect_token(p, NAME);
839 if (t == NULL) {
840 return NULL;
841 }
842 char* s = PyBytes_AsString(t->bytes);
843 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300844 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100845 return NULL;
846 }
847 PyObject *id = _PyPegen_new_identifier(p, s);
848 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300849 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100850 return NULL;
851 }
852 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
853 p->arena);
854}
855
856void *
857_PyPegen_string_token(Parser *p)
858{
859 return _PyPegen_expect_token(p, STRING);
860}
861
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100862static PyObject *
863parsenumber_raw(const char *s)
864{
865 const char *end;
866 long x;
867 double dx;
868 Py_complex compl;
869 int imflag;
870
871 assert(s != NULL);
872 errno = 0;
873 end = s + strlen(s) - 1;
874 imflag = *end == 'j' || *end == 'J';
875 if (s[0] == '0') {
876 x = (long)PyOS_strtoul(s, (char **)&end, 0);
877 if (x < 0 && errno == 0) {
878 return PyLong_FromString(s, (char **)0, 0);
879 }
880 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100881 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100882 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100883 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100884 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100885 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100886 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100887 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100888 return PyLong_FromLong(x);
889 }
890 /* XXX Huge floats may silently fail */
891 if (imflag) {
892 compl.real = 0.;
893 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100894 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100895 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100896 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100897 return PyComplex_FromCComplex(compl);
898 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100899 dx = PyOS_string_to_double(s, NULL, NULL);
900 if (dx == -1.0 && PyErr_Occurred()) {
901 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100902 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100903 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100904}
905
906static PyObject *
907parsenumber(const char *s)
908{
Pablo Galindofb61c422020-06-15 14:23:43 +0100909 char *dup;
910 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100911 PyObject *res = NULL;
912
913 assert(s != NULL);
914
915 if (strchr(s, '_') == NULL) {
916 return parsenumber_raw(s);
917 }
918 /* Create a duplicate without underscores. */
919 dup = PyMem_Malloc(strlen(s) + 1);
920 if (dup == NULL) {
921 return PyErr_NoMemory();
922 }
923 end = dup;
924 for (; *s; s++) {
925 if (*s != '_') {
926 *end++ = *s;
927 }
928 }
929 *end = '\0';
930 res = parsenumber_raw(dup);
931 PyMem_Free(dup);
932 return res;
933}
934
935expr_ty
936_PyPegen_number_token(Parser *p)
937{
938 Token *t = _PyPegen_expect_token(p, NUMBER);
939 if (t == NULL) {
940 return NULL;
941 }
942
943 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100944 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300945 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100946 return NULL;
947 }
948
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300949 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
950 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700951 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300952 "in Python 3.6 and greater");
953 }
954
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100955 PyObject *c = parsenumber(num_raw);
956
957 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300958 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100959 return NULL;
960 }
961
962 if (PyArena_AddPyObject(p->arena, c) < 0) {
963 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300964 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100965 return NULL;
966 }
967
968 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
969 p->arena);
970}
971
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300972static int // bool
973newline_in_string(Parser *p, const char *cur)
974{
Pablo Galindo2e6593d2020-06-06 00:52:27 +0100975 for (const char *c = cur; c >= p->tok->buf; c--) {
976 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300977 return 1;
978 }
979 }
980 return 0;
981}
982
983/* Check that the source for a single input statement really is a single
984 statement by looking at what is left in the buffer after parsing.
985 Trailing whitespace and comments are OK. */
986static int // bool
987bad_single_statement(Parser *p)
988{
989 const char *cur = strchr(p->tok->buf, '\n');
990
991 /* Newlines are allowed if preceded by a line continuation character
992 or if they appear inside a string. */
Pablo Galindoe68c6782020-10-25 23:03:41 +0000993 if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
994 || newline_in_string(p, cur)) {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300995 return 0;
996 }
997 char c = *cur;
998
999 for (;;) {
1000 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
1001 c = *++cur;
1002 }
1003
1004 if (!c) {
1005 return 0;
1006 }
1007
1008 if (c != '#') {
1009 return 1;
1010 }
1011
1012 /* Suck up comment. */
1013 while (c && c != '\n') {
1014 c = *++cur;
1015 }
1016 }
1017}
1018
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001019void
1020_PyPegen_Parser_Free(Parser *p)
1021{
1022 Py_XDECREF(p->normalize);
1023 for (int i = 0; i < p->size; i++) {
1024 PyMem_Free(p->tokens[i]);
1025 }
1026 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001027 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001028 PyMem_Free(p);
1029}
1030
Pablo Galindo2b74c832020-04-27 18:02:07 +01001031static int
1032compute_parser_flags(PyCompilerFlags *flags)
1033{
1034 int parser_flags = 0;
1035 if (!flags) {
1036 return 0;
1037 }
1038 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1039 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1040 }
1041 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1042 parser_flags |= PyPARSE_IGNORE_COOKIE;
1043 }
1044 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1045 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1046 }
1047 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1048 parser_flags |= PyPARSE_TYPE_COMMENTS;
1049 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001050 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001051 parser_flags |= PyPARSE_ASYNC_HACKS;
1052 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001053 return parser_flags;
1054}
1055
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001056Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001057_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001058 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001059{
1060 Parser *p = PyMem_Malloc(sizeof(Parser));
1061 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001062 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001063 }
1064 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001065 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1066 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001067 p->tok = tok;
1068 p->keywords = NULL;
1069 p->n_keyword_lists = -1;
1070 p->tokens = PyMem_Malloc(sizeof(Token *));
1071 if (!p->tokens) {
1072 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001073 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001074 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001075 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001076 if (!p->tokens) {
1077 PyMem_Free(p->tokens);
1078 PyMem_Free(p);
1079 return (Parser *) PyErr_NoMemory();
1080 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001081 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1082 PyMem_Free(p->tokens[0]);
1083 PyMem_Free(p->tokens);
1084 PyMem_Free(p);
1085 return (Parser *) PyErr_NoMemory();
1086 }
1087
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001088 p->mark = 0;
1089 p->fill = 0;
1090 p->size = 1;
1091
1092 p->errcode = errcode;
1093 p->arena = arena;
1094 p->start_rule = start_rule;
1095 p->parsing_started = 0;
1096 p->normalize = NULL;
1097 p->error_indicator = 0;
1098
1099 p->starting_lineno = 0;
1100 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001101 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001102 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001103 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001104 p->level = 0;
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001105 p->call_invalid_rules = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001106
1107 return p;
1108}
1109
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001110static void
1111reset_parser_state(Parser *p)
1112{
1113 for (int i = 0; i < p->fill; i++) {
1114 p->tokens[i]->memo = NULL;
1115 }
1116 p->mark = 0;
1117 p->call_invalid_rules = 1;
1118}
1119
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001120void *
1121_PyPegen_run_parser(Parser *p)
1122{
1123 void *res = _PyPegen_parse(p);
1124 if (res == NULL) {
Lysandros Nikolaoubca70142020-10-27 00:42:04 +02001125 reset_parser_state(p);
1126 _PyPegen_parse(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001127 if (PyErr_Occurred()) {
1128 return NULL;
1129 }
1130 if (p->fill == 0) {
1131 RAISE_SYNTAX_ERROR("error at start before reading any input");
1132 }
1133 else if (p->tok->done == E_EOF) {
1134 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1135 }
1136 else {
1137 if (p->tokens[p->fill-1]->type == INDENT) {
1138 RAISE_INDENTATION_ERROR("unexpected indent");
1139 }
1140 else if (p->tokens[p->fill-1]->type == DEDENT) {
1141 RAISE_INDENTATION_ERROR("unexpected unindent");
1142 }
1143 else {
1144 RAISE_SYNTAX_ERROR("invalid syntax");
1145 }
1146 }
1147 return NULL;
1148 }
1149
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001150 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1151 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1152 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1153 }
1154
Pablo Galindo13322262020-07-27 23:46:59 +01001155#if defined(Py_DEBUG) && defined(Py_BUILD_CORE)
1156 if (p->start_rule == Py_single_input ||
1157 p->start_rule == Py_file_input ||
1158 p->start_rule == Py_eval_input)
1159 {
Batuhan Taskaya3af4b582020-10-30 14:48:41 +03001160 if (!PyAST_Validate(res)) {
1161 return NULL;
1162 }
Pablo Galindo13322262020-07-27 23:46:59 +01001163 }
1164#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001165 return res;
1166}
1167
1168mod_ty
1169_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1170 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001171 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001172{
1173 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1174 if (tok == NULL) {
1175 if (PyErr_Occurred()) {
1176 raise_tokenizer_init_error(filename_ob);
1177 return NULL;
1178 }
1179 return NULL;
1180 }
1181 // This transfers the ownership to the tokenizer
1182 tok->filename = filename_ob;
1183 Py_INCREF(filename_ob);
1184
1185 // From here on we need to clean up even if there's an error
1186 mod_ty result = NULL;
1187
Pablo Galindo2b74c832020-04-27 18:02:07 +01001188 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001189 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1190 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001191 if (p == NULL) {
1192 goto error;
1193 }
1194
1195 result = _PyPegen_run_parser(p);
1196 _PyPegen_Parser_Free(p);
1197
1198error:
1199 PyTokenizer_Free(tok);
1200 return result;
1201}
1202
1203mod_ty
1204_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001205 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001206{
1207 FILE *fp = fopen(filename, "rb");
1208 if (fp == NULL) {
1209 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1210 return NULL;
1211 }
1212
1213 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001214 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001215
1216 fclose(fp);
1217 return result;
1218}
1219
1220mod_ty
1221_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001222 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001223{
1224 int exec_input = start_rule == Py_file_input;
1225
1226 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001227 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001228 tok = PyTokenizer_FromUTF8(str, exec_input);
1229 } else {
1230 tok = PyTokenizer_FromString(str, exec_input);
1231 }
1232 if (tok == NULL) {
1233 if (PyErr_Occurred()) {
1234 raise_tokenizer_init_error(filename_ob);
1235 }
1236 return NULL;
1237 }
1238 // This transfers the ownership to the tokenizer
1239 tok->filename = filename_ob;
1240 Py_INCREF(filename_ob);
1241
1242 // We need to clear up from here on
1243 mod_ty result = NULL;
1244
Pablo Galindo2b74c832020-04-27 18:02:07 +01001245 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001246 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1247 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001248 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1249 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001250 if (p == NULL) {
1251 goto error;
1252 }
1253
1254 result = _PyPegen_run_parser(p);
1255 _PyPegen_Parser_Free(p);
1256
1257error:
1258 PyTokenizer_Free(tok);
1259 return result;
1260}
1261
Pablo Galindoa5634c42020-09-16 19:42:00 +01001262asdl_stmt_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001263_PyPegen_interactive_exit(Parser *p)
1264{
1265 if (p->errcode) {
1266 *(p->errcode) = E_EOF;
1267 }
1268 return NULL;
1269}
1270
1271/* Creates a single-element asdl_seq* that contains a */
1272asdl_seq *
1273_PyPegen_singleton_seq(Parser *p, void *a)
1274{
1275 assert(a != NULL);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001276 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001277 if (!seq) {
1278 return NULL;
1279 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001280 asdl_seq_SET_UNTYPED(seq, 0, a);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001281 return seq;
1282}
1283
1284/* Creates a copy of seq and prepends a to it */
1285asdl_seq *
1286_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1287{
1288 assert(a != NULL);
1289 if (!seq) {
1290 return _PyPegen_singleton_seq(p, a);
1291 }
1292
Pablo Galindoa5634c42020-09-16 19:42:00 +01001293 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 +01001294 if (!new_seq) {
1295 return NULL;
1296 }
1297
Pablo Galindoa5634c42020-09-16 19:42:00 +01001298 asdl_seq_SET_UNTYPED(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001299 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001300 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001301 }
1302 return new_seq;
1303}
1304
Guido van Rossumc001c092020-04-30 12:12:19 -07001305/* Creates a copy of seq and appends a to it */
1306asdl_seq *
1307_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1308{
1309 assert(a != NULL);
1310 if (!seq) {
1311 return _PyPegen_singleton_seq(p, a);
1312 }
1313
Pablo Galindoa5634c42020-09-16 19:42:00 +01001314 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 -07001315 if (!new_seq) {
1316 return NULL;
1317 }
1318
1319 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001320 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
Guido van Rossumc001c092020-04-30 12:12:19 -07001321 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001322 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
Guido van Rossumc001c092020-04-30 12:12:19 -07001323 return new_seq;
1324}
1325
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001326static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001327_get_flattened_seq_size(asdl_seq *seqs)
1328{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001329 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001330 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001331 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001332 size += asdl_seq_LEN(inner_seq);
1333 }
1334 return size;
1335}
1336
1337/* Flattens an asdl_seq* of asdl_seq*s */
1338asdl_seq *
1339_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1340{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001341 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001342 assert(flattened_seq_size > 0);
1343
Pablo Galindoa5634c42020-09-16 19:42:00 +01001344 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001345 if (!flattened_seq) {
1346 return NULL;
1347 }
1348
1349 int flattened_seq_idx = 0;
1350 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001351 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001352 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001353 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001354 }
1355 }
1356 assert(flattened_seq_idx == flattened_seq_size);
1357
1358 return flattened_seq;
1359}
1360
1361/* Creates a new name of the form <first_name>.<second_name> */
1362expr_ty
1363_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1364{
1365 assert(first_name != NULL && second_name != NULL);
1366 PyObject *first_identifier = first_name->v.Name.id;
1367 PyObject *second_identifier = second_name->v.Name.id;
1368
1369 if (PyUnicode_READY(first_identifier) == -1) {
1370 return NULL;
1371 }
1372 if (PyUnicode_READY(second_identifier) == -1) {
1373 return NULL;
1374 }
1375 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1376 if (!first_str) {
1377 return NULL;
1378 }
1379 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1380 if (!second_str) {
1381 return NULL;
1382 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001383 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001384
1385 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1386 if (!str) {
1387 return NULL;
1388 }
1389
1390 char *s = PyBytes_AS_STRING(str);
1391 if (!s) {
1392 return NULL;
1393 }
1394
1395 strcpy(s, first_str);
1396 s += strlen(first_str);
1397 *s++ = '.';
1398 strcpy(s, second_str);
1399 s += strlen(second_str);
1400 *s = '\0';
1401
1402 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1403 Py_DECREF(str);
1404 if (!uni) {
1405 return NULL;
1406 }
1407 PyUnicode_InternInPlace(&uni);
1408 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1409 Py_DECREF(uni);
1410 return NULL;
1411 }
1412
1413 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1414}
1415
1416/* Counts the total number of dots in seq's tokens */
1417int
1418_PyPegen_seq_count_dots(asdl_seq *seq)
1419{
1420 int number_of_dots = 0;
1421 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001422 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001423 switch (current_expr->type) {
1424 case ELLIPSIS:
1425 number_of_dots += 3;
1426 break;
1427 case DOT:
1428 number_of_dots += 1;
1429 break;
1430 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001431 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001432 }
1433 }
1434
1435 return number_of_dots;
1436}
1437
1438/* Creates an alias with '*' as the identifier name */
1439alias_ty
1440_PyPegen_alias_for_star(Parser *p)
1441{
1442 PyObject *str = PyUnicode_InternFromString("*");
1443 if (!str) {
1444 return NULL;
1445 }
1446 if (PyArena_AddPyObject(p->arena, str) < 0) {
1447 Py_DECREF(str);
1448 return NULL;
1449 }
1450 return alias(str, NULL, p->arena);
1451}
1452
1453/* Creates a new asdl_seq* with the identifiers of all the names in seq */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001454asdl_identifier_seq *
1455_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001456{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001457 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001458 assert(len > 0);
1459
Pablo Galindoa5634c42020-09-16 19:42:00 +01001460 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001461 if (!new_seq) {
1462 return NULL;
1463 }
1464 for (Py_ssize_t i = 0; i < len; i++) {
1465 expr_ty e = asdl_seq_GET(seq, i);
1466 asdl_seq_SET(new_seq, i, e->v.Name.id);
1467 }
1468 return new_seq;
1469}
1470
1471/* Constructs a CmpopExprPair */
1472CmpopExprPair *
1473_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1474{
1475 assert(expr != NULL);
1476 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1477 if (!a) {
1478 return NULL;
1479 }
1480 a->cmpop = cmpop;
1481 a->expr = expr;
1482 return a;
1483}
1484
1485asdl_int_seq *
1486_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1487{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001488 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001489 assert(len > 0);
1490
1491 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1492 if (!new_seq) {
1493 return NULL;
1494 }
1495 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001496 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001497 asdl_seq_SET(new_seq, i, pair->cmpop);
1498 }
1499 return new_seq;
1500}
1501
Pablo Galindoa5634c42020-09-16 19:42:00 +01001502asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001503_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1504{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001505 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001506 assert(len > 0);
1507
Pablo Galindoa5634c42020-09-16 19:42:00 +01001508 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001509 if (!new_seq) {
1510 return NULL;
1511 }
1512 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001513 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001514 asdl_seq_SET(new_seq, i, pair->expr);
1515 }
1516 return new_seq;
1517}
1518
1519/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001520static asdl_expr_seq *
1521_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001522{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001523 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001524 if (len == 0) {
1525 return NULL;
1526 }
1527
Pablo Galindoa5634c42020-09-16 19:42:00 +01001528 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001529 if (!new_seq) {
1530 return NULL;
1531 }
1532 for (Py_ssize_t i = 0; i < len; i++) {
1533 expr_ty e = asdl_seq_GET(seq, i);
1534 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1535 }
1536 return new_seq;
1537}
1538
1539static expr_ty
1540_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1541{
1542 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1543}
1544
1545static expr_ty
1546_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1547{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001548 return _Py_Tuple(
1549 _set_seq_context(p, e->v.Tuple.elts, ctx),
1550 ctx,
1551 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001552}
1553
1554static expr_ty
1555_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1556{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001557 return _Py_List(
1558 _set_seq_context(p, e->v.List.elts, ctx),
1559 ctx,
1560 EXTRA_EXPR(e, e));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001561}
1562
1563static expr_ty
1564_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1565{
1566 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1567}
1568
1569static expr_ty
1570_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1571{
1572 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1573}
1574
1575static expr_ty
1576_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1577{
1578 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1579}
1580
1581/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1582expr_ty
1583_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1584{
1585 assert(expr != NULL);
1586
1587 expr_ty new = NULL;
1588 switch (expr->kind) {
1589 case Name_kind:
1590 new = _set_name_context(p, expr, ctx);
1591 break;
1592 case Tuple_kind:
1593 new = _set_tuple_context(p, expr, ctx);
1594 break;
1595 case List_kind:
1596 new = _set_list_context(p, expr, ctx);
1597 break;
1598 case Subscript_kind:
1599 new = _set_subscript_context(p, expr, ctx);
1600 break;
1601 case Attribute_kind:
1602 new = _set_attribute_context(p, expr, ctx);
1603 break;
1604 case Starred_kind:
1605 new = _set_starred_context(p, expr, ctx);
1606 break;
1607 default:
1608 new = expr;
1609 }
1610 return new;
1611}
1612
1613/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1614KeyValuePair *
1615_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1616{
1617 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1618 if (!a) {
1619 return NULL;
1620 }
1621 a->key = key;
1622 a->value = value;
1623 return a;
1624}
1625
1626/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001627asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001628_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1629{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001630 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001631 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001632 if (!new_seq) {
1633 return NULL;
1634 }
1635 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001636 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001637 asdl_seq_SET(new_seq, i, pair->key);
1638 }
1639 return new_seq;
1640}
1641
1642/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001643asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001644_PyPegen_get_values(Parser *p, asdl_seq *seq)
1645{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001646 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001647 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001648 if (!new_seq) {
1649 return NULL;
1650 }
1651 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001652 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001653 asdl_seq_SET(new_seq, i, pair->value);
1654 }
1655 return new_seq;
1656}
1657
1658/* Constructs a NameDefaultPair */
1659NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001660_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001661{
1662 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1663 if (!a) {
1664 return NULL;
1665 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001666 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001667 a->value = value;
1668 return a;
1669}
1670
1671/* Constructs a SlashWithDefault */
1672SlashWithDefault *
Pablo Galindoa5634c42020-09-16 19:42:00 +01001673_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001674{
1675 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1676 if (!a) {
1677 return NULL;
1678 }
1679 a->plain_names = plain_names;
1680 a->names_with_defaults = names_with_defaults;
1681 return a;
1682}
1683
1684/* Constructs a StarEtc */
1685StarEtc *
1686_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1687{
1688 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1689 if (!a) {
1690 return NULL;
1691 }
1692 a->vararg = vararg;
1693 a->kwonlyargs = kwonlyargs;
1694 a->kwarg = kwarg;
1695 return a;
1696}
1697
1698asdl_seq *
1699_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1700{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001701 Py_ssize_t first_len = asdl_seq_LEN(a);
1702 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001703 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001704 if (!new_seq) {
1705 return NULL;
1706 }
1707
1708 int k = 0;
1709 for (Py_ssize_t i = 0; i < first_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001710 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001711 }
1712 for (Py_ssize_t i = 0; i < second_len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001713 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001714 }
1715
1716 return new_seq;
1717}
1718
Pablo Galindoa5634c42020-09-16 19:42:00 +01001719static asdl_arg_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001720_get_names(Parser *p, asdl_seq *names_with_defaults)
1721{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001722 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001723 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001724 if (!seq) {
1725 return NULL;
1726 }
1727 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001728 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001729 asdl_seq_SET(seq, i, pair->arg);
1730 }
1731 return seq;
1732}
1733
Pablo Galindoa5634c42020-09-16 19:42:00 +01001734static asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001735_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1736{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001737 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoa5634c42020-09-16 19:42:00 +01001738 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001739 if (!seq) {
1740 return NULL;
1741 }
1742 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001743 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001744 asdl_seq_SET(seq, i, pair->value);
1745 }
1746 return seq;
1747}
1748
1749/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1750arguments_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001751_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
1752 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001753 asdl_seq *names_with_default, StarEtc *star_etc)
1754{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001755 asdl_arg_seq *posonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001756 if (slash_without_default != NULL) {
1757 posonlyargs = slash_without_default;
1758 }
1759 else if (slash_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001760 asdl_arg_seq *slash_with_default_names =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001761 _get_names(p, slash_with_default->names_with_defaults);
1762 if (!slash_with_default_names) {
1763 return NULL;
1764 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001765 posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1766 p,
1767 (asdl_seq*)slash_with_default->plain_names,
1768 (asdl_seq*)slash_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001769 if (!posonlyargs) {
1770 return NULL;
1771 }
1772 }
1773 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001774 posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001775 if (!posonlyargs) {
1776 return NULL;
1777 }
1778 }
1779
Pablo Galindoa5634c42020-09-16 19:42:00 +01001780 asdl_arg_seq *posargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001781 if (plain_names != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001782 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001783 if (!names_with_default_names) {
1784 return NULL;
1785 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001786 posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
1787 p,
1788 (asdl_seq*)plain_names,
1789 (asdl_seq*)names_with_default_names);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001790 if (!posargs) {
1791 return NULL;
1792 }
1793 }
1794 else if (plain_names == NULL && names_with_default != NULL) {
1795 posargs = _get_names(p, names_with_default);
1796 if (!posargs) {
1797 return NULL;
1798 }
1799 }
1800 else if (plain_names != NULL && names_with_default == NULL) {
1801 posargs = plain_names;
1802 }
1803 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001804 posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001805 if (!posargs) {
1806 return NULL;
1807 }
1808 }
1809
Pablo Galindoa5634c42020-09-16 19:42:00 +01001810 asdl_expr_seq *posdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001811 if (slash_with_default != NULL && names_with_default != NULL) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001812 asdl_expr_seq *slash_with_default_values =
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001813 _get_defaults(p, slash_with_default->names_with_defaults);
1814 if (!slash_with_default_values) {
1815 return NULL;
1816 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001817 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001818 if (!names_with_default_values) {
1819 return NULL;
1820 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001821 posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
1822 p,
1823 (asdl_seq*)slash_with_default_values,
1824 (asdl_seq*)names_with_default_values);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001825 if (!posdefaults) {
1826 return NULL;
1827 }
1828 }
1829 else if (slash_with_default == NULL && names_with_default != NULL) {
1830 posdefaults = _get_defaults(p, names_with_default);
1831 if (!posdefaults) {
1832 return NULL;
1833 }
1834 }
1835 else if (slash_with_default != NULL && names_with_default == NULL) {
1836 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1837 if (!posdefaults) {
1838 return NULL;
1839 }
1840 }
1841 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001842 posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001843 if (!posdefaults) {
1844 return NULL;
1845 }
1846 }
1847
1848 arg_ty vararg = NULL;
1849 if (star_etc != NULL && star_etc->vararg != NULL) {
1850 vararg = star_etc->vararg;
1851 }
1852
Pablo Galindoa5634c42020-09-16 19:42:00 +01001853 asdl_arg_seq *kwonlyargs;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001854 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1855 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1856 if (!kwonlyargs) {
1857 return NULL;
1858 }
1859 }
1860 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001861 kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001862 if (!kwonlyargs) {
1863 return NULL;
1864 }
1865 }
1866
Pablo Galindoa5634c42020-09-16 19:42:00 +01001867 asdl_expr_seq *kwdefaults;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001868 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1869 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1870 if (!kwdefaults) {
1871 return NULL;
1872 }
1873 }
1874 else {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001875 kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001876 if (!kwdefaults) {
1877 return NULL;
1878 }
1879 }
1880
1881 arg_ty kwarg = NULL;
1882 if (star_etc != NULL && star_etc->kwarg != NULL) {
1883 kwarg = star_etc->kwarg;
1884 }
1885
1886 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1887 posdefaults, p->arena);
1888}
1889
1890/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1891 * arguments. */
1892arguments_ty
1893_PyPegen_empty_arguments(Parser *p)
1894{
Pablo Galindoa5634c42020-09-16 19:42:00 +01001895 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001896 if (!posonlyargs) {
1897 return NULL;
1898 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001899 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001900 if (!posargs) {
1901 return NULL;
1902 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001903 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001904 if (!posdefaults) {
1905 return NULL;
1906 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001907 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001908 if (!kwonlyargs) {
1909 return NULL;
1910 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01001911 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001912 if (!kwdefaults) {
1913 return NULL;
1914 }
1915
Batuhan Taskaya02a16032020-10-10 20:14:59 +03001916 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, posdefaults,
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001917 p->arena);
1918}
1919
1920/* Encapsulates the value of an operator_ty into an AugOperator struct */
1921AugOperator *
1922_PyPegen_augoperator(Parser *p, operator_ty kind)
1923{
1924 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1925 if (!a) {
1926 return NULL;
1927 }
1928 a->kind = kind;
1929 return a;
1930}
1931
1932/* Construct a FunctionDef equivalent to function_def, but with decorators */
1933stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001934_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001935{
1936 assert(function_def != NULL);
1937 if (function_def->kind == AsyncFunctionDef_kind) {
1938 return _Py_AsyncFunctionDef(
1939 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1940 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1941 function_def->v.FunctionDef.type_comment, function_def->lineno,
1942 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1943 p->arena);
1944 }
1945
1946 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1947 function_def->v.FunctionDef.body, decorators,
1948 function_def->v.FunctionDef.returns,
1949 function_def->v.FunctionDef.type_comment, function_def->lineno,
1950 function_def->col_offset, function_def->end_lineno,
1951 function_def->end_col_offset, p->arena);
1952}
1953
1954/* Construct a ClassDef equivalent to class_def, but with decorators */
1955stmt_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01001956_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001957{
1958 assert(class_def != NULL);
1959 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1960 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1961 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1962 class_def->end_col_offset, p->arena);
1963}
1964
1965/* Construct a KeywordOrStarred */
1966KeywordOrStarred *
1967_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1968{
1969 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1970 if (!a) {
1971 return NULL;
1972 }
1973 a->element = element;
1974 a->is_keyword = is_keyword;
1975 return a;
1976}
1977
1978/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1979static int
1980_seq_number_of_starred_exprs(asdl_seq *seq)
1981{
1982 int n = 0;
1983 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01001984 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001985 if (!k->is_keyword) {
1986 n++;
1987 }
1988 }
1989 return n;
1990}
1991
1992/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
Pablo Galindoa5634c42020-09-16 19:42:00 +01001993asdl_expr_seq *
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001994_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1995{
1996 int new_len = _seq_number_of_starred_exprs(kwargs);
1997 if (new_len == 0) {
1998 return NULL;
1999 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002000 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002001 if (!new_seq) {
2002 return NULL;
2003 }
2004
2005 int idx = 0;
2006 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002007 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002008 if (!k->is_keyword) {
2009 asdl_seq_SET(new_seq, idx++, k->element);
2010 }
2011 }
2012 return new_seq;
2013}
2014
2015/* Return a new asdl_seq* with only the keywords in kwargs */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002016asdl_keyword_seq*
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002017_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
2018{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002019 Py_ssize_t len = asdl_seq_LEN(kwargs);
2020 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002021 if (new_len == 0) {
2022 return NULL;
2023 }
Pablo Galindoa5634c42020-09-16 19:42:00 +01002024 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002025 if (!new_seq) {
2026 return NULL;
2027 }
2028
2029 int idx = 0;
2030 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002031 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002032 if (k->is_keyword) {
2033 asdl_seq_SET(new_seq, idx++, k->element);
2034 }
2035 }
2036 return new_seq;
2037}
2038
2039expr_ty
2040_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2041{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002042 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002043 assert(len > 0);
2044
Pablo Galindoa5634c42020-09-16 19:42:00 +01002045 Token *first = asdl_seq_GET_UNTYPED(strings, 0);
2046 Token *last = asdl_seq_GET_UNTYPED(strings, len - 1);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002047
2048 int bytesmode = 0;
2049 PyObject *bytes_str = NULL;
2050
2051 FstringParser state;
2052 _PyPegen_FstringParser_Init(&state);
2053
2054 for (Py_ssize_t i = 0; i < len; i++) {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002055 Token *t = asdl_seq_GET_UNTYPED(strings, i);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002056
2057 int this_bytesmode;
2058 int this_rawmode;
2059 PyObject *s;
2060 const char *fstr;
2061 Py_ssize_t fstrlen = -1;
2062
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002063 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002064 goto error;
2065 }
2066
2067 /* Check that we are not mixing bytes with unicode. */
2068 if (i != 0 && bytesmode != this_bytesmode) {
2069 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2070 Py_XDECREF(s);
2071 goto error;
2072 }
2073 bytesmode = this_bytesmode;
2074
2075 if (fstr != NULL) {
2076 assert(s == NULL && !bytesmode);
2077
2078 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2079 this_rawmode, 0, first, t, last);
2080 if (result < 0) {
2081 goto error;
2082 }
2083 }
2084 else {
2085 /* String or byte string. */
2086 assert(s != NULL && fstr == NULL);
2087 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2088
2089 if (bytesmode) {
2090 if (i == 0) {
2091 bytes_str = s;
2092 }
2093 else {
2094 PyBytes_ConcatAndDel(&bytes_str, s);
2095 if (!bytes_str) {
2096 goto error;
2097 }
2098 }
2099 }
2100 else {
2101 /* This is a regular string. Concatenate it. */
2102 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2103 goto error;
2104 }
2105 }
2106 }
2107 }
2108
2109 if (bytesmode) {
2110 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2111 goto error;
2112 }
2113 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2114 last->end_col_offset, p->arena);
2115 }
2116
2117 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2118
2119error:
2120 Py_XDECREF(bytes_str);
2121 _PyPegen_FstringParser_Dealloc(&state);
2122 if (PyErr_Occurred()) {
2123 raise_decode_error(p);
2124 }
2125 return NULL;
2126}
Guido van Rossumc001c092020-04-30 12:12:19 -07002127
2128mod_ty
Pablo Galindoa5634c42020-09-16 19:42:00 +01002129_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
2130 asdl_type_ignore_seq *type_ignores = NULL;
Guido van Rossumc001c092020-04-30 12:12:19 -07002131 Py_ssize_t num = p->type_ignore_comments.num_items;
2132 if (num > 0) {
2133 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
Pablo Galindoa5634c42020-09-16 19:42:00 +01002134 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
Guido van Rossumc001c092020-04-30 12:12:19 -07002135 if (type_ignores == NULL) {
2136 return NULL;
2137 }
2138 for (int i = 0; i < num; i++) {
2139 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2140 if (tag == NULL) {
2141 return NULL;
2142 }
2143 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2144 if (ti == NULL) {
2145 return NULL;
2146 }
2147 asdl_seq_SET(type_ignores, i, ti);
2148 }
2149 }
2150 return Module(a, type_ignores, p->arena);
2151}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002152
2153// Error reporting helpers
2154
2155expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002156_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002157{
2158 if (e == NULL) {
2159 return NULL;
2160 }
2161
2162#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2163 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2164 for (Py_ssize_t i = 0; i < len; i++) {\
2165 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002166 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002167 if (child != NULL) {\
2168 return child;\
2169 }\
2170 }\
2171 } while (0)
2172
2173 // We only need to visit List and Tuple nodes recursively as those
2174 // are the only ones that can contain valid names in targets when
2175 // they are parsed as expressions. Any other kind of expression
2176 // that is a container (like Sets or Dicts) is directly invalid and
2177 // we don't need to visit it recursively.
2178
2179 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002180 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002181 VISIT_CONTAINER(e, List);
2182 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002183 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002184 VISIT_CONTAINER(e, Tuple);
2185 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002186 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002187 if (targets_type == DEL_TARGETS) {
2188 return e;
2189 }
2190 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2191 case Compare_kind:
2192 // This is needed, because the `a in b` in `for a in b` gets parsed
2193 // as a comparison, and so we need to search the left side of the comparison
2194 // for invalid targets.
2195 if (targets_type == FOR_TARGETS) {
2196 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2197 if (cmpop == In) {
2198 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2199 }
2200 return NULL;
2201 }
2202 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002203 case Name_kind:
2204 case Subscript_kind:
2205 case Attribute_kind:
2206 return NULL;
2207 default:
2208 return e;
2209 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002210}
2211
2212void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2213 int kwarg_unpacking = 0;
2214 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2215 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2216 if (!keyword->arg) {
2217 kwarg_unpacking = 1;
2218 }
2219 }
2220
2221 const char *msg = NULL;
2222 if (kwarg_unpacking) {
2223 msg = "positional argument follows keyword argument unpacking";
2224 } else {
2225 msg = "positional argument follows keyword argument";
2226 }
2227
2228 return RAISE_SYNTAX_ERROR(msg);
2229}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002230
2231void *
2232_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2233{
2234 /* The rule that calls this function is 'args for_if_clauses'.
2235 For the input f(L, x for x in y), L and x are in args and
2236 the for is parsed as a for_if_clause. We have to check if
2237 len <= 1, so that input like dict((a, b) for a, b in x)
2238 gets successfully parsed and then we pass the last
2239 argument (x in the above example) as the location of the
2240 error */
2241 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2242 if (len <= 1) {
2243 return NULL;
2244 }
2245
2246 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2247 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2248 "Generator expression must be parenthesized"
2249 );
2250}
Pablo Galindo4a97b152020-09-02 17:44:19 +01002251
2252
Pablo Galindoa5634c42020-09-16 19:42:00 +01002253expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
Pablo Galindo315a61f2020-09-03 15:29:32 +01002254 int lineno, int col_offset, int end_lineno,
2255 int end_col_offset, PyArena *arena) {
Pablo Galindo4a97b152020-09-02 17:44:19 +01002256 Py_ssize_t args_len = asdl_seq_LEN(a);
2257 Py_ssize_t total_len = args_len;
2258
2259 if (b == NULL) {
Pablo Galindo315a61f2020-09-03 15:29:32 +01002260 return _Py_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2261 end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002262
2263 }
2264
Pablo Galindoa5634c42020-09-16 19:42:00 +01002265 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2266 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002267
2268 if (starreds) {
2269 total_len += asdl_seq_LEN(starreds);
2270 }
2271
Pablo Galindoa5634c42020-09-16 19:42:00 +01002272 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002273
2274 Py_ssize_t i = 0;
2275 for (i = 0; i < args_len; i++) {
2276 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2277 }
2278 for (; i < total_len; i++) {
2279 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2280 }
2281
Pablo Galindo315a61f2020-09-03 15:29:32 +01002282 return _Py_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2283 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo4a97b152020-09-02 17:44:19 +01002284}