blob: beb2b2da5696d937169c3674d2659ab1142b7480 [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"
7
Guido van Rossumc001c092020-04-30 12:12:19 -07008PyObject *
9_PyPegen_new_type_comment(Parser *p, char *s)
10{
11 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
12 if (res == NULL) {
13 return NULL;
14 }
15 if (PyArena_AddPyObject(p->arena, res) < 0) {
16 Py_DECREF(res);
17 return NULL;
18 }
19 return res;
20}
21
22arg_ty
23_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
24{
25 if (tc == NULL) {
26 return a;
27 }
28 char *bytes = PyBytes_AsString(tc->bytes);
29 if (bytes == NULL) {
30 return NULL;
31 }
32 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
33 if (tco == NULL) {
34 return NULL;
35 }
36 return arg(a->arg, a->annotation, tco,
37 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
38 p->arena);
39}
40
Pablo Galindoc5fc1562020-04-22 23:29:27 +010041static int
42init_normalization(Parser *p)
43{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030044 if (p->normalize) {
45 return 1;
46 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010047 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
48 if (!m)
49 {
50 return 0;
51 }
52 p->normalize = PyObject_GetAttrString(m, "normalize");
53 Py_DECREF(m);
54 if (!p->normalize)
55 {
56 return 0;
57 }
58 return 1;
59}
60
Pablo Galindo2b74c832020-04-27 18:02:07 +010061/* Checks if the NOTEQUAL token is valid given the current parser flags
620 indicates success and nonzero indicates failure (an exception may be set) */
63int
64_PyPegen_check_barry_as_flufl(Parser *p) {
65 Token *t = p->tokens[p->fill - 1];
66 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindo30b59fd2020-06-15 15:08:00 +010070 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010071 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
Pablo Galindo30b59fd2020-06-15 15:08:00 +010073 }
74 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010075 return strcmp(tok_str, "!=");
76 }
77 return 0;
78}
79
Pablo Galindoc5fc1562020-04-22 23:29:27 +010080PyObject *
81_PyPegen_new_identifier(Parser *p, char *n)
82{
83 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
84 if (!id) {
85 goto error;
86 }
87 /* PyUnicode_DecodeUTF8 should always return a ready string. */
88 assert(PyUnicode_IS_READY(id));
89 /* Check whether there are non-ASCII characters in the
90 identifier; if so, normalize to NFKC. */
91 if (!PyUnicode_IS_ASCII(id))
92 {
93 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030094 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010095 {
96 Py_DECREF(id);
97 goto error;
98 }
99 PyObject *form = PyUnicode_InternFromString("NFKC");
100 if (form == NULL)
101 {
102 Py_DECREF(id);
103 goto error;
104 }
105 PyObject *args[2] = {form, id};
106 id2 = _PyObject_FastCall(p->normalize, args, 2);
107 Py_DECREF(id);
108 Py_DECREF(form);
109 if (!id2) {
110 goto error;
111 }
112 if (!PyUnicode_Check(id2))
113 {
114 PyErr_Format(PyExc_TypeError,
115 "unicodedata.normalize() must return a string, not "
116 "%.200s",
117 _PyType_Name(Py_TYPE(id2)));
118 Py_DECREF(id2);
119 goto error;
120 }
121 id = id2;
122 }
123 PyUnicode_InternInPlace(&id);
124 if (PyArena_AddPyObject(p->arena, id) < 0)
125 {
126 Py_DECREF(id);
127 goto error;
128 }
129 return id;
130
131error:
132 p->error_indicator = 1;
133 return NULL;
134}
135
136static PyObject *
137_create_dummy_identifier(Parser *p)
138{
139 return _PyPegen_new_identifier(p, "");
140}
141
142static inline Py_ssize_t
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700143byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100144{
145 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300146 if (!str) {
147 return 0;
148 }
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700149 assert(col_offset >= 0 && (unsigned long)col_offset <= strlen(str));
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300150 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100151 if (!text) {
152 return 0;
153 }
154 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
155 Py_DECREF(text);
156 return size;
157}
158
159const char *
160_PyPegen_get_expr_name(expr_ty e)
161{
Miss Islington (bot)8df4f392020-06-08 02:22:06 -0700162 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100163 switch (e->kind) {
164 case Attribute_kind:
165 return "attribute";
166 case Subscript_kind:
167 return "subscript";
168 case Starred_kind:
169 return "starred";
170 case Name_kind:
171 return "name";
172 case List_kind:
173 return "list";
174 case Tuple_kind:
175 return "tuple";
176 case Lambda_kind:
177 return "lambda";
178 case Call_kind:
179 return "function call";
180 case BoolOp_kind:
181 case BinOp_kind:
182 case UnaryOp_kind:
183 return "operator";
184 case GeneratorExp_kind:
185 return "generator expression";
186 case Yield_kind:
187 case YieldFrom_kind:
188 return "yield expression";
189 case Await_kind:
190 return "await expression";
191 case ListComp_kind:
192 return "list comprehension";
193 case SetComp_kind:
194 return "set comprehension";
195 case DictComp_kind:
196 return "dict comprehension";
197 case Dict_kind:
198 return "dict display";
199 case Set_kind:
200 return "set display";
201 case JoinedStr_kind:
202 case FormattedValue_kind:
203 return "f-string expression";
204 case Constant_kind: {
205 PyObject *value = e->v.Constant.value;
206 if (value == Py_None) {
207 return "None";
208 }
209 if (value == Py_False) {
210 return "False";
211 }
212 if (value == Py_True) {
213 return "True";
214 }
215 if (value == Py_Ellipsis) {
216 return "Ellipsis";
217 }
218 return "literal";
219 }
220 case Compare_kind:
221 return "comparison";
222 case IfExp_kind:
223 return "conditional expression";
224 case NamedExpr_kind:
225 return "named expression";
226 default:
227 PyErr_Format(PyExc_SystemError,
228 "unexpected expression in assignment %d (line %d)",
229 e->kind, e->lineno);
230 return NULL;
231 }
232}
233
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300234static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100235raise_decode_error(Parser *p)
236{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300237 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100238 const char *errtype = NULL;
239 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
240 errtype = "unicode error";
241 }
242 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
243 errtype = "value error";
244 }
245 if (errtype) {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100246 PyObject *type;
247 PyObject *value;
248 PyObject *tback;
249 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100250 PyErr_Fetch(&type, &value, &tback);
251 errstr = PyObject_Str(value);
252 if (errstr) {
253 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
254 Py_DECREF(errstr);
255 }
256 else {
257 PyErr_Clear();
258 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
259 }
260 Py_XDECREF(type);
261 Py_XDECREF(value);
262 Py_XDECREF(tback);
263 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300264
265 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100266}
267
268static void
269raise_tokenizer_init_error(PyObject *filename)
270{
271 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
272 || PyErr_ExceptionMatches(PyExc_ValueError)
273 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
274 return;
275 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300276 PyObject *errstr = NULL;
277 PyObject *tuple = NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100278 PyObject *type;
279 PyObject *value;
280 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100281 PyErr_Fetch(&type, &value, &tback);
282 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300283 if (!errstr) {
284 goto error;
285 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100286
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300287 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100288 if (!tmp) {
289 goto error;
290 }
291
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300292 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100293 Py_DECREF(tmp);
294 if (!value) {
295 goto error;
296 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300297 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100298
299error:
300 Py_XDECREF(type);
301 Py_XDECREF(value);
302 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300303 Py_XDECREF(errstr);
304 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100305}
306
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100307static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308tokenizer_error(Parser *p)
309{
310 if (PyErr_Occurred()) {
311 return -1;
312 }
313
314 const char *msg = NULL;
315 PyObject* errtype = PyExc_SyntaxError;
316 switch (p->tok->done) {
317 case E_TOKEN:
318 msg = "invalid token";
319 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300321 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
322 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100323 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300324 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
325 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300326 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300327 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
328 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100329 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300330 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
331 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332 case E_INTR:
333 if (!PyErr_Occurred()) {
334 PyErr_SetNone(PyExc_KeyboardInterrupt);
335 }
336 return -1;
337 case E_NOMEM:
338 PyErr_NoMemory();
339 return -1;
340 case E_TABSPACE:
341 errtype = PyExc_TabError;
342 msg = "inconsistent use of tabs and spaces in indentation";
343 break;
344 case E_TOODEEP:
345 errtype = PyExc_IndentationError;
346 msg = "too many levels of indentation";
347 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100348 case E_LINECONT:
349 msg = "unexpected character after line continuation character";
350 break;
351 default:
352 msg = "unknown parsing error";
353 }
354
355 PyErr_Format(errtype, msg);
356 // There is no reliable column information for this error
357 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
358
359 return -1;
360}
361
362void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300363_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
364{
365 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700366 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300367 if (t->col_offset == -1) {
368 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
369 intptr_t, int);
370 } else {
371 col_offset = t->col_offset + 1;
372 }
373
374 va_list va;
375 va_start(va, errmsg);
376 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
377 col_offset, errmsg, va);
378 va_end(va);
379
380 return NULL;
381}
382
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300383void *
384_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700385 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300386 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100387{
388 PyObject *value = NULL;
389 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300390 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300392 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100393
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700394 if (p->start_rule == Py_fstring_input) {
395 const char *fstring_msg = "f-string: ";
396 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
397
398 char *new_errmsg = PyMem_RawMalloc(len + 1); // Lengths of both strings plus NULL character
399 if (!new_errmsg) {
400 return (void *) PyErr_NoMemory();
401 }
402
403 // Copy both strings into new buffer
404 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
405 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
406 new_errmsg[len] = 0;
407 errmsg = new_errmsg;
408 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100409 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100410 if (!errstr) {
411 goto error;
412 }
413
414 if (p->start_rule == Py_file_input) {
Miss Islington (bot)c9f83c12020-06-20 10:35:03 -0700415 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100416 }
417
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300418 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100419 Py_ssize_t size = p->tok->inp - p->tok->buf;
Pablo Galindobcc30362020-05-14 21:11:48 +0100420 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300421 if (!error_line) {
422 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300423 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100424 }
425
Pablo Galindodab533d2020-06-28 01:15:28 +0100426 if (p->start_rule == Py_fstring_input) {
427 col_offset -= p->starting_col_offset;
428 }
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700429 Py_ssize_t col_number = col_offset;
430
431 if (p->tok->encoding != NULL) {
432 col_number = byte_offset_to_character_offset(error_line, col_offset);
433 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300434
435 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100436 if (!tmp) {
437 goto error;
438 }
439 value = PyTuple_Pack(2, errstr, tmp);
440 Py_DECREF(tmp);
441 if (!value) {
442 goto error;
443 }
444 PyErr_SetObject(errtype, value);
445
446 Py_DECREF(errstr);
447 Py_DECREF(value);
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700448 if (p->start_rule == Py_fstring_input) {
449 PyMem_RawFree((void *)errmsg);
450 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100451 return NULL;
452
453error:
454 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300455 Py_XDECREF(error_line);
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700456 if (p->start_rule == Py_fstring_input) {
457 PyMem_RawFree((void *)errmsg);
458 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100459 return NULL;
460}
461
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100462#if 0
463static const char *
464token_name(int type)
465{
466 if (0 <= type && type <= N_TOKENS) {
467 return _PyParser_TokenNames[type];
468 }
469 return "<Huh?>";
470}
471#endif
472
473// Here, mark is the start of the node, while p->mark is the end.
474// If node==NULL, they should be the same.
475int
476_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
477{
478 // Insert in front
479 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
480 if (m == NULL) {
481 return -1;
482 }
483 m->type = type;
484 m->node = node;
485 m->mark = p->mark;
486 m->next = p->tokens[mark]->memo;
487 p->tokens[mark]->memo = m;
488 return 0;
489}
490
491// Like _PyPegen_insert_memo(), but updates an existing node if found.
492int
493_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
494{
495 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
496 if (m->type == type) {
497 // Update existing node.
498 m->node = node;
499 m->mark = p->mark;
500 return 0;
501 }
502 }
503 // Insert new node.
504 return _PyPegen_insert_memo(p, mark, type, node);
505}
506
507// Return dummy NAME.
508void *
509_PyPegen_dummy_name(Parser *p, ...)
510{
511 static void *cache = NULL;
512
513 if (cache != NULL) {
514 return cache;
515 }
516
517 PyObject *id = _create_dummy_identifier(p);
518 if (!id) {
519 return NULL;
520 }
521 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
522 return cache;
523}
524
525static int
526_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
527{
Miss Islington (bot)edeaf612020-07-06 16:35:10 -0700528 assert(name_len > 0);
Pablo Galindo54f115d2020-07-06 20:29:59 +0100529 if (name_len >= p->n_keyword_lists ||
530 p->keywords[name_len] == NULL ||
531 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100532 return NAME;
533 }
Pablo Galindo54f115d2020-07-06 20:29:59 +0100534 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100535 if (strncmp(k->str, name, name_len) == 0) {
536 return k->type;
537 }
538 }
539 return NAME;
540}
541
Guido van Rossumc001c092020-04-30 12:12:19 -0700542static int
543growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
544 assert(initial_size > 0);
545 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
546 arr->size = initial_size;
547 arr->num_items = 0;
548
549 return arr->items != NULL;
550}
551
552static int
553growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
554 if (arr->num_items >= arr->size) {
555 size_t new_size = arr->size * 2;
556 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
557 if (!new_items_array) {
558 return 0;
559 }
560 arr->items = new_items_array;
561 arr->size = new_size;
562 }
563
564 arr->items[arr->num_items].lineno = lineno;
565 arr->items[arr->num_items].comment = comment; // Take ownership
566 arr->num_items++;
567 return 1;
568}
569
570static void
571growable_comment_array_deallocate(growable_comment_array *arr) {
572 for (unsigned i = 0; i < arr->num_items; i++) {
573 PyMem_Free(arr->items[i].comment);
574 }
575 PyMem_Free(arr->items);
576}
577
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100578int
579_PyPegen_fill_token(Parser *p)
580{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100581 const char *start;
582 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100583 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700584
585 // Record and skip '# type: ignore' comments
586 while (type == TYPE_IGNORE) {
587 Py_ssize_t len = end - start;
588 char *tag = PyMem_Malloc(len + 1);
589 if (tag == NULL) {
590 PyErr_NoMemory();
591 return -1;
592 }
593 strncpy(tag, start, len);
594 tag[len] = '\0';
595 // Ownership of tag passes to the growable array
596 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
597 PyErr_NoMemory();
598 return -1;
599 }
600 type = PyTokenizer_Get(p->tok, &start, &end);
601 }
602
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100603 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
604 type = NEWLINE; /* Add an extra newline */
605 p->parsing_started = 0;
606
Pablo Galindob94dbd72020-04-27 18:35:58 +0100607 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100608 p->tok->pendin = -p->tok->indent;
609 p->tok->indent = 0;
610 }
611 }
612 else {
613 p->parsing_started = 1;
614 }
615
616 if (p->fill == p->size) {
617 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300618 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
619 if (new_tokens == NULL) {
620 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100621 return -1;
622 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100623 p->tokens = new_tokens;
624
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100625 for (int i = p->size; i < newsize; i++) {
626 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300627 if (p->tokens[i] == NULL) {
628 p->size = i; // Needed, in order to cleanup correctly after parser fails
629 PyErr_NoMemory();
630 return -1;
631 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100632 memset(p->tokens[i], '\0', sizeof(Token));
633 }
634 p->size = newsize;
635 }
636
637 Token *t = p->tokens[p->fill];
638 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
639 t->bytes = PyBytes_FromStringAndSize(start, end - start);
640 if (t->bytes == NULL) {
641 return -1;
642 }
643 PyArena_AddPyObject(p->arena, t->bytes);
644
645 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
646 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100647 int end_lineno = p->tok->lineno;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100648 int col_offset = -1;
649 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100650 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100651 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100652 }
653 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100654 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100655 }
656
657 t->lineno = p->starting_lineno + lineno;
658 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
659 t->end_lineno = p->starting_lineno + end_lineno;
660 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
661
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100662 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300663
664 if (type == ERRORTOKEN) {
665 if (p->tok->done == E_DECODE) {
666 return raise_decode_error(p);
667 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100668 return tokenizer_error(p);
669
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300670 }
671
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100672 return 0;
673}
674
675// Instrumentation to count the effectiveness of memoization.
676// The array counts the number of tokens skipped by memoization,
677// indexed by type.
678
679#define NSTATISTICS 2000
680static long memo_statistics[NSTATISTICS];
681
682void
683_PyPegen_clear_memo_statistics()
684{
685 for (int i = 0; i < NSTATISTICS; i++) {
686 memo_statistics[i] = 0;
687 }
688}
689
690PyObject *
691_PyPegen_get_memo_statistics()
692{
693 PyObject *ret = PyList_New(NSTATISTICS);
694 if (ret == NULL) {
695 return NULL;
696 }
697 for (int i = 0; i < NSTATISTICS; i++) {
698 PyObject *value = PyLong_FromLong(memo_statistics[i]);
699 if (value == NULL) {
700 Py_DECREF(ret);
701 return NULL;
702 }
703 // PyList_SetItem borrows a reference to value.
704 if (PyList_SetItem(ret, i, value) < 0) {
705 Py_DECREF(ret);
706 return NULL;
707 }
708 }
709 return ret;
710}
711
712int // bool
713_PyPegen_is_memoized(Parser *p, int type, void *pres)
714{
715 if (p->mark == p->fill) {
716 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300717 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100718 return -1;
719 }
720 }
721
722 Token *t = p->tokens[p->mark];
723
724 for (Memo *m = t->memo; m != NULL; m = m->next) {
725 if (m->type == type) {
726 if (0 <= type && type < NSTATISTICS) {
727 long count = m->mark - p->mark;
728 // A memoized negative result counts for one.
729 if (count <= 0) {
730 count = 1;
731 }
732 memo_statistics[type] += count;
733 }
734 p->mark = m->mark;
735 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100736 return 1;
737 }
738 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100739 return 0;
740}
741
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100742int
743_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
744{
745 int mark = p->mark;
746 void *res = func(p);
747 p->mark = mark;
748 return (res != NULL) == positive;
749}
750
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100751int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300752_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
753{
754 int mark = p->mark;
755 void *res = func(p, arg);
756 p->mark = mark;
757 return (res != NULL) == positive;
758}
759
760int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100761_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
762{
763 int mark = p->mark;
764 void *res = func(p, arg);
765 p->mark = mark;
766 return (res != NULL) == positive;
767}
768
769int
770_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
771{
772 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100773 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100774 p->mark = mark;
775 return (res != NULL) == positive;
776}
777
778Token *
779_PyPegen_expect_token(Parser *p, int type)
780{
781 if (p->mark == p->fill) {
782 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300783 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100784 return NULL;
785 }
786 }
787 Token *t = p->tokens[p->mark];
788 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100789 return NULL;
790 }
791 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100792 return t;
793}
794
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300795expr_ty
796_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
797{
798 if (p->mark == p->fill) {
799 if (_PyPegen_fill_token(p) < 0) {
800 p->error_indicator = 1;
801 return NULL;
802 }
803 }
804 Token *t = p->tokens[p->mark];
805 if (t->type != NAME) {
806 return NULL;
807 }
808 char* s = PyBytes_AsString(t->bytes);
809 if (!s) {
810 p->error_indicator = 1;
811 return NULL;
812 }
813 if (strcmp(s, keyword) != 0) {
814 return NULL;
815 }
816 return _PyPegen_name_token(p);
817}
818
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100819Token *
820_PyPegen_get_last_nonnwhitespace_token(Parser *p)
821{
822 assert(p->mark >= 0);
823 Token *token = NULL;
824 for (int m = p->mark - 1; m >= 0; m--) {
825 token = p->tokens[m];
826 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
827 break;
828 }
829 }
830 return token;
831}
832
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100833expr_ty
834_PyPegen_name_token(Parser *p)
835{
836 Token *t = _PyPegen_expect_token(p, NAME);
837 if (t == NULL) {
838 return NULL;
839 }
840 char* s = PyBytes_AsString(t->bytes);
841 if (!s) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300842 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100843 return NULL;
844 }
845 PyObject *id = _PyPegen_new_identifier(p, s);
846 if (id == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300847 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100848 return NULL;
849 }
850 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
851 p->arena);
852}
853
854void *
855_PyPegen_string_token(Parser *p)
856{
857 return _PyPegen_expect_token(p, STRING);
858}
859
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100860static PyObject *
861parsenumber_raw(const char *s)
862{
863 const char *end;
864 long x;
865 double dx;
866 Py_complex compl;
867 int imflag;
868
869 assert(s != NULL);
870 errno = 0;
871 end = s + strlen(s) - 1;
872 imflag = *end == 'j' || *end == 'J';
873 if (s[0] == '0') {
874 x = (long)PyOS_strtoul(s, (char **)&end, 0);
875 if (x < 0 && errno == 0) {
876 return PyLong_FromString(s, (char **)0, 0);
877 }
878 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100879 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100880 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100881 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100882 if (*end == '\0') {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100883 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100884 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100885 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100886 return PyLong_FromLong(x);
887 }
888 /* XXX Huge floats may silently fail */
889 if (imflag) {
890 compl.real = 0.;
891 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100892 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100893 return NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100894 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100895 return PyComplex_FromCComplex(compl);
896 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100897 dx = PyOS_string_to_double(s, NULL, NULL);
898 if (dx == -1.0 && PyErr_Occurred()) {
899 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100900 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100901 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100902}
903
904static PyObject *
905parsenumber(const char *s)
906{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100907 char *dup;
908 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100909 PyObject *res = NULL;
910
911 assert(s != NULL);
912
913 if (strchr(s, '_') == NULL) {
914 return parsenumber_raw(s);
915 }
916 /* Create a duplicate without underscores. */
917 dup = PyMem_Malloc(strlen(s) + 1);
918 if (dup == NULL) {
919 return PyErr_NoMemory();
920 }
921 end = dup;
922 for (; *s; s++) {
923 if (*s != '_') {
924 *end++ = *s;
925 }
926 }
927 *end = '\0';
928 res = parsenumber_raw(dup);
929 PyMem_Free(dup);
930 return res;
931}
932
933expr_ty
934_PyPegen_number_token(Parser *p)
935{
936 Token *t = _PyPegen_expect_token(p, NUMBER);
937 if (t == NULL) {
938 return NULL;
939 }
940
941 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100942 if (num_raw == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300943 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100944 return NULL;
945 }
946
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300947 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
948 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700949 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300950 "in Python 3.6 and greater");
951 }
952
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100953 PyObject *c = parsenumber(num_raw);
954
955 if (c == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300956 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100957 return NULL;
958 }
959
960 if (PyArena_AddPyObject(p->arena, c) < 0) {
961 Py_DECREF(c);
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300962 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100963 return NULL;
964 }
965
966 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
967 p->arena);
968}
969
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300970static int // bool
971newline_in_string(Parser *p, const char *cur)
972{
Miss Islington (bot)15fec562020-06-05 17:13:14 -0700973 for (const char *c = cur; c >= p->tok->buf; c--) {
974 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300975 return 1;
976 }
977 }
978 return 0;
979}
980
981/* Check that the source for a single input statement really is a single
982 statement by looking at what is left in the buffer after parsing.
983 Trailing whitespace and comments are OK. */
984static int // bool
985bad_single_statement(Parser *p)
986{
987 const char *cur = strchr(p->tok->buf, '\n');
988
989 /* Newlines are allowed if preceded by a line continuation character
990 or if they appear inside a string. */
991 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
992 return 0;
993 }
994 char c = *cur;
995
996 for (;;) {
997 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
998 c = *++cur;
999 }
1000
1001 if (!c) {
1002 return 0;
1003 }
1004
1005 if (c != '#') {
1006 return 1;
1007 }
1008
1009 /* Suck up comment. */
1010 while (c && c != '\n') {
1011 c = *++cur;
1012 }
1013 }
1014}
1015
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001016void
1017_PyPegen_Parser_Free(Parser *p)
1018{
1019 Py_XDECREF(p->normalize);
1020 for (int i = 0; i < p->size; i++) {
1021 PyMem_Free(p->tokens[i]);
1022 }
1023 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001024 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001025 PyMem_Free(p);
1026}
1027
Pablo Galindo2b74c832020-04-27 18:02:07 +01001028static int
1029compute_parser_flags(PyCompilerFlags *flags)
1030{
1031 int parser_flags = 0;
1032 if (!flags) {
1033 return 0;
1034 }
1035 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1036 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1037 }
1038 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1039 parser_flags |= PyPARSE_IGNORE_COOKIE;
1040 }
1041 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1042 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1043 }
1044 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1045 parser_flags |= PyPARSE_TYPE_COMMENTS;
1046 }
Guido van Rossum2a1ee1d2020-06-27 17:34:30 -07001047 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001048 parser_flags |= PyPARSE_ASYNC_HACKS;
1049 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001050 return parser_flags;
1051}
1052
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001053Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001054_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001055 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001056{
1057 Parser *p = PyMem_Malloc(sizeof(Parser));
1058 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001059 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001060 }
1061 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001062 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1063 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001064 p->tok = tok;
1065 p->keywords = NULL;
1066 p->n_keyword_lists = -1;
1067 p->tokens = PyMem_Malloc(sizeof(Token *));
1068 if (!p->tokens) {
1069 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001070 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001071 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001072 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001073 if (!p->tokens) {
1074 PyMem_Free(p->tokens);
1075 PyMem_Free(p);
1076 return (Parser *) PyErr_NoMemory();
1077 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001078 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1079 PyMem_Free(p->tokens[0]);
1080 PyMem_Free(p->tokens);
1081 PyMem_Free(p);
1082 return (Parser *) PyErr_NoMemory();
1083 }
1084
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001085 p->mark = 0;
1086 p->fill = 0;
1087 p->size = 1;
1088
1089 p->errcode = errcode;
1090 p->arena = arena;
1091 p->start_rule = start_rule;
1092 p->parsing_started = 0;
1093 p->normalize = NULL;
1094 p->error_indicator = 0;
1095
1096 p->starting_lineno = 0;
1097 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001098 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001099 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001100 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001101 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001102
1103 return p;
1104}
1105
1106void *
1107_PyPegen_run_parser(Parser *p)
1108{
1109 void *res = _PyPegen_parse(p);
1110 if (res == NULL) {
1111 if (PyErr_Occurred()) {
1112 return NULL;
1113 }
1114 if (p->fill == 0) {
1115 RAISE_SYNTAX_ERROR("error at start before reading any input");
1116 }
1117 else if (p->tok->done == E_EOF) {
1118 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1119 }
1120 else {
1121 if (p->tokens[p->fill-1]->type == INDENT) {
1122 RAISE_INDENTATION_ERROR("unexpected indent");
1123 }
1124 else if (p->tokens[p->fill-1]->type == DEDENT) {
1125 RAISE_INDENTATION_ERROR("unexpected unindent");
1126 }
1127 else {
1128 RAISE_SYNTAX_ERROR("invalid syntax");
1129 }
1130 }
1131 return NULL;
1132 }
1133
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001134 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1135 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1136 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1137 }
1138
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001139 return res;
1140}
1141
1142mod_ty
1143_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1144 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001145 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001146{
1147 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1148 if (tok == NULL) {
1149 if (PyErr_Occurred()) {
1150 raise_tokenizer_init_error(filename_ob);
1151 return NULL;
1152 }
1153 return NULL;
1154 }
1155 // This transfers the ownership to the tokenizer
1156 tok->filename = filename_ob;
1157 Py_INCREF(filename_ob);
1158
1159 // From here on we need to clean up even if there's an error
1160 mod_ty result = NULL;
1161
Pablo Galindo2b74c832020-04-27 18:02:07 +01001162 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001163 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1164 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001165 if (p == NULL) {
1166 goto error;
1167 }
1168
1169 result = _PyPegen_run_parser(p);
1170 _PyPegen_Parser_Free(p);
1171
1172error:
1173 PyTokenizer_Free(tok);
1174 return result;
1175}
1176
1177mod_ty
1178_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001179 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001180{
1181 FILE *fp = fopen(filename, "rb");
1182 if (fp == NULL) {
1183 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1184 return NULL;
1185 }
1186
1187 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001188 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001189
1190 fclose(fp);
1191 return result;
1192}
1193
1194mod_ty
1195_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001196 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001197{
1198 int exec_input = start_rule == Py_file_input;
1199
1200 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001201 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001202 tok = PyTokenizer_FromUTF8(str, exec_input);
1203 } else {
1204 tok = PyTokenizer_FromString(str, exec_input);
1205 }
1206 if (tok == NULL) {
1207 if (PyErr_Occurred()) {
1208 raise_tokenizer_init_error(filename_ob);
1209 }
1210 return NULL;
1211 }
1212 // This transfers the ownership to the tokenizer
1213 tok->filename = filename_ob;
1214 Py_INCREF(filename_ob);
1215
1216 // We need to clear up from here on
1217 mod_ty result = NULL;
1218
Pablo Galindo2b74c832020-04-27 18:02:07 +01001219 int parser_flags = compute_parser_flags(flags);
Guido van Rossum2a1ee1d2020-06-27 17:34:30 -07001220 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1221 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001222 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1223 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001224 if (p == NULL) {
1225 goto error;
1226 }
1227
1228 result = _PyPegen_run_parser(p);
1229 _PyPegen_Parser_Free(p);
1230
1231error:
1232 PyTokenizer_Free(tok);
1233 return result;
1234}
1235
1236void *
1237_PyPegen_interactive_exit(Parser *p)
1238{
1239 if (p->errcode) {
1240 *(p->errcode) = E_EOF;
1241 }
1242 return NULL;
1243}
1244
1245/* Creates a single-element asdl_seq* that contains a */
1246asdl_seq *
1247_PyPegen_singleton_seq(Parser *p, void *a)
1248{
1249 assert(a != NULL);
1250 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1251 if (!seq) {
1252 return NULL;
1253 }
1254 asdl_seq_SET(seq, 0, a);
1255 return seq;
1256}
1257
1258/* Creates a copy of seq and prepends a to it */
1259asdl_seq *
1260_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1261{
1262 assert(a != NULL);
1263 if (!seq) {
1264 return _PyPegen_singleton_seq(p, a);
1265 }
1266
1267 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1268 if (!new_seq) {
1269 return NULL;
1270 }
1271
1272 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001273 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001274 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1275 }
1276 return new_seq;
1277}
1278
Guido van Rossumc001c092020-04-30 12:12:19 -07001279/* Creates a copy of seq and appends a to it */
1280asdl_seq *
1281_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1282{
1283 assert(a != NULL);
1284 if (!seq) {
1285 return _PyPegen_singleton_seq(p, a);
1286 }
1287
1288 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1289 if (!new_seq) {
1290 return NULL;
1291 }
1292
1293 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1294 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1295 }
1296 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1297 return new_seq;
1298}
1299
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001300static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001301_get_flattened_seq_size(asdl_seq *seqs)
1302{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001303 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001304 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1305 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1306 size += asdl_seq_LEN(inner_seq);
1307 }
1308 return size;
1309}
1310
1311/* Flattens an asdl_seq* of asdl_seq*s */
1312asdl_seq *
1313_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1314{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001315 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001316 assert(flattened_seq_size > 0);
1317
1318 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1319 if (!flattened_seq) {
1320 return NULL;
1321 }
1322
1323 int flattened_seq_idx = 0;
1324 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1325 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001326 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001327 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1328 }
1329 }
1330 assert(flattened_seq_idx == flattened_seq_size);
1331
1332 return flattened_seq;
1333}
1334
1335/* Creates a new name of the form <first_name>.<second_name> */
1336expr_ty
1337_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1338{
1339 assert(first_name != NULL && second_name != NULL);
1340 PyObject *first_identifier = first_name->v.Name.id;
1341 PyObject *second_identifier = second_name->v.Name.id;
1342
1343 if (PyUnicode_READY(first_identifier) == -1) {
1344 return NULL;
1345 }
1346 if (PyUnicode_READY(second_identifier) == -1) {
1347 return NULL;
1348 }
1349 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1350 if (!first_str) {
1351 return NULL;
1352 }
1353 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1354 if (!second_str) {
1355 return NULL;
1356 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001357 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001358
1359 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1360 if (!str) {
1361 return NULL;
1362 }
1363
1364 char *s = PyBytes_AS_STRING(str);
1365 if (!s) {
1366 return NULL;
1367 }
1368
1369 strcpy(s, first_str);
1370 s += strlen(first_str);
1371 *s++ = '.';
1372 strcpy(s, second_str);
1373 s += strlen(second_str);
1374 *s = '\0';
1375
1376 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1377 Py_DECREF(str);
1378 if (!uni) {
1379 return NULL;
1380 }
1381 PyUnicode_InternInPlace(&uni);
1382 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1383 Py_DECREF(uni);
1384 return NULL;
1385 }
1386
1387 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1388}
1389
1390/* Counts the total number of dots in seq's tokens */
1391int
1392_PyPegen_seq_count_dots(asdl_seq *seq)
1393{
1394 int number_of_dots = 0;
1395 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1396 Token *current_expr = asdl_seq_GET(seq, i);
1397 switch (current_expr->type) {
1398 case ELLIPSIS:
1399 number_of_dots += 3;
1400 break;
1401 case DOT:
1402 number_of_dots += 1;
1403 break;
1404 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001405 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001406 }
1407 }
1408
1409 return number_of_dots;
1410}
1411
1412/* Creates an alias with '*' as the identifier name */
1413alias_ty
1414_PyPegen_alias_for_star(Parser *p)
1415{
1416 PyObject *str = PyUnicode_InternFromString("*");
1417 if (!str) {
1418 return NULL;
1419 }
1420 if (PyArena_AddPyObject(p->arena, str) < 0) {
1421 Py_DECREF(str);
1422 return NULL;
1423 }
1424 return alias(str, NULL, p->arena);
1425}
1426
1427/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1428asdl_seq *
1429_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1430{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001431 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001432 assert(len > 0);
1433
1434 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1435 if (!new_seq) {
1436 return NULL;
1437 }
1438 for (Py_ssize_t i = 0; i < len; i++) {
1439 expr_ty e = asdl_seq_GET(seq, i);
1440 asdl_seq_SET(new_seq, i, e->v.Name.id);
1441 }
1442 return new_seq;
1443}
1444
1445/* Constructs a CmpopExprPair */
1446CmpopExprPair *
1447_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1448{
1449 assert(expr != NULL);
1450 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1451 if (!a) {
1452 return NULL;
1453 }
1454 a->cmpop = cmpop;
1455 a->expr = expr;
1456 return a;
1457}
1458
1459asdl_int_seq *
1460_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1461{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001462 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001463 assert(len > 0);
1464
1465 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1466 if (!new_seq) {
1467 return NULL;
1468 }
1469 for (Py_ssize_t i = 0; i < len; i++) {
1470 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1471 asdl_seq_SET(new_seq, i, pair->cmpop);
1472 }
1473 return new_seq;
1474}
1475
1476asdl_seq *
1477_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1478{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001479 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001480 assert(len > 0);
1481
1482 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1483 if (!new_seq) {
1484 return NULL;
1485 }
1486 for (Py_ssize_t i = 0; i < len; i++) {
1487 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1488 asdl_seq_SET(new_seq, i, pair->expr);
1489 }
1490 return new_seq;
1491}
1492
1493/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1494static asdl_seq *
1495_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1496{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001497 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001498 if (len == 0) {
1499 return NULL;
1500 }
1501
1502 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1503 if (!new_seq) {
1504 return NULL;
1505 }
1506 for (Py_ssize_t i = 0; i < len; i++) {
1507 expr_ty e = asdl_seq_GET(seq, i);
1508 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1509 }
1510 return new_seq;
1511}
1512
1513static expr_ty
1514_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1515{
1516 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1517}
1518
1519static expr_ty
1520_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1521{
1522 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1523}
1524
1525static expr_ty
1526_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1527{
1528 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1529}
1530
1531static expr_ty
1532_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1533{
1534 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1535}
1536
1537static expr_ty
1538_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1539{
1540 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1541}
1542
1543static expr_ty
1544_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1545{
1546 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1547}
1548
1549/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1550expr_ty
1551_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1552{
1553 assert(expr != NULL);
1554
1555 expr_ty new = NULL;
1556 switch (expr->kind) {
1557 case Name_kind:
1558 new = _set_name_context(p, expr, ctx);
1559 break;
1560 case Tuple_kind:
1561 new = _set_tuple_context(p, expr, ctx);
1562 break;
1563 case List_kind:
1564 new = _set_list_context(p, expr, ctx);
1565 break;
1566 case Subscript_kind:
1567 new = _set_subscript_context(p, expr, ctx);
1568 break;
1569 case Attribute_kind:
1570 new = _set_attribute_context(p, expr, ctx);
1571 break;
1572 case Starred_kind:
1573 new = _set_starred_context(p, expr, ctx);
1574 break;
1575 default:
1576 new = expr;
1577 }
1578 return new;
1579}
1580
1581/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1582KeyValuePair *
1583_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1584{
1585 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1586 if (!a) {
1587 return NULL;
1588 }
1589 a->key = key;
1590 a->value = value;
1591 return a;
1592}
1593
1594/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1595asdl_seq *
1596_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1597{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001598 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001599 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1600 if (!new_seq) {
1601 return NULL;
1602 }
1603 for (Py_ssize_t i = 0; i < len; i++) {
1604 KeyValuePair *pair = asdl_seq_GET(seq, i);
1605 asdl_seq_SET(new_seq, i, pair->key);
1606 }
1607 return new_seq;
1608}
1609
1610/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1611asdl_seq *
1612_PyPegen_get_values(Parser *p, asdl_seq *seq)
1613{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001614 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001615 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1616 if (!new_seq) {
1617 return NULL;
1618 }
1619 for (Py_ssize_t i = 0; i < len; i++) {
1620 KeyValuePair *pair = asdl_seq_GET(seq, i);
1621 asdl_seq_SET(new_seq, i, pair->value);
1622 }
1623 return new_seq;
1624}
1625
1626/* Constructs a NameDefaultPair */
1627NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001628_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001629{
1630 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1631 if (!a) {
1632 return NULL;
1633 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001634 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001635 a->value = value;
1636 return a;
1637}
1638
1639/* Constructs a SlashWithDefault */
1640SlashWithDefault *
1641_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1642{
1643 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1644 if (!a) {
1645 return NULL;
1646 }
1647 a->plain_names = plain_names;
1648 a->names_with_defaults = names_with_defaults;
1649 return a;
1650}
1651
1652/* Constructs a StarEtc */
1653StarEtc *
1654_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1655{
1656 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1657 if (!a) {
1658 return NULL;
1659 }
1660 a->vararg = vararg;
1661 a->kwonlyargs = kwonlyargs;
1662 a->kwarg = kwarg;
1663 return a;
1664}
1665
1666asdl_seq *
1667_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1668{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001669 Py_ssize_t first_len = asdl_seq_LEN(a);
1670 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001671 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1672 if (!new_seq) {
1673 return NULL;
1674 }
1675
1676 int k = 0;
1677 for (Py_ssize_t i = 0; i < first_len; i++) {
1678 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1679 }
1680 for (Py_ssize_t i = 0; i < second_len; i++) {
1681 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1682 }
1683
1684 return new_seq;
1685}
1686
1687static asdl_seq *
1688_get_names(Parser *p, asdl_seq *names_with_defaults)
1689{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001690 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001691 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1692 if (!seq) {
1693 return NULL;
1694 }
1695 for (Py_ssize_t i = 0; i < len; i++) {
1696 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1697 asdl_seq_SET(seq, i, pair->arg);
1698 }
1699 return seq;
1700}
1701
1702static asdl_seq *
1703_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1704{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001705 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001706 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1707 if (!seq) {
1708 return NULL;
1709 }
1710 for (Py_ssize_t i = 0; i < len; i++) {
1711 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1712 asdl_seq_SET(seq, i, pair->value);
1713 }
1714 return seq;
1715}
1716
1717/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1718arguments_ty
1719_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1720 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1721 asdl_seq *names_with_default, StarEtc *star_etc)
1722{
1723 asdl_seq *posonlyargs;
1724 if (slash_without_default != NULL) {
1725 posonlyargs = slash_without_default;
1726 }
1727 else if (slash_with_default != NULL) {
1728 asdl_seq *slash_with_default_names =
1729 _get_names(p, slash_with_default->names_with_defaults);
1730 if (!slash_with_default_names) {
1731 return NULL;
1732 }
1733 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1734 if (!posonlyargs) {
1735 return NULL;
1736 }
1737 }
1738 else {
1739 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1740 if (!posonlyargs) {
1741 return NULL;
1742 }
1743 }
1744
1745 asdl_seq *posargs;
1746 if (plain_names != NULL && names_with_default != NULL) {
1747 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1748 if (!names_with_default_names) {
1749 return NULL;
1750 }
1751 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1752 if (!posargs) {
1753 return NULL;
1754 }
1755 }
1756 else if (plain_names == NULL && names_with_default != NULL) {
1757 posargs = _get_names(p, names_with_default);
1758 if (!posargs) {
1759 return NULL;
1760 }
1761 }
1762 else if (plain_names != NULL && names_with_default == NULL) {
1763 posargs = plain_names;
1764 }
1765 else {
1766 posargs = _Py_asdl_seq_new(0, p->arena);
1767 if (!posargs) {
1768 return NULL;
1769 }
1770 }
1771
1772 asdl_seq *posdefaults;
1773 if (slash_with_default != NULL && names_with_default != NULL) {
1774 asdl_seq *slash_with_default_values =
1775 _get_defaults(p, slash_with_default->names_with_defaults);
1776 if (!slash_with_default_values) {
1777 return NULL;
1778 }
1779 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1780 if (!names_with_default_values) {
1781 return NULL;
1782 }
1783 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1784 if (!posdefaults) {
1785 return NULL;
1786 }
1787 }
1788 else if (slash_with_default == NULL && names_with_default != NULL) {
1789 posdefaults = _get_defaults(p, names_with_default);
1790 if (!posdefaults) {
1791 return NULL;
1792 }
1793 }
1794 else if (slash_with_default != NULL && names_with_default == NULL) {
1795 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1796 if (!posdefaults) {
1797 return NULL;
1798 }
1799 }
1800 else {
1801 posdefaults = _Py_asdl_seq_new(0, p->arena);
1802 if (!posdefaults) {
1803 return NULL;
1804 }
1805 }
1806
1807 arg_ty vararg = NULL;
1808 if (star_etc != NULL && star_etc->vararg != NULL) {
1809 vararg = star_etc->vararg;
1810 }
1811
1812 asdl_seq *kwonlyargs;
1813 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1814 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1815 if (!kwonlyargs) {
1816 return NULL;
1817 }
1818 }
1819 else {
1820 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1821 if (!kwonlyargs) {
1822 return NULL;
1823 }
1824 }
1825
1826 asdl_seq *kwdefaults;
1827 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1828 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1829 if (!kwdefaults) {
1830 return NULL;
1831 }
1832 }
1833 else {
1834 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1835 if (!kwdefaults) {
1836 return NULL;
1837 }
1838 }
1839
1840 arg_ty kwarg = NULL;
1841 if (star_etc != NULL && star_etc->kwarg != NULL) {
1842 kwarg = star_etc->kwarg;
1843 }
1844
1845 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1846 posdefaults, p->arena);
1847}
1848
1849/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1850 * arguments. */
1851arguments_ty
1852_PyPegen_empty_arguments(Parser *p)
1853{
1854 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1855 if (!posonlyargs) {
1856 return NULL;
1857 }
1858 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1859 if (!posargs) {
1860 return NULL;
1861 }
1862 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1863 if (!posdefaults) {
1864 return NULL;
1865 }
1866 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1867 if (!kwonlyargs) {
1868 return NULL;
1869 }
1870 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1871 if (!kwdefaults) {
1872 return NULL;
1873 }
1874
1875 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1876 p->arena);
1877}
1878
1879/* Encapsulates the value of an operator_ty into an AugOperator struct */
1880AugOperator *
1881_PyPegen_augoperator(Parser *p, operator_ty kind)
1882{
1883 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1884 if (!a) {
1885 return NULL;
1886 }
1887 a->kind = kind;
1888 return a;
1889}
1890
1891/* Construct a FunctionDef equivalent to function_def, but with decorators */
1892stmt_ty
1893_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1894{
1895 assert(function_def != NULL);
1896 if (function_def->kind == AsyncFunctionDef_kind) {
1897 return _Py_AsyncFunctionDef(
1898 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1899 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1900 function_def->v.FunctionDef.type_comment, function_def->lineno,
1901 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1902 p->arena);
1903 }
1904
1905 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1906 function_def->v.FunctionDef.body, decorators,
1907 function_def->v.FunctionDef.returns,
1908 function_def->v.FunctionDef.type_comment, function_def->lineno,
1909 function_def->col_offset, function_def->end_lineno,
1910 function_def->end_col_offset, p->arena);
1911}
1912
1913/* Construct a ClassDef equivalent to class_def, but with decorators */
1914stmt_ty
1915_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1916{
1917 assert(class_def != NULL);
1918 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1919 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1920 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1921 class_def->end_col_offset, p->arena);
1922}
1923
1924/* Construct a KeywordOrStarred */
1925KeywordOrStarred *
1926_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1927{
1928 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1929 if (!a) {
1930 return NULL;
1931 }
1932 a->element = element;
1933 a->is_keyword = is_keyword;
1934 return a;
1935}
1936
1937/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1938static int
1939_seq_number_of_starred_exprs(asdl_seq *seq)
1940{
1941 int n = 0;
1942 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1943 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1944 if (!k->is_keyword) {
1945 n++;
1946 }
1947 }
1948 return n;
1949}
1950
1951/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1952asdl_seq *
1953_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1954{
1955 int new_len = _seq_number_of_starred_exprs(kwargs);
1956 if (new_len == 0) {
1957 return NULL;
1958 }
1959 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1960 if (!new_seq) {
1961 return NULL;
1962 }
1963
1964 int idx = 0;
1965 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1966 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1967 if (!k->is_keyword) {
1968 asdl_seq_SET(new_seq, idx++, k->element);
1969 }
1970 }
1971 return new_seq;
1972}
1973
1974/* Return a new asdl_seq* with only the keywords in kwargs */
1975asdl_seq *
1976_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1977{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001978 Py_ssize_t len = asdl_seq_LEN(kwargs);
1979 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001980 if (new_len == 0) {
1981 return NULL;
1982 }
1983 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1984 if (!new_seq) {
1985 return NULL;
1986 }
1987
1988 int idx = 0;
1989 for (Py_ssize_t i = 0; i < len; i++) {
1990 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1991 if (k->is_keyword) {
1992 asdl_seq_SET(new_seq, idx++, k->element);
1993 }
1994 }
1995 return new_seq;
1996}
1997
1998expr_ty
1999_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2000{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002001 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002002 assert(len > 0);
2003
2004 Token *first = asdl_seq_GET(strings, 0);
2005 Token *last = asdl_seq_GET(strings, len - 1);
2006
2007 int bytesmode = 0;
2008 PyObject *bytes_str = NULL;
2009
2010 FstringParser state;
2011 _PyPegen_FstringParser_Init(&state);
2012
2013 for (Py_ssize_t i = 0; i < len; i++) {
2014 Token *t = asdl_seq_GET(strings, i);
2015
2016 int this_bytesmode;
2017 int this_rawmode;
2018 PyObject *s;
2019 const char *fstr;
2020 Py_ssize_t fstrlen = -1;
2021
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002022 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002023 goto error;
2024 }
2025
2026 /* Check that we are not mixing bytes with unicode. */
2027 if (i != 0 && bytesmode != this_bytesmode) {
2028 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2029 Py_XDECREF(s);
2030 goto error;
2031 }
2032 bytesmode = this_bytesmode;
2033
2034 if (fstr != NULL) {
2035 assert(s == NULL && !bytesmode);
2036
2037 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2038 this_rawmode, 0, first, t, last);
2039 if (result < 0) {
2040 goto error;
2041 }
2042 }
2043 else {
2044 /* String or byte string. */
2045 assert(s != NULL && fstr == NULL);
2046 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2047
2048 if (bytesmode) {
2049 if (i == 0) {
2050 bytes_str = s;
2051 }
2052 else {
2053 PyBytes_ConcatAndDel(&bytes_str, s);
2054 if (!bytes_str) {
2055 goto error;
2056 }
2057 }
2058 }
2059 else {
2060 /* This is a regular string. Concatenate it. */
2061 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2062 goto error;
2063 }
2064 }
2065 }
2066 }
2067
2068 if (bytesmode) {
2069 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2070 goto error;
2071 }
2072 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2073 last->end_col_offset, p->arena);
2074 }
2075
2076 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2077
2078error:
2079 Py_XDECREF(bytes_str);
2080 _PyPegen_FstringParser_Dealloc(&state);
2081 if (PyErr_Occurred()) {
2082 raise_decode_error(p);
2083 }
2084 return NULL;
2085}
Guido van Rossumc001c092020-04-30 12:12:19 -07002086
2087mod_ty
2088_PyPegen_make_module(Parser *p, asdl_seq *a) {
2089 asdl_seq *type_ignores = NULL;
2090 Py_ssize_t num = p->type_ignore_comments.num_items;
2091 if (num > 0) {
2092 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2093 type_ignores = _Py_asdl_seq_new(num, p->arena);
2094 if (type_ignores == NULL) {
2095 return NULL;
2096 }
2097 for (int i = 0; i < num; i++) {
2098 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2099 if (tag == NULL) {
2100 return NULL;
2101 }
2102 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2103 if (ti == NULL) {
2104 return NULL;
2105 }
2106 asdl_seq_SET(type_ignores, i, ti);
2107 }
2108 }
2109 return Module(a, type_ignores, p->arena);
2110}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002111
2112// Error reporting helpers
2113
2114expr_ty
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002115_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002116{
2117 if (e == NULL) {
2118 return NULL;
2119 }
2120
2121#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2122 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2123 for (Py_ssize_t i = 0; i < len; i++) {\
2124 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002125 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002126 if (child != NULL) {\
2127 return child;\
2128 }\
2129 }\
2130 } while (0)
2131
2132 // We only need to visit List and Tuple nodes recursively as those
2133 // are the only ones that can contain valid names in targets when
2134 // they are parsed as expressions. Any other kind of expression
2135 // that is a container (like Sets or Dicts) is directly invalid and
2136 // we don't need to visit it recursively.
2137
2138 switch (e->kind) {
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002139 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002140 VISIT_CONTAINER(e, List);
2141 return NULL;
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002142 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002143 VISIT_CONTAINER(e, Tuple);
2144 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002145 case Starred_kind:
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002146 if (targets_type == DEL_TARGETS) {
2147 return e;
2148 }
2149 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2150 case Compare_kind:
2151 // This is needed, because the `a in b` in `for a in b` gets parsed
2152 // as a comparison, and so we need to search the left side of the comparison
2153 // for invalid targets.
2154 if (targets_type == FOR_TARGETS) {
2155 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2156 if (cmpop == In) {
2157 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2158 }
2159 return NULL;
2160 }
2161 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002162 case Name_kind:
2163 case Subscript_kind:
2164 case Attribute_kind:
2165 return NULL;
2166 default:
2167 return e;
2168 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002169}
2170
2171void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2172 int kwarg_unpacking = 0;
2173 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2174 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2175 if (!keyword->arg) {
2176 kwarg_unpacking = 1;
2177 }
2178 }
2179
2180 const char *msg = NULL;
2181 if (kwarg_unpacking) {
2182 msg = "positional argument follows keyword argument unpacking";
2183 } else {
2184 msg = "positional argument follows keyword argument";
2185 }
2186
2187 return RAISE_SYNTAX_ERROR(msg);
2188}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002189
2190void *
2191_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2192{
2193 /* The rule that calls this function is 'args for_if_clauses'.
2194 For the input f(L, x for x in y), L and x are in args and
2195 the for is parsed as a for_if_clause. We have to check if
2196 len <= 1, so that input like dict((a, b) for a, b in x)
2197 gets successfully parsed and then we pass the last
2198 argument (x in the above example) as the location of the
2199 error */
2200 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2201 if (len <= 1) {
2202 return NULL;
2203 }
2204
2205 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2206 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2207 "Generator expression must be parenthesized"
2208 );
2209}