blob: 2c435fb367836e49a8180351ab9add03c6a99f2c [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
3#include "../tokenizer.h"
4
5#include "pegen.h"
6#include "parse_string.h"
Pablo Galindobc2c0e92020-07-28 00:12:31 +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 Galindo30b59fd2020-06-15 15:08:00 +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 Galindo30b59fd2020-06-15 15:08:00 +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
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700144byte_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 }
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700150 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{
Miss Islington (bot)8df4f392020-06-08 02:22:06 -0700163 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 Galindo30b59fd2020-06-15 15:08:00 +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 Galindo30b59fd2020-06-15 15:08:00 +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];
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700367 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,
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700386 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
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700395 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
399 char *new_errmsg = PyMem_RawMalloc(len + 1); // Lengths of both strings plus NULL character
400 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) {
Miss Islington (bot)c9f83c12020-06-20 10:35:03 -0700416 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
Pablo Galindodab533d2020-06-28 01:15:28 +0100427 if (p->start_rule == Py_fstring_input) {
428 col_offset -= p->starting_col_offset;
429 }
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700430 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);
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700449 if (p->start_rule == Py_fstring_input) {
450 PyMem_RawFree((void *)errmsg);
451 }
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);
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700457 if (p->start_rule == Py_fstring_input) {
458 PyMem_RawFree((void *)errmsg);
459 }
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{
Miss Islington (bot)edeaf612020-07-06 16:35:10 -0700529 assert(name_len > 0);
Pablo Galindo54f115d2020-07-06 20:29:59 +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 Galindo54f115d2020-07-06 20:29:59 +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 Galindo30b59fd2020-06-15 15:08:00 +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 Galindo30b59fd2020-06-15 15:08:00 +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 Galindo30b59fd2020-06-15 15:08:00 +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 Galindo30b59fd2020-06-15 15:08:00 +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 +0100743int
744_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
745{
746 int mark = p->mark;
747 void *res = func(p);
748 p->mark = mark;
749 return (res != NULL) == positive;
750}
751
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100752int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300753_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
754{
755 int mark = p->mark;
756 void *res = func(p, arg);
757 p->mark = mark;
758 return (res != NULL) == positive;
759}
760
761int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100762_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
763{
764 int mark = p->mark;
765 void *res = func(p, arg);
766 p->mark = mark;
767 return (res != NULL) == positive;
768}
769
770int
771_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
772{
773 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100774 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100775 p->mark = mark;
776 return (res != NULL) == positive;
777}
778
779Token *
780_PyPegen_expect_token(Parser *p, int type)
781{
782 if (p->mark == p->fill) {
783 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300784 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100785 return NULL;
786 }
787 }
788 Token *t = p->tokens[p->mark];
789 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100790 return NULL;
791 }
792 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100793 return t;
794}
795
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300796expr_ty
797_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
798{
799 if (p->mark == p->fill) {
800 if (_PyPegen_fill_token(p) < 0) {
801 p->error_indicator = 1;
802 return NULL;
803 }
804 }
805 Token *t = p->tokens[p->mark];
806 if (t->type != NAME) {
807 return NULL;
808 }
809 char* s = PyBytes_AsString(t->bytes);
810 if (!s) {
811 p->error_indicator = 1;
812 return NULL;
813 }
814 if (strcmp(s, keyword) != 0) {
815 return NULL;
816 }
817 return _PyPegen_name_token(p);
818}
819
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100820Token *
821_PyPegen_get_last_nonnwhitespace_token(Parser *p)
822{
823 assert(p->mark >= 0);
824 Token *token = NULL;
825 for (int m = p->mark - 1; m >= 0; m--) {
826 token = p->tokens[m];
827 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
828 break;
829 }
830 }
831 return token;
832}
833
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100834expr_ty
835_PyPegen_name_token(Parser *p)
836{
837 Token *t = _PyPegen_expect_token(p, NAME);
838 if (t == NULL) {
839 return NULL;
840 }
841 char* s = PyBytes_AsString(t->bytes);
842 if (!s) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300843 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100844 return NULL;
845 }
846 PyObject *id = _PyPegen_new_identifier(p, s);
847 if (id == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300848 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100849 return NULL;
850 }
851 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
852 p->arena);
853}
854
855void *
856_PyPegen_string_token(Parser *p)
857{
858 return _PyPegen_expect_token(p, STRING);
859}
860
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100861static PyObject *
862parsenumber_raw(const char *s)
863{
864 const char *end;
865 long x;
866 double dx;
867 Py_complex compl;
868 int imflag;
869
870 assert(s != NULL);
871 errno = 0;
872 end = s + strlen(s) - 1;
873 imflag = *end == 'j' || *end == 'J';
874 if (s[0] == '0') {
875 x = (long)PyOS_strtoul(s, (char **)&end, 0);
876 if (x < 0 && errno == 0) {
877 return PyLong_FromString(s, (char **)0, 0);
878 }
879 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100880 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100881 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100882 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100883 if (*end == '\0') {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100884 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100885 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100886 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100887 return PyLong_FromLong(x);
888 }
889 /* XXX Huge floats may silently fail */
890 if (imflag) {
891 compl.real = 0.;
892 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100893 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100894 return NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100895 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100896 return PyComplex_FromCComplex(compl);
897 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100898 dx = PyOS_string_to_double(s, NULL, NULL);
899 if (dx == -1.0 && PyErr_Occurred()) {
900 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100901 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100902 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100903}
904
905static PyObject *
906parsenumber(const char *s)
907{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100908 char *dup;
909 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100910 PyObject *res = NULL;
911
912 assert(s != NULL);
913
914 if (strchr(s, '_') == NULL) {
915 return parsenumber_raw(s);
916 }
917 /* Create a duplicate without underscores. */
918 dup = PyMem_Malloc(strlen(s) + 1);
919 if (dup == NULL) {
920 return PyErr_NoMemory();
921 }
922 end = dup;
923 for (; *s; s++) {
924 if (*s != '_') {
925 *end++ = *s;
926 }
927 }
928 *end = '\0';
929 res = parsenumber_raw(dup);
930 PyMem_Free(dup);
931 return res;
932}
933
934expr_ty
935_PyPegen_number_token(Parser *p)
936{
937 Token *t = _PyPegen_expect_token(p, NUMBER);
938 if (t == NULL) {
939 return NULL;
940 }
941
942 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100943 if (num_raw == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300944 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100945 return NULL;
946 }
947
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300948 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
949 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700950 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300951 "in Python 3.6 and greater");
952 }
953
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100954 PyObject *c = parsenumber(num_raw);
955
956 if (c == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300957 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100958 return NULL;
959 }
960
961 if (PyArena_AddPyObject(p->arena, c) < 0) {
962 Py_DECREF(c);
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300963 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100964 return NULL;
965 }
966
967 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
968 p->arena);
969}
970
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300971static int // bool
972newline_in_string(Parser *p, const char *cur)
973{
Miss Islington (bot)15fec562020-06-05 17:13:14 -0700974 for (const char *c = cur; c >= p->tok->buf; c--) {
975 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300976 return 1;
977 }
978 }
979 return 0;
980}
981
982/* Check that the source for a single input statement really is a single
983 statement by looking at what is left in the buffer after parsing.
984 Trailing whitespace and comments are OK. */
985static int // bool
986bad_single_statement(Parser *p)
987{
988 const char *cur = strchr(p->tok->buf, '\n');
989
990 /* Newlines are allowed if preceded by a line continuation character
991 or if they appear inside a string. */
992 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
993 return 0;
994 }
995 char c = *cur;
996
997 for (;;) {
998 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
999 c = *++cur;
1000 }
1001
1002 if (!c) {
1003 return 0;
1004 }
1005
1006 if (c != '#') {
1007 return 1;
1008 }
1009
1010 /* Suck up comment. */
1011 while (c && c != '\n') {
1012 c = *++cur;
1013 }
1014 }
1015}
1016
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001017void
1018_PyPegen_Parser_Free(Parser *p)
1019{
1020 Py_XDECREF(p->normalize);
1021 for (int i = 0; i < p->size; i++) {
1022 PyMem_Free(p->tokens[i]);
1023 }
1024 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001025 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001026 PyMem_Free(p);
1027}
1028
Pablo Galindo2b74c832020-04-27 18:02:07 +01001029static int
1030compute_parser_flags(PyCompilerFlags *flags)
1031{
1032 int parser_flags = 0;
1033 if (!flags) {
1034 return 0;
1035 }
1036 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1037 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1038 }
1039 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1040 parser_flags |= PyPARSE_IGNORE_COOKIE;
1041 }
1042 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1043 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1044 }
1045 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1046 parser_flags |= PyPARSE_TYPE_COMMENTS;
1047 }
Guido van Rossum2a1ee1d2020-06-27 17:34:30 -07001048 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001049 parser_flags |= PyPARSE_ASYNC_HACKS;
1050 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001051 return parser_flags;
1052}
1053
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001054Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001055_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001056 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001057{
1058 Parser *p = PyMem_Malloc(sizeof(Parser));
1059 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001060 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001061 }
1062 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001063 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1064 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001065 p->tok = tok;
1066 p->keywords = NULL;
1067 p->n_keyword_lists = -1;
1068 p->tokens = PyMem_Malloc(sizeof(Token *));
1069 if (!p->tokens) {
1070 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001071 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001072 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001073 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001074 if (!p->tokens) {
1075 PyMem_Free(p->tokens);
1076 PyMem_Free(p);
1077 return (Parser *) PyErr_NoMemory();
1078 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001079 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1080 PyMem_Free(p->tokens[0]);
1081 PyMem_Free(p->tokens);
1082 PyMem_Free(p);
1083 return (Parser *) PyErr_NoMemory();
1084 }
1085
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001086 p->mark = 0;
1087 p->fill = 0;
1088 p->size = 1;
1089
1090 p->errcode = errcode;
1091 p->arena = arena;
1092 p->start_rule = start_rule;
1093 p->parsing_started = 0;
1094 p->normalize = NULL;
1095 p->error_indicator = 0;
1096
1097 p->starting_lineno = 0;
1098 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001099 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001100 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001101 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001102 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001103
1104 return p;
1105}
1106
1107void *
1108_PyPegen_run_parser(Parser *p)
1109{
1110 void *res = _PyPegen_parse(p);
1111 if (res == NULL) {
1112 if (PyErr_Occurred()) {
1113 return NULL;
1114 }
1115 if (p->fill == 0) {
1116 RAISE_SYNTAX_ERROR("error at start before reading any input");
1117 }
1118 else if (p->tok->done == E_EOF) {
1119 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1120 }
1121 else {
1122 if (p->tokens[p->fill-1]->type == INDENT) {
1123 RAISE_INDENTATION_ERROR("unexpected indent");
1124 }
1125 else if (p->tokens[p->fill-1]->type == DEDENT) {
1126 RAISE_INDENTATION_ERROR("unexpected unindent");
1127 }
1128 else {
1129 RAISE_SYNTAX_ERROR("invalid syntax");
1130 }
1131 }
1132 return NULL;
1133 }
1134
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001135 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1136 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1137 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1138 }
1139
Pablo Galindobc2c0e92020-07-28 00:12:31 +01001140#if defined(Py_DEBUG) && defined(Py_BUILD_CORE)
1141 if (p->start_rule == Py_single_input ||
1142 p->start_rule == Py_file_input ||
1143 p->start_rule == Py_eval_input)
1144 {
1145 assert(PyAST_Validate(res));
1146 }
1147#endif
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001148 return res;
1149}
1150
1151mod_ty
1152_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1153 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001154 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001155{
1156 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1157 if (tok == NULL) {
1158 if (PyErr_Occurred()) {
1159 raise_tokenizer_init_error(filename_ob);
1160 return NULL;
1161 }
1162 return NULL;
1163 }
1164 // This transfers the ownership to the tokenizer
1165 tok->filename = filename_ob;
1166 Py_INCREF(filename_ob);
1167
1168 // From here on we need to clean up even if there's an error
1169 mod_ty result = NULL;
1170
Pablo Galindo2b74c832020-04-27 18:02:07 +01001171 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001172 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1173 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001174 if (p == NULL) {
1175 goto error;
1176 }
1177
1178 result = _PyPegen_run_parser(p);
1179 _PyPegen_Parser_Free(p);
1180
1181error:
1182 PyTokenizer_Free(tok);
1183 return result;
1184}
1185
1186mod_ty
1187_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001188 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001189{
1190 FILE *fp = fopen(filename, "rb");
1191 if (fp == NULL) {
1192 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1193 return NULL;
1194 }
1195
1196 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001197 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001198
1199 fclose(fp);
1200 return result;
1201}
1202
1203mod_ty
1204_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001205 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001206{
1207 int exec_input = start_rule == Py_file_input;
1208
1209 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001210 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001211 tok = PyTokenizer_FromUTF8(str, exec_input);
1212 } else {
1213 tok = PyTokenizer_FromString(str, exec_input);
1214 }
1215 if (tok == NULL) {
1216 if (PyErr_Occurred()) {
1217 raise_tokenizer_init_error(filename_ob);
1218 }
1219 return NULL;
1220 }
1221 // This transfers the ownership to the tokenizer
1222 tok->filename = filename_ob;
1223 Py_INCREF(filename_ob);
1224
1225 // We need to clear up from here on
1226 mod_ty result = NULL;
1227
Pablo Galindo2b74c832020-04-27 18:02:07 +01001228 int parser_flags = compute_parser_flags(flags);
Guido van Rossum2a1ee1d2020-06-27 17:34:30 -07001229 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1230 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001231 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1232 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001233 if (p == NULL) {
1234 goto error;
1235 }
1236
1237 result = _PyPegen_run_parser(p);
1238 _PyPegen_Parser_Free(p);
1239
1240error:
1241 PyTokenizer_Free(tok);
1242 return result;
1243}
1244
1245void *
1246_PyPegen_interactive_exit(Parser *p)
1247{
1248 if (p->errcode) {
1249 *(p->errcode) = E_EOF;
1250 }
1251 return NULL;
1252}
1253
1254/* Creates a single-element asdl_seq* that contains a */
1255asdl_seq *
1256_PyPegen_singleton_seq(Parser *p, void *a)
1257{
1258 assert(a != NULL);
1259 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1260 if (!seq) {
1261 return NULL;
1262 }
1263 asdl_seq_SET(seq, 0, a);
1264 return seq;
1265}
1266
1267/* Creates a copy of seq and prepends a to it */
1268asdl_seq *
1269_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1270{
1271 assert(a != NULL);
1272 if (!seq) {
1273 return _PyPegen_singleton_seq(p, a);
1274 }
1275
1276 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1277 if (!new_seq) {
1278 return NULL;
1279 }
1280
1281 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001282 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001283 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1284 }
1285 return new_seq;
1286}
1287
Guido van Rossumc001c092020-04-30 12:12:19 -07001288/* Creates a copy of seq and appends a to it */
1289asdl_seq *
1290_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1291{
1292 assert(a != NULL);
1293 if (!seq) {
1294 return _PyPegen_singleton_seq(p, a);
1295 }
1296
1297 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1298 if (!new_seq) {
1299 return NULL;
1300 }
1301
1302 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1303 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1304 }
1305 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1306 return new_seq;
1307}
1308
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001309static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001310_get_flattened_seq_size(asdl_seq *seqs)
1311{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001312 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001313 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1314 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1315 size += asdl_seq_LEN(inner_seq);
1316 }
1317 return size;
1318}
1319
1320/* Flattens an asdl_seq* of asdl_seq*s */
1321asdl_seq *
1322_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1323{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001324 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001325 assert(flattened_seq_size > 0);
1326
1327 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1328 if (!flattened_seq) {
1329 return NULL;
1330 }
1331
1332 int flattened_seq_idx = 0;
1333 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1334 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001335 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001336 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1337 }
1338 }
1339 assert(flattened_seq_idx == flattened_seq_size);
1340
1341 return flattened_seq;
1342}
1343
1344/* Creates a new name of the form <first_name>.<second_name> */
1345expr_ty
1346_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1347{
1348 assert(first_name != NULL && second_name != NULL);
1349 PyObject *first_identifier = first_name->v.Name.id;
1350 PyObject *second_identifier = second_name->v.Name.id;
1351
1352 if (PyUnicode_READY(first_identifier) == -1) {
1353 return NULL;
1354 }
1355 if (PyUnicode_READY(second_identifier) == -1) {
1356 return NULL;
1357 }
1358 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1359 if (!first_str) {
1360 return NULL;
1361 }
1362 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1363 if (!second_str) {
1364 return NULL;
1365 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001366 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001367
1368 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1369 if (!str) {
1370 return NULL;
1371 }
1372
1373 char *s = PyBytes_AS_STRING(str);
1374 if (!s) {
1375 return NULL;
1376 }
1377
1378 strcpy(s, first_str);
1379 s += strlen(first_str);
1380 *s++ = '.';
1381 strcpy(s, second_str);
1382 s += strlen(second_str);
1383 *s = '\0';
1384
1385 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1386 Py_DECREF(str);
1387 if (!uni) {
1388 return NULL;
1389 }
1390 PyUnicode_InternInPlace(&uni);
1391 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1392 Py_DECREF(uni);
1393 return NULL;
1394 }
1395
1396 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1397}
1398
1399/* Counts the total number of dots in seq's tokens */
1400int
1401_PyPegen_seq_count_dots(asdl_seq *seq)
1402{
1403 int number_of_dots = 0;
1404 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1405 Token *current_expr = asdl_seq_GET(seq, i);
1406 switch (current_expr->type) {
1407 case ELLIPSIS:
1408 number_of_dots += 3;
1409 break;
1410 case DOT:
1411 number_of_dots += 1;
1412 break;
1413 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001414 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001415 }
1416 }
1417
1418 return number_of_dots;
1419}
1420
1421/* Creates an alias with '*' as the identifier name */
1422alias_ty
1423_PyPegen_alias_for_star(Parser *p)
1424{
1425 PyObject *str = PyUnicode_InternFromString("*");
1426 if (!str) {
1427 return NULL;
1428 }
1429 if (PyArena_AddPyObject(p->arena, str) < 0) {
1430 Py_DECREF(str);
1431 return NULL;
1432 }
1433 return alias(str, NULL, p->arena);
1434}
1435
1436/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1437asdl_seq *
1438_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1439{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001440 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001441 assert(len > 0);
1442
1443 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1444 if (!new_seq) {
1445 return NULL;
1446 }
1447 for (Py_ssize_t i = 0; i < len; i++) {
1448 expr_ty e = asdl_seq_GET(seq, i);
1449 asdl_seq_SET(new_seq, i, e->v.Name.id);
1450 }
1451 return new_seq;
1452}
1453
1454/* Constructs a CmpopExprPair */
1455CmpopExprPair *
1456_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1457{
1458 assert(expr != NULL);
1459 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1460 if (!a) {
1461 return NULL;
1462 }
1463 a->cmpop = cmpop;
1464 a->expr = expr;
1465 return a;
1466}
1467
1468asdl_int_seq *
1469_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1470{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001471 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001472 assert(len > 0);
1473
1474 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1475 if (!new_seq) {
1476 return NULL;
1477 }
1478 for (Py_ssize_t i = 0; i < len; i++) {
1479 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1480 asdl_seq_SET(new_seq, i, pair->cmpop);
1481 }
1482 return new_seq;
1483}
1484
1485asdl_seq *
1486_PyPegen_get_exprs(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_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1492 if (!new_seq) {
1493 return NULL;
1494 }
1495 for (Py_ssize_t i = 0; i < len; i++) {
1496 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1497 asdl_seq_SET(new_seq, i, pair->expr);
1498 }
1499 return new_seq;
1500}
1501
1502/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1503static asdl_seq *
1504_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1505{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001506 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001507 if (len == 0) {
1508 return NULL;
1509 }
1510
1511 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1512 if (!new_seq) {
1513 return NULL;
1514 }
1515 for (Py_ssize_t i = 0; i < len; i++) {
1516 expr_ty e = asdl_seq_GET(seq, i);
1517 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1518 }
1519 return new_seq;
1520}
1521
1522static expr_ty
1523_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1524{
1525 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1526}
1527
1528static expr_ty
1529_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1530{
1531 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1532}
1533
1534static expr_ty
1535_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1536{
1537 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1538}
1539
1540static expr_ty
1541_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1542{
1543 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1544}
1545
1546static expr_ty
1547_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1548{
1549 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1550}
1551
1552static expr_ty
1553_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1554{
1555 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1556}
1557
1558/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1559expr_ty
1560_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1561{
1562 assert(expr != NULL);
1563
1564 expr_ty new = NULL;
1565 switch (expr->kind) {
1566 case Name_kind:
1567 new = _set_name_context(p, expr, ctx);
1568 break;
1569 case Tuple_kind:
1570 new = _set_tuple_context(p, expr, ctx);
1571 break;
1572 case List_kind:
1573 new = _set_list_context(p, expr, ctx);
1574 break;
1575 case Subscript_kind:
1576 new = _set_subscript_context(p, expr, ctx);
1577 break;
1578 case Attribute_kind:
1579 new = _set_attribute_context(p, expr, ctx);
1580 break;
1581 case Starred_kind:
1582 new = _set_starred_context(p, expr, ctx);
1583 break;
1584 default:
1585 new = expr;
1586 }
1587 return new;
1588}
1589
1590/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1591KeyValuePair *
1592_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1593{
1594 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1595 if (!a) {
1596 return NULL;
1597 }
1598 a->key = key;
1599 a->value = value;
1600 return a;
1601}
1602
1603/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1604asdl_seq *
1605_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1606{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001607 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001608 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1609 if (!new_seq) {
1610 return NULL;
1611 }
1612 for (Py_ssize_t i = 0; i < len; i++) {
1613 KeyValuePair *pair = asdl_seq_GET(seq, i);
1614 asdl_seq_SET(new_seq, i, pair->key);
1615 }
1616 return new_seq;
1617}
1618
1619/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1620asdl_seq *
1621_PyPegen_get_values(Parser *p, asdl_seq *seq)
1622{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001623 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001624 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1625 if (!new_seq) {
1626 return NULL;
1627 }
1628 for (Py_ssize_t i = 0; i < len; i++) {
1629 KeyValuePair *pair = asdl_seq_GET(seq, i);
1630 asdl_seq_SET(new_seq, i, pair->value);
1631 }
1632 return new_seq;
1633}
1634
1635/* Constructs a NameDefaultPair */
1636NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001637_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001638{
1639 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1640 if (!a) {
1641 return NULL;
1642 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001643 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001644 a->value = value;
1645 return a;
1646}
1647
1648/* Constructs a SlashWithDefault */
1649SlashWithDefault *
1650_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1651{
1652 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1653 if (!a) {
1654 return NULL;
1655 }
1656 a->plain_names = plain_names;
1657 a->names_with_defaults = names_with_defaults;
1658 return a;
1659}
1660
1661/* Constructs a StarEtc */
1662StarEtc *
1663_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1664{
1665 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1666 if (!a) {
1667 return NULL;
1668 }
1669 a->vararg = vararg;
1670 a->kwonlyargs = kwonlyargs;
1671 a->kwarg = kwarg;
1672 return a;
1673}
1674
1675asdl_seq *
1676_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1677{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001678 Py_ssize_t first_len = asdl_seq_LEN(a);
1679 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001680 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1681 if (!new_seq) {
1682 return NULL;
1683 }
1684
1685 int k = 0;
1686 for (Py_ssize_t i = 0; i < first_len; i++) {
1687 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1688 }
1689 for (Py_ssize_t i = 0; i < second_len; i++) {
1690 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1691 }
1692
1693 return new_seq;
1694}
1695
1696static asdl_seq *
1697_get_names(Parser *p, asdl_seq *names_with_defaults)
1698{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001699 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001700 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1701 if (!seq) {
1702 return NULL;
1703 }
1704 for (Py_ssize_t i = 0; i < len; i++) {
1705 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1706 asdl_seq_SET(seq, i, pair->arg);
1707 }
1708 return seq;
1709}
1710
1711static asdl_seq *
1712_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1713{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001714 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001715 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1716 if (!seq) {
1717 return NULL;
1718 }
1719 for (Py_ssize_t i = 0; i < len; i++) {
1720 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1721 asdl_seq_SET(seq, i, pair->value);
1722 }
1723 return seq;
1724}
1725
1726/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1727arguments_ty
1728_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1729 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1730 asdl_seq *names_with_default, StarEtc *star_etc)
1731{
1732 asdl_seq *posonlyargs;
1733 if (slash_without_default != NULL) {
1734 posonlyargs = slash_without_default;
1735 }
1736 else if (slash_with_default != NULL) {
1737 asdl_seq *slash_with_default_names =
1738 _get_names(p, slash_with_default->names_with_defaults);
1739 if (!slash_with_default_names) {
1740 return NULL;
1741 }
1742 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1743 if (!posonlyargs) {
1744 return NULL;
1745 }
1746 }
1747 else {
1748 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1749 if (!posonlyargs) {
1750 return NULL;
1751 }
1752 }
1753
1754 asdl_seq *posargs;
1755 if (plain_names != NULL && names_with_default != NULL) {
1756 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1757 if (!names_with_default_names) {
1758 return NULL;
1759 }
1760 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1761 if (!posargs) {
1762 return NULL;
1763 }
1764 }
1765 else if (plain_names == NULL && names_with_default != NULL) {
1766 posargs = _get_names(p, names_with_default);
1767 if (!posargs) {
1768 return NULL;
1769 }
1770 }
1771 else if (plain_names != NULL && names_with_default == NULL) {
1772 posargs = plain_names;
1773 }
1774 else {
1775 posargs = _Py_asdl_seq_new(0, p->arena);
1776 if (!posargs) {
1777 return NULL;
1778 }
1779 }
1780
1781 asdl_seq *posdefaults;
1782 if (slash_with_default != NULL && names_with_default != NULL) {
1783 asdl_seq *slash_with_default_values =
1784 _get_defaults(p, slash_with_default->names_with_defaults);
1785 if (!slash_with_default_values) {
1786 return NULL;
1787 }
1788 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1789 if (!names_with_default_values) {
1790 return NULL;
1791 }
1792 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1793 if (!posdefaults) {
1794 return NULL;
1795 }
1796 }
1797 else if (slash_with_default == NULL && names_with_default != NULL) {
1798 posdefaults = _get_defaults(p, names_with_default);
1799 if (!posdefaults) {
1800 return NULL;
1801 }
1802 }
1803 else if (slash_with_default != NULL && names_with_default == NULL) {
1804 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1805 if (!posdefaults) {
1806 return NULL;
1807 }
1808 }
1809 else {
1810 posdefaults = _Py_asdl_seq_new(0, p->arena);
1811 if (!posdefaults) {
1812 return NULL;
1813 }
1814 }
1815
1816 arg_ty vararg = NULL;
1817 if (star_etc != NULL && star_etc->vararg != NULL) {
1818 vararg = star_etc->vararg;
1819 }
1820
1821 asdl_seq *kwonlyargs;
1822 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1823 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1824 if (!kwonlyargs) {
1825 return NULL;
1826 }
1827 }
1828 else {
1829 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1830 if (!kwonlyargs) {
1831 return NULL;
1832 }
1833 }
1834
1835 asdl_seq *kwdefaults;
1836 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1837 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1838 if (!kwdefaults) {
1839 return NULL;
1840 }
1841 }
1842 else {
1843 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1844 if (!kwdefaults) {
1845 return NULL;
1846 }
1847 }
1848
1849 arg_ty kwarg = NULL;
1850 if (star_etc != NULL && star_etc->kwarg != NULL) {
1851 kwarg = star_etc->kwarg;
1852 }
1853
1854 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1855 posdefaults, p->arena);
1856}
1857
1858/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1859 * arguments. */
1860arguments_ty
1861_PyPegen_empty_arguments(Parser *p)
1862{
1863 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1864 if (!posonlyargs) {
1865 return NULL;
1866 }
1867 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1868 if (!posargs) {
1869 return NULL;
1870 }
1871 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1872 if (!posdefaults) {
1873 return NULL;
1874 }
1875 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1876 if (!kwonlyargs) {
1877 return NULL;
1878 }
1879 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1880 if (!kwdefaults) {
1881 return NULL;
1882 }
1883
1884 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1885 p->arena);
1886}
1887
1888/* Encapsulates the value of an operator_ty into an AugOperator struct */
1889AugOperator *
1890_PyPegen_augoperator(Parser *p, operator_ty kind)
1891{
1892 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1893 if (!a) {
1894 return NULL;
1895 }
1896 a->kind = kind;
1897 return a;
1898}
1899
1900/* Construct a FunctionDef equivalent to function_def, but with decorators */
1901stmt_ty
1902_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1903{
1904 assert(function_def != NULL);
1905 if (function_def->kind == AsyncFunctionDef_kind) {
1906 return _Py_AsyncFunctionDef(
1907 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1908 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1909 function_def->v.FunctionDef.type_comment, function_def->lineno,
1910 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1911 p->arena);
1912 }
1913
1914 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1915 function_def->v.FunctionDef.body, decorators,
1916 function_def->v.FunctionDef.returns,
1917 function_def->v.FunctionDef.type_comment, function_def->lineno,
1918 function_def->col_offset, function_def->end_lineno,
1919 function_def->end_col_offset, p->arena);
1920}
1921
1922/* Construct a ClassDef equivalent to class_def, but with decorators */
1923stmt_ty
1924_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1925{
1926 assert(class_def != NULL);
1927 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1928 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1929 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1930 class_def->end_col_offset, p->arena);
1931}
1932
1933/* Construct a KeywordOrStarred */
1934KeywordOrStarred *
1935_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1936{
1937 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1938 if (!a) {
1939 return NULL;
1940 }
1941 a->element = element;
1942 a->is_keyword = is_keyword;
1943 return a;
1944}
1945
1946/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1947static int
1948_seq_number_of_starred_exprs(asdl_seq *seq)
1949{
1950 int n = 0;
1951 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1952 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1953 if (!k->is_keyword) {
1954 n++;
1955 }
1956 }
1957 return n;
1958}
1959
1960/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1961asdl_seq *
1962_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1963{
1964 int new_len = _seq_number_of_starred_exprs(kwargs);
1965 if (new_len == 0) {
1966 return NULL;
1967 }
1968 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1969 if (!new_seq) {
1970 return NULL;
1971 }
1972
1973 int idx = 0;
1974 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1975 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1976 if (!k->is_keyword) {
1977 asdl_seq_SET(new_seq, idx++, k->element);
1978 }
1979 }
1980 return new_seq;
1981}
1982
1983/* Return a new asdl_seq* with only the keywords in kwargs */
1984asdl_seq *
1985_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1986{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001987 Py_ssize_t len = asdl_seq_LEN(kwargs);
1988 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001989 if (new_len == 0) {
1990 return NULL;
1991 }
1992 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1993 if (!new_seq) {
1994 return NULL;
1995 }
1996
1997 int idx = 0;
1998 for (Py_ssize_t i = 0; i < len; i++) {
1999 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
2000 if (k->is_keyword) {
2001 asdl_seq_SET(new_seq, idx++, k->element);
2002 }
2003 }
2004 return new_seq;
2005}
2006
2007expr_ty
2008_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2009{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002010 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002011 assert(len > 0);
2012
2013 Token *first = asdl_seq_GET(strings, 0);
2014 Token *last = asdl_seq_GET(strings, len - 1);
2015
2016 int bytesmode = 0;
2017 PyObject *bytes_str = NULL;
2018
2019 FstringParser state;
2020 _PyPegen_FstringParser_Init(&state);
2021
2022 for (Py_ssize_t i = 0; i < len; i++) {
2023 Token *t = asdl_seq_GET(strings, i);
2024
2025 int this_bytesmode;
2026 int this_rawmode;
2027 PyObject *s;
2028 const char *fstr;
2029 Py_ssize_t fstrlen = -1;
2030
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002031 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002032 goto error;
2033 }
2034
2035 /* Check that we are not mixing bytes with unicode. */
2036 if (i != 0 && bytesmode != this_bytesmode) {
2037 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2038 Py_XDECREF(s);
2039 goto error;
2040 }
2041 bytesmode = this_bytesmode;
2042
2043 if (fstr != NULL) {
2044 assert(s == NULL && !bytesmode);
2045
2046 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2047 this_rawmode, 0, first, t, last);
2048 if (result < 0) {
2049 goto error;
2050 }
2051 }
2052 else {
2053 /* String or byte string. */
2054 assert(s != NULL && fstr == NULL);
2055 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2056
2057 if (bytesmode) {
2058 if (i == 0) {
2059 bytes_str = s;
2060 }
2061 else {
2062 PyBytes_ConcatAndDel(&bytes_str, s);
2063 if (!bytes_str) {
2064 goto error;
2065 }
2066 }
2067 }
2068 else {
2069 /* This is a regular string. Concatenate it. */
2070 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2071 goto error;
2072 }
2073 }
2074 }
2075 }
2076
2077 if (bytesmode) {
2078 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2079 goto error;
2080 }
2081 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2082 last->end_col_offset, p->arena);
2083 }
2084
2085 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2086
2087error:
2088 Py_XDECREF(bytes_str);
2089 _PyPegen_FstringParser_Dealloc(&state);
2090 if (PyErr_Occurred()) {
2091 raise_decode_error(p);
2092 }
2093 return NULL;
2094}
Guido van Rossumc001c092020-04-30 12:12:19 -07002095
2096mod_ty
2097_PyPegen_make_module(Parser *p, asdl_seq *a) {
2098 asdl_seq *type_ignores = NULL;
2099 Py_ssize_t num = p->type_ignore_comments.num_items;
2100 if (num > 0) {
2101 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2102 type_ignores = _Py_asdl_seq_new(num, p->arena);
2103 if (type_ignores == NULL) {
2104 return NULL;
2105 }
2106 for (int i = 0; i < num; i++) {
2107 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2108 if (tag == NULL) {
2109 return NULL;
2110 }
2111 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2112 if (ti == NULL) {
2113 return NULL;
2114 }
2115 asdl_seq_SET(type_ignores, i, ti);
2116 }
2117 }
2118 return Module(a, type_ignores, p->arena);
2119}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002120
2121// Error reporting helpers
2122
2123expr_ty
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002124_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002125{
2126 if (e == NULL) {
2127 return NULL;
2128 }
2129
2130#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2131 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2132 for (Py_ssize_t i = 0; i < len; i++) {\
2133 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002134 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002135 if (child != NULL) {\
2136 return child;\
2137 }\
2138 }\
2139 } while (0)
2140
2141 // We only need to visit List and Tuple nodes recursively as those
2142 // are the only ones that can contain valid names in targets when
2143 // they are parsed as expressions. Any other kind of expression
2144 // that is a container (like Sets or Dicts) is directly invalid and
2145 // we don't need to visit it recursively.
2146
2147 switch (e->kind) {
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002148 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002149 VISIT_CONTAINER(e, List);
2150 return NULL;
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002151 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002152 VISIT_CONTAINER(e, Tuple);
2153 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002154 case Starred_kind:
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002155 if (targets_type == DEL_TARGETS) {
2156 return e;
2157 }
2158 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2159 case Compare_kind:
2160 // This is needed, because the `a in b` in `for a in b` gets parsed
2161 // as a comparison, and so we need to search the left side of the comparison
2162 // for invalid targets.
2163 if (targets_type == FOR_TARGETS) {
2164 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2165 if (cmpop == In) {
2166 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2167 }
2168 return NULL;
2169 }
2170 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002171 case Name_kind:
2172 case Subscript_kind:
2173 case Attribute_kind:
2174 return NULL;
2175 default:
2176 return e;
2177 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002178}
2179
2180void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2181 int kwarg_unpacking = 0;
2182 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2183 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2184 if (!keyword->arg) {
2185 kwarg_unpacking = 1;
2186 }
2187 }
2188
2189 const char *msg = NULL;
2190 if (kwarg_unpacking) {
2191 msg = "positional argument follows keyword argument unpacking";
2192 } else {
2193 msg = "positional argument follows keyword argument";
2194 }
2195
2196 return RAISE_SYNTAX_ERROR(msg);
2197}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002198
2199void *
2200_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2201{
2202 /* The rule that calls this function is 'args for_if_clauses'.
2203 For the input f(L, x for x in y), L and x are in args and
2204 the for is parsed as a for_if_clause. We have to check if
2205 len <= 1, so that input like dict((a, b) for a, b in x)
2206 gets successfully parsed and then we pass the last
2207 argument (x in the above example) as the location of the
2208 error */
2209 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2210 if (len <= 1) {
2211 return NULL;
2212 }
2213
2214 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2215 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2216 "Generator expression must be parenthesized"
2217 );
2218}
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002219
2220
Pablo Galindobe172952020-09-03 16:35:17 +01002221expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_seq *a, asdl_seq *b,
2222 int lineno, int col_offset, int end_lineno,
2223 int end_col_offset, PyArena *arena) {
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002224 Py_ssize_t args_len = asdl_seq_LEN(a);
2225 Py_ssize_t total_len = args_len;
2226
2227 if (b == NULL) {
Pablo Galindobe172952020-09-03 16:35:17 +01002228 return _Py_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
2229 end_lineno, end_col_offset, arena);
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002230
2231 }
2232
2233 asdl_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
2234 asdl_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
2235
2236 if (starreds) {
2237 total_len += asdl_seq_LEN(starreds);
2238 }
2239
Pablo Galindobe172952020-09-03 16:35:17 +01002240 asdl_seq *args = _Py_asdl_seq_new(total_len, arena);
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002241
2242 Py_ssize_t i = 0;
2243 for (i = 0; i < args_len; i++) {
2244 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
2245 }
2246 for (; i < total_len; i++) {
2247 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
2248 }
2249
Pablo Galindobe172952020-09-03 16:35:17 +01002250 return _Py_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
2251 col_offset, end_lineno, end_col_offset, arena);
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002252
Pablo Galindobe172952020-09-03 16:35:17 +01002253
Pablo Galindo8de34cd2020-09-02 21:30:51 +01002254}