blob: ef48ade5453829f449efda6913cad9c5e1ca7cfa [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{
528 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
529 return NAME;
530 }
531 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
532 if (strncmp(k->str, name, name_len) == 0) {
533 return k->type;
534 }
535 }
536 return NAME;
537}
538
Guido van Rossumc001c092020-04-30 12:12:19 -0700539static int
540growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
541 assert(initial_size > 0);
542 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
543 arr->size = initial_size;
544 arr->num_items = 0;
545
546 return arr->items != NULL;
547}
548
549static int
550growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
551 if (arr->num_items >= arr->size) {
552 size_t new_size = arr->size * 2;
553 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
554 if (!new_items_array) {
555 return 0;
556 }
557 arr->items = new_items_array;
558 arr->size = new_size;
559 }
560
561 arr->items[arr->num_items].lineno = lineno;
562 arr->items[arr->num_items].comment = comment; // Take ownership
563 arr->num_items++;
564 return 1;
565}
566
567static void
568growable_comment_array_deallocate(growable_comment_array *arr) {
569 for (unsigned i = 0; i < arr->num_items; i++) {
570 PyMem_Free(arr->items[i].comment);
571 }
572 PyMem_Free(arr->items);
573}
574
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100575int
576_PyPegen_fill_token(Parser *p)
577{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100578 const char *start;
579 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100580 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700581
582 // Record and skip '# type: ignore' comments
583 while (type == TYPE_IGNORE) {
584 Py_ssize_t len = end - start;
585 char *tag = PyMem_Malloc(len + 1);
586 if (tag == NULL) {
587 PyErr_NoMemory();
588 return -1;
589 }
590 strncpy(tag, start, len);
591 tag[len] = '\0';
592 // Ownership of tag passes to the growable array
593 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
594 PyErr_NoMemory();
595 return -1;
596 }
597 type = PyTokenizer_Get(p->tok, &start, &end);
598 }
599
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100600 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
601 type = NEWLINE; /* Add an extra newline */
602 p->parsing_started = 0;
603
Pablo Galindob94dbd72020-04-27 18:35:58 +0100604 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100605 p->tok->pendin = -p->tok->indent;
606 p->tok->indent = 0;
607 }
608 }
609 else {
610 p->parsing_started = 1;
611 }
612
613 if (p->fill == p->size) {
614 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300615 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
616 if (new_tokens == NULL) {
617 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100618 return -1;
619 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100620 p->tokens = new_tokens;
621
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100622 for (int i = p->size; i < newsize; i++) {
623 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300624 if (p->tokens[i] == NULL) {
625 p->size = i; // Needed, in order to cleanup correctly after parser fails
626 PyErr_NoMemory();
627 return -1;
628 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100629 memset(p->tokens[i], '\0', sizeof(Token));
630 }
631 p->size = newsize;
632 }
633
634 Token *t = p->tokens[p->fill];
635 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
636 t->bytes = PyBytes_FromStringAndSize(start, end - start);
637 if (t->bytes == NULL) {
638 return -1;
639 }
640 PyArena_AddPyObject(p->arena, t->bytes);
641
642 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
643 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100644 int end_lineno = p->tok->lineno;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100645 int col_offset = -1;
646 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100647 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100648 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100649 }
650 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100651 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100652 }
653
654 t->lineno = p->starting_lineno + lineno;
655 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
656 t->end_lineno = p->starting_lineno + end_lineno;
657 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
658
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100659 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300660
661 if (type == ERRORTOKEN) {
662 if (p->tok->done == E_DECODE) {
663 return raise_decode_error(p);
664 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100665 return tokenizer_error(p);
666
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300667 }
668
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100669 return 0;
670}
671
672// Instrumentation to count the effectiveness of memoization.
673// The array counts the number of tokens skipped by memoization,
674// indexed by type.
675
676#define NSTATISTICS 2000
677static long memo_statistics[NSTATISTICS];
678
679void
680_PyPegen_clear_memo_statistics()
681{
682 for (int i = 0; i < NSTATISTICS; i++) {
683 memo_statistics[i] = 0;
684 }
685}
686
687PyObject *
688_PyPegen_get_memo_statistics()
689{
690 PyObject *ret = PyList_New(NSTATISTICS);
691 if (ret == NULL) {
692 return NULL;
693 }
694 for (int i = 0; i < NSTATISTICS; i++) {
695 PyObject *value = PyLong_FromLong(memo_statistics[i]);
696 if (value == NULL) {
697 Py_DECREF(ret);
698 return NULL;
699 }
700 // PyList_SetItem borrows a reference to value.
701 if (PyList_SetItem(ret, i, value) < 0) {
702 Py_DECREF(ret);
703 return NULL;
704 }
705 }
706 return ret;
707}
708
709int // bool
710_PyPegen_is_memoized(Parser *p, int type, void *pres)
711{
712 if (p->mark == p->fill) {
713 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300714 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100715 return -1;
716 }
717 }
718
719 Token *t = p->tokens[p->mark];
720
721 for (Memo *m = t->memo; m != NULL; m = m->next) {
722 if (m->type == type) {
723 if (0 <= type && type < NSTATISTICS) {
724 long count = m->mark - p->mark;
725 // A memoized negative result counts for one.
726 if (count <= 0) {
727 count = 1;
728 }
729 memo_statistics[type] += count;
730 }
731 p->mark = m->mark;
732 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100733 return 1;
734 }
735 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100736 return 0;
737}
738
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100739int
740_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
741{
742 int mark = p->mark;
743 void *res = func(p);
744 p->mark = mark;
745 return (res != NULL) == positive;
746}
747
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100748int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300749_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
750{
751 int mark = p->mark;
752 void *res = func(p, arg);
753 p->mark = mark;
754 return (res != NULL) == positive;
755}
756
757int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100758_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
759{
760 int mark = p->mark;
761 void *res = func(p, arg);
762 p->mark = mark;
763 return (res != NULL) == positive;
764}
765
766int
767_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
768{
769 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100770 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100771 p->mark = mark;
772 return (res != NULL) == positive;
773}
774
775Token *
776_PyPegen_expect_token(Parser *p, int type)
777{
778 if (p->mark == p->fill) {
779 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300780 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100781 return NULL;
782 }
783 }
784 Token *t = p->tokens[p->mark];
785 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100786 return NULL;
787 }
788 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100789 return t;
790}
791
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300792expr_ty
793_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
794{
795 if (p->mark == p->fill) {
796 if (_PyPegen_fill_token(p) < 0) {
797 p->error_indicator = 1;
798 return NULL;
799 }
800 }
801 Token *t = p->tokens[p->mark];
802 if (t->type != NAME) {
803 return NULL;
804 }
805 char* s = PyBytes_AsString(t->bytes);
806 if (!s) {
807 p->error_indicator = 1;
808 return NULL;
809 }
810 if (strcmp(s, keyword) != 0) {
811 return NULL;
812 }
813 return _PyPegen_name_token(p);
814}
815
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100816Token *
817_PyPegen_get_last_nonnwhitespace_token(Parser *p)
818{
819 assert(p->mark >= 0);
820 Token *token = NULL;
821 for (int m = p->mark - 1; m >= 0; m--) {
822 token = p->tokens[m];
823 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
824 break;
825 }
826 }
827 return token;
828}
829
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100830expr_ty
831_PyPegen_name_token(Parser *p)
832{
833 Token *t = _PyPegen_expect_token(p, NAME);
834 if (t == NULL) {
835 return NULL;
836 }
837 char* s = PyBytes_AsString(t->bytes);
838 if (!s) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300839 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100840 return NULL;
841 }
842 PyObject *id = _PyPegen_new_identifier(p, s);
843 if (id == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300844 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100845 return NULL;
846 }
847 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
848 p->arena);
849}
850
851void *
852_PyPegen_string_token(Parser *p)
853{
854 return _PyPegen_expect_token(p, STRING);
855}
856
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100857static PyObject *
858parsenumber_raw(const char *s)
859{
860 const char *end;
861 long x;
862 double dx;
863 Py_complex compl;
864 int imflag;
865
866 assert(s != NULL);
867 errno = 0;
868 end = s + strlen(s) - 1;
869 imflag = *end == 'j' || *end == 'J';
870 if (s[0] == '0') {
871 x = (long)PyOS_strtoul(s, (char **)&end, 0);
872 if (x < 0 && errno == 0) {
873 return PyLong_FromString(s, (char **)0, 0);
874 }
875 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100876 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100877 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100878 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100879 if (*end == '\0') {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100880 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100881 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100882 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100883 return PyLong_FromLong(x);
884 }
885 /* XXX Huge floats may silently fail */
886 if (imflag) {
887 compl.real = 0.;
888 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100889 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100890 return NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100891 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100892 return PyComplex_FromCComplex(compl);
893 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100894 dx = PyOS_string_to_double(s, NULL, NULL);
895 if (dx == -1.0 && PyErr_Occurred()) {
896 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100897 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100898 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100899}
900
901static PyObject *
902parsenumber(const char *s)
903{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100904 char *dup;
905 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100906 PyObject *res = NULL;
907
908 assert(s != NULL);
909
910 if (strchr(s, '_') == NULL) {
911 return parsenumber_raw(s);
912 }
913 /* Create a duplicate without underscores. */
914 dup = PyMem_Malloc(strlen(s) + 1);
915 if (dup == NULL) {
916 return PyErr_NoMemory();
917 }
918 end = dup;
919 for (; *s; s++) {
920 if (*s != '_') {
921 *end++ = *s;
922 }
923 }
924 *end = '\0';
925 res = parsenumber_raw(dup);
926 PyMem_Free(dup);
927 return res;
928}
929
930expr_ty
931_PyPegen_number_token(Parser *p)
932{
933 Token *t = _PyPegen_expect_token(p, NUMBER);
934 if (t == NULL) {
935 return NULL;
936 }
937
938 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100939 if (num_raw == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300940 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100941 return NULL;
942 }
943
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300944 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
945 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700946 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300947 "in Python 3.6 and greater");
948 }
949
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100950 PyObject *c = parsenumber(num_raw);
951
952 if (c == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300953 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100954 return NULL;
955 }
956
957 if (PyArena_AddPyObject(p->arena, c) < 0) {
958 Py_DECREF(c);
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300959 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100960 return NULL;
961 }
962
963 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
964 p->arena);
965}
966
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300967static int // bool
968newline_in_string(Parser *p, const char *cur)
969{
Miss Islington (bot)15fec562020-06-05 17:13:14 -0700970 for (const char *c = cur; c >= p->tok->buf; c--) {
971 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300972 return 1;
973 }
974 }
975 return 0;
976}
977
978/* Check that the source for a single input statement really is a single
979 statement by looking at what is left in the buffer after parsing.
980 Trailing whitespace and comments are OK. */
981static int // bool
982bad_single_statement(Parser *p)
983{
984 const char *cur = strchr(p->tok->buf, '\n');
985
986 /* Newlines are allowed if preceded by a line continuation character
987 or if they appear inside a string. */
988 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
989 return 0;
990 }
991 char c = *cur;
992
993 for (;;) {
994 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
995 c = *++cur;
996 }
997
998 if (!c) {
999 return 0;
1000 }
1001
1002 if (c != '#') {
1003 return 1;
1004 }
1005
1006 /* Suck up comment. */
1007 while (c && c != '\n') {
1008 c = *++cur;
1009 }
1010 }
1011}
1012
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001013void
1014_PyPegen_Parser_Free(Parser *p)
1015{
1016 Py_XDECREF(p->normalize);
1017 for (int i = 0; i < p->size; i++) {
1018 PyMem_Free(p->tokens[i]);
1019 }
1020 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001021 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001022 PyMem_Free(p);
1023}
1024
Pablo Galindo2b74c832020-04-27 18:02:07 +01001025static int
1026compute_parser_flags(PyCompilerFlags *flags)
1027{
1028 int parser_flags = 0;
1029 if (!flags) {
1030 return 0;
1031 }
1032 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1033 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1034 }
1035 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1036 parser_flags |= PyPARSE_IGNORE_COOKIE;
1037 }
1038 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1039 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1040 }
1041 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1042 parser_flags |= PyPARSE_TYPE_COMMENTS;
1043 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001044 if (flags->cf_feature_version < 7) {
1045 parser_flags |= PyPARSE_ASYNC_HACKS;
1046 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001047 return parser_flags;
1048}
1049
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001050Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001051_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001052 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001053{
1054 Parser *p = PyMem_Malloc(sizeof(Parser));
1055 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001056 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001057 }
1058 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001059 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1060 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001061 p->tok = tok;
1062 p->keywords = NULL;
1063 p->n_keyword_lists = -1;
1064 p->tokens = PyMem_Malloc(sizeof(Token *));
1065 if (!p->tokens) {
1066 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001067 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001068 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001069 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001070 if (!p->tokens) {
1071 PyMem_Free(p->tokens);
1072 PyMem_Free(p);
1073 return (Parser *) PyErr_NoMemory();
1074 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001075 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1076 PyMem_Free(p->tokens[0]);
1077 PyMem_Free(p->tokens);
1078 PyMem_Free(p);
1079 return (Parser *) PyErr_NoMemory();
1080 }
1081
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001082 p->mark = 0;
1083 p->fill = 0;
1084 p->size = 1;
1085
1086 p->errcode = errcode;
1087 p->arena = arena;
1088 p->start_rule = start_rule;
1089 p->parsing_started = 0;
1090 p->normalize = NULL;
1091 p->error_indicator = 0;
1092
1093 p->starting_lineno = 0;
1094 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001095 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001096 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001097 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001098 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001099
1100 return p;
1101}
1102
1103void *
1104_PyPegen_run_parser(Parser *p)
1105{
1106 void *res = _PyPegen_parse(p);
1107 if (res == NULL) {
1108 if (PyErr_Occurred()) {
1109 return NULL;
1110 }
1111 if (p->fill == 0) {
1112 RAISE_SYNTAX_ERROR("error at start before reading any input");
1113 }
1114 else if (p->tok->done == E_EOF) {
1115 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1116 }
1117 else {
1118 if (p->tokens[p->fill-1]->type == INDENT) {
1119 RAISE_INDENTATION_ERROR("unexpected indent");
1120 }
1121 else if (p->tokens[p->fill-1]->type == DEDENT) {
1122 RAISE_INDENTATION_ERROR("unexpected unindent");
1123 }
1124 else {
1125 RAISE_SYNTAX_ERROR("invalid syntax");
1126 }
1127 }
1128 return NULL;
1129 }
1130
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001131 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1132 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1133 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1134 }
1135
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001136 return res;
1137}
1138
1139mod_ty
1140_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1141 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001142 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001143{
1144 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1145 if (tok == NULL) {
1146 if (PyErr_Occurred()) {
1147 raise_tokenizer_init_error(filename_ob);
1148 return NULL;
1149 }
1150 return NULL;
1151 }
1152 // This transfers the ownership to the tokenizer
1153 tok->filename = filename_ob;
1154 Py_INCREF(filename_ob);
1155
1156 // From here on we need to clean up even if there's an error
1157 mod_ty result = NULL;
1158
Pablo Galindo2b74c832020-04-27 18:02:07 +01001159 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001160 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1161 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001162 if (p == NULL) {
1163 goto error;
1164 }
1165
1166 result = _PyPegen_run_parser(p);
1167 _PyPegen_Parser_Free(p);
1168
1169error:
1170 PyTokenizer_Free(tok);
1171 return result;
1172}
1173
1174mod_ty
1175_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001176 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001177{
1178 FILE *fp = fopen(filename, "rb");
1179 if (fp == NULL) {
1180 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1181 return NULL;
1182 }
1183
1184 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001185 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001186
1187 fclose(fp);
1188 return result;
1189}
1190
1191mod_ty
1192_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001193 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001194{
1195 int exec_input = start_rule == Py_file_input;
1196
1197 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001198 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001199 tok = PyTokenizer_FromUTF8(str, exec_input);
1200 } else {
1201 tok = PyTokenizer_FromString(str, exec_input);
1202 }
1203 if (tok == NULL) {
1204 if (PyErr_Occurred()) {
1205 raise_tokenizer_init_error(filename_ob);
1206 }
1207 return NULL;
1208 }
1209 // This transfers the ownership to the tokenizer
1210 tok->filename = filename_ob;
1211 Py_INCREF(filename_ob);
1212
1213 // We need to clear up from here on
1214 mod_ty result = NULL;
1215
Pablo Galindo2b74c832020-04-27 18:02:07 +01001216 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001217 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001218 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1219 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001220 if (p == NULL) {
1221 goto error;
1222 }
1223
1224 result = _PyPegen_run_parser(p);
1225 _PyPegen_Parser_Free(p);
1226
1227error:
1228 PyTokenizer_Free(tok);
1229 return result;
1230}
1231
1232void *
1233_PyPegen_interactive_exit(Parser *p)
1234{
1235 if (p->errcode) {
1236 *(p->errcode) = E_EOF;
1237 }
1238 return NULL;
1239}
1240
1241/* Creates a single-element asdl_seq* that contains a */
1242asdl_seq *
1243_PyPegen_singleton_seq(Parser *p, void *a)
1244{
1245 assert(a != NULL);
1246 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1247 if (!seq) {
1248 return NULL;
1249 }
1250 asdl_seq_SET(seq, 0, a);
1251 return seq;
1252}
1253
1254/* Creates a copy of seq and prepends a to it */
1255asdl_seq *
1256_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1257{
1258 assert(a != NULL);
1259 if (!seq) {
1260 return _PyPegen_singleton_seq(p, a);
1261 }
1262
1263 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1264 if (!new_seq) {
1265 return NULL;
1266 }
1267
1268 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001269 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001270 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1271 }
1272 return new_seq;
1273}
1274
Guido van Rossumc001c092020-04-30 12:12:19 -07001275/* Creates a copy of seq and appends a to it */
1276asdl_seq *
1277_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1278{
1279 assert(a != NULL);
1280 if (!seq) {
1281 return _PyPegen_singleton_seq(p, a);
1282 }
1283
1284 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1285 if (!new_seq) {
1286 return NULL;
1287 }
1288
1289 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1290 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1291 }
1292 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1293 return new_seq;
1294}
1295
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001296static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001297_get_flattened_seq_size(asdl_seq *seqs)
1298{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001299 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001300 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1301 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1302 size += asdl_seq_LEN(inner_seq);
1303 }
1304 return size;
1305}
1306
1307/* Flattens an asdl_seq* of asdl_seq*s */
1308asdl_seq *
1309_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1310{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001311 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001312 assert(flattened_seq_size > 0);
1313
1314 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1315 if (!flattened_seq) {
1316 return NULL;
1317 }
1318
1319 int flattened_seq_idx = 0;
1320 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1321 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001322 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001323 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1324 }
1325 }
1326 assert(flattened_seq_idx == flattened_seq_size);
1327
1328 return flattened_seq;
1329}
1330
1331/* Creates a new name of the form <first_name>.<second_name> */
1332expr_ty
1333_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1334{
1335 assert(first_name != NULL && second_name != NULL);
1336 PyObject *first_identifier = first_name->v.Name.id;
1337 PyObject *second_identifier = second_name->v.Name.id;
1338
1339 if (PyUnicode_READY(first_identifier) == -1) {
1340 return NULL;
1341 }
1342 if (PyUnicode_READY(second_identifier) == -1) {
1343 return NULL;
1344 }
1345 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1346 if (!first_str) {
1347 return NULL;
1348 }
1349 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1350 if (!second_str) {
1351 return NULL;
1352 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001353 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001354
1355 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1356 if (!str) {
1357 return NULL;
1358 }
1359
1360 char *s = PyBytes_AS_STRING(str);
1361 if (!s) {
1362 return NULL;
1363 }
1364
1365 strcpy(s, first_str);
1366 s += strlen(first_str);
1367 *s++ = '.';
1368 strcpy(s, second_str);
1369 s += strlen(second_str);
1370 *s = '\0';
1371
1372 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1373 Py_DECREF(str);
1374 if (!uni) {
1375 return NULL;
1376 }
1377 PyUnicode_InternInPlace(&uni);
1378 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1379 Py_DECREF(uni);
1380 return NULL;
1381 }
1382
1383 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1384}
1385
1386/* Counts the total number of dots in seq's tokens */
1387int
1388_PyPegen_seq_count_dots(asdl_seq *seq)
1389{
1390 int number_of_dots = 0;
1391 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1392 Token *current_expr = asdl_seq_GET(seq, i);
1393 switch (current_expr->type) {
1394 case ELLIPSIS:
1395 number_of_dots += 3;
1396 break;
1397 case DOT:
1398 number_of_dots += 1;
1399 break;
1400 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001401 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001402 }
1403 }
1404
1405 return number_of_dots;
1406}
1407
1408/* Creates an alias with '*' as the identifier name */
1409alias_ty
1410_PyPegen_alias_for_star(Parser *p)
1411{
1412 PyObject *str = PyUnicode_InternFromString("*");
1413 if (!str) {
1414 return NULL;
1415 }
1416 if (PyArena_AddPyObject(p->arena, str) < 0) {
1417 Py_DECREF(str);
1418 return NULL;
1419 }
1420 return alias(str, NULL, p->arena);
1421}
1422
1423/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1424asdl_seq *
1425_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1426{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001427 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001428 assert(len > 0);
1429
1430 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1431 if (!new_seq) {
1432 return NULL;
1433 }
1434 for (Py_ssize_t i = 0; i < len; i++) {
1435 expr_ty e = asdl_seq_GET(seq, i);
1436 asdl_seq_SET(new_seq, i, e->v.Name.id);
1437 }
1438 return new_seq;
1439}
1440
1441/* Constructs a CmpopExprPair */
1442CmpopExprPair *
1443_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1444{
1445 assert(expr != NULL);
1446 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1447 if (!a) {
1448 return NULL;
1449 }
1450 a->cmpop = cmpop;
1451 a->expr = expr;
1452 return a;
1453}
1454
1455asdl_int_seq *
1456_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1457{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001458 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001459 assert(len > 0);
1460
1461 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1462 if (!new_seq) {
1463 return NULL;
1464 }
1465 for (Py_ssize_t i = 0; i < len; i++) {
1466 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1467 asdl_seq_SET(new_seq, i, pair->cmpop);
1468 }
1469 return new_seq;
1470}
1471
1472asdl_seq *
1473_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1474{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001475 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001476 assert(len > 0);
1477
1478 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1479 if (!new_seq) {
1480 return NULL;
1481 }
1482 for (Py_ssize_t i = 0; i < len; i++) {
1483 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1484 asdl_seq_SET(new_seq, i, pair->expr);
1485 }
1486 return new_seq;
1487}
1488
1489/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1490static asdl_seq *
1491_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1492{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001493 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001494 if (len == 0) {
1495 return NULL;
1496 }
1497
1498 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1499 if (!new_seq) {
1500 return NULL;
1501 }
1502 for (Py_ssize_t i = 0; i < len; i++) {
1503 expr_ty e = asdl_seq_GET(seq, i);
1504 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1505 }
1506 return new_seq;
1507}
1508
1509static expr_ty
1510_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1511{
1512 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1513}
1514
1515static expr_ty
1516_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1517{
1518 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1519}
1520
1521static expr_ty
1522_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1523{
1524 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1525}
1526
1527static expr_ty
1528_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1529{
1530 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1531}
1532
1533static expr_ty
1534_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1535{
1536 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1537}
1538
1539static expr_ty
1540_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1541{
1542 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1543}
1544
1545/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1546expr_ty
1547_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1548{
1549 assert(expr != NULL);
1550
1551 expr_ty new = NULL;
1552 switch (expr->kind) {
1553 case Name_kind:
1554 new = _set_name_context(p, expr, ctx);
1555 break;
1556 case Tuple_kind:
1557 new = _set_tuple_context(p, expr, ctx);
1558 break;
1559 case List_kind:
1560 new = _set_list_context(p, expr, ctx);
1561 break;
1562 case Subscript_kind:
1563 new = _set_subscript_context(p, expr, ctx);
1564 break;
1565 case Attribute_kind:
1566 new = _set_attribute_context(p, expr, ctx);
1567 break;
1568 case Starred_kind:
1569 new = _set_starred_context(p, expr, ctx);
1570 break;
1571 default:
1572 new = expr;
1573 }
1574 return new;
1575}
1576
1577/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1578KeyValuePair *
1579_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1580{
1581 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1582 if (!a) {
1583 return NULL;
1584 }
1585 a->key = key;
1586 a->value = value;
1587 return a;
1588}
1589
1590/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1591asdl_seq *
1592_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1593{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001594 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001595 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1596 if (!new_seq) {
1597 return NULL;
1598 }
1599 for (Py_ssize_t i = 0; i < len; i++) {
1600 KeyValuePair *pair = asdl_seq_GET(seq, i);
1601 asdl_seq_SET(new_seq, i, pair->key);
1602 }
1603 return new_seq;
1604}
1605
1606/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1607asdl_seq *
1608_PyPegen_get_values(Parser *p, asdl_seq *seq)
1609{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001610 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001611 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1612 if (!new_seq) {
1613 return NULL;
1614 }
1615 for (Py_ssize_t i = 0; i < len; i++) {
1616 KeyValuePair *pair = asdl_seq_GET(seq, i);
1617 asdl_seq_SET(new_seq, i, pair->value);
1618 }
1619 return new_seq;
1620}
1621
1622/* Constructs a NameDefaultPair */
1623NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001624_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001625{
1626 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1627 if (!a) {
1628 return NULL;
1629 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001630 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001631 a->value = value;
1632 return a;
1633}
1634
1635/* Constructs a SlashWithDefault */
1636SlashWithDefault *
1637_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1638{
1639 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1640 if (!a) {
1641 return NULL;
1642 }
1643 a->plain_names = plain_names;
1644 a->names_with_defaults = names_with_defaults;
1645 return a;
1646}
1647
1648/* Constructs a StarEtc */
1649StarEtc *
1650_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1651{
1652 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1653 if (!a) {
1654 return NULL;
1655 }
1656 a->vararg = vararg;
1657 a->kwonlyargs = kwonlyargs;
1658 a->kwarg = kwarg;
1659 return a;
1660}
1661
1662asdl_seq *
1663_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1664{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001665 Py_ssize_t first_len = asdl_seq_LEN(a);
1666 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001667 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1668 if (!new_seq) {
1669 return NULL;
1670 }
1671
1672 int k = 0;
1673 for (Py_ssize_t i = 0; i < first_len; i++) {
1674 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1675 }
1676 for (Py_ssize_t i = 0; i < second_len; i++) {
1677 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1678 }
1679
1680 return new_seq;
1681}
1682
1683static asdl_seq *
1684_get_names(Parser *p, asdl_seq *names_with_defaults)
1685{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001686 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001687 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1688 if (!seq) {
1689 return NULL;
1690 }
1691 for (Py_ssize_t i = 0; i < len; i++) {
1692 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1693 asdl_seq_SET(seq, i, pair->arg);
1694 }
1695 return seq;
1696}
1697
1698static asdl_seq *
1699_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1700{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001701 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001702 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1703 if (!seq) {
1704 return NULL;
1705 }
1706 for (Py_ssize_t i = 0; i < len; i++) {
1707 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1708 asdl_seq_SET(seq, i, pair->value);
1709 }
1710 return seq;
1711}
1712
1713/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1714arguments_ty
1715_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1716 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1717 asdl_seq *names_with_default, StarEtc *star_etc)
1718{
1719 asdl_seq *posonlyargs;
1720 if (slash_without_default != NULL) {
1721 posonlyargs = slash_without_default;
1722 }
1723 else if (slash_with_default != NULL) {
1724 asdl_seq *slash_with_default_names =
1725 _get_names(p, slash_with_default->names_with_defaults);
1726 if (!slash_with_default_names) {
1727 return NULL;
1728 }
1729 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1730 if (!posonlyargs) {
1731 return NULL;
1732 }
1733 }
1734 else {
1735 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1736 if (!posonlyargs) {
1737 return NULL;
1738 }
1739 }
1740
1741 asdl_seq *posargs;
1742 if (plain_names != NULL && names_with_default != NULL) {
1743 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1744 if (!names_with_default_names) {
1745 return NULL;
1746 }
1747 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1748 if (!posargs) {
1749 return NULL;
1750 }
1751 }
1752 else if (plain_names == NULL && names_with_default != NULL) {
1753 posargs = _get_names(p, names_with_default);
1754 if (!posargs) {
1755 return NULL;
1756 }
1757 }
1758 else if (plain_names != NULL && names_with_default == NULL) {
1759 posargs = plain_names;
1760 }
1761 else {
1762 posargs = _Py_asdl_seq_new(0, p->arena);
1763 if (!posargs) {
1764 return NULL;
1765 }
1766 }
1767
1768 asdl_seq *posdefaults;
1769 if (slash_with_default != NULL && names_with_default != NULL) {
1770 asdl_seq *slash_with_default_values =
1771 _get_defaults(p, slash_with_default->names_with_defaults);
1772 if (!slash_with_default_values) {
1773 return NULL;
1774 }
1775 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1776 if (!names_with_default_values) {
1777 return NULL;
1778 }
1779 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1780 if (!posdefaults) {
1781 return NULL;
1782 }
1783 }
1784 else if (slash_with_default == NULL && names_with_default != NULL) {
1785 posdefaults = _get_defaults(p, names_with_default);
1786 if (!posdefaults) {
1787 return NULL;
1788 }
1789 }
1790 else if (slash_with_default != NULL && names_with_default == NULL) {
1791 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1792 if (!posdefaults) {
1793 return NULL;
1794 }
1795 }
1796 else {
1797 posdefaults = _Py_asdl_seq_new(0, p->arena);
1798 if (!posdefaults) {
1799 return NULL;
1800 }
1801 }
1802
1803 arg_ty vararg = NULL;
1804 if (star_etc != NULL && star_etc->vararg != NULL) {
1805 vararg = star_etc->vararg;
1806 }
1807
1808 asdl_seq *kwonlyargs;
1809 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1810 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1811 if (!kwonlyargs) {
1812 return NULL;
1813 }
1814 }
1815 else {
1816 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1817 if (!kwonlyargs) {
1818 return NULL;
1819 }
1820 }
1821
1822 asdl_seq *kwdefaults;
1823 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1824 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1825 if (!kwdefaults) {
1826 return NULL;
1827 }
1828 }
1829 else {
1830 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1831 if (!kwdefaults) {
1832 return NULL;
1833 }
1834 }
1835
1836 arg_ty kwarg = NULL;
1837 if (star_etc != NULL && star_etc->kwarg != NULL) {
1838 kwarg = star_etc->kwarg;
1839 }
1840
1841 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1842 posdefaults, p->arena);
1843}
1844
1845/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1846 * arguments. */
1847arguments_ty
1848_PyPegen_empty_arguments(Parser *p)
1849{
1850 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1851 if (!posonlyargs) {
1852 return NULL;
1853 }
1854 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1855 if (!posargs) {
1856 return NULL;
1857 }
1858 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1859 if (!posdefaults) {
1860 return NULL;
1861 }
1862 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1863 if (!kwonlyargs) {
1864 return NULL;
1865 }
1866 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1867 if (!kwdefaults) {
1868 return NULL;
1869 }
1870
1871 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1872 p->arena);
1873}
1874
1875/* Encapsulates the value of an operator_ty into an AugOperator struct */
1876AugOperator *
1877_PyPegen_augoperator(Parser *p, operator_ty kind)
1878{
1879 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1880 if (!a) {
1881 return NULL;
1882 }
1883 a->kind = kind;
1884 return a;
1885}
1886
1887/* Construct a FunctionDef equivalent to function_def, but with decorators */
1888stmt_ty
1889_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1890{
1891 assert(function_def != NULL);
1892 if (function_def->kind == AsyncFunctionDef_kind) {
1893 return _Py_AsyncFunctionDef(
1894 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1895 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1896 function_def->v.FunctionDef.type_comment, function_def->lineno,
1897 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1898 p->arena);
1899 }
1900
1901 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1902 function_def->v.FunctionDef.body, decorators,
1903 function_def->v.FunctionDef.returns,
1904 function_def->v.FunctionDef.type_comment, function_def->lineno,
1905 function_def->col_offset, function_def->end_lineno,
1906 function_def->end_col_offset, p->arena);
1907}
1908
1909/* Construct a ClassDef equivalent to class_def, but with decorators */
1910stmt_ty
1911_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1912{
1913 assert(class_def != NULL);
1914 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1915 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1916 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1917 class_def->end_col_offset, p->arena);
1918}
1919
1920/* Construct a KeywordOrStarred */
1921KeywordOrStarred *
1922_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1923{
1924 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1925 if (!a) {
1926 return NULL;
1927 }
1928 a->element = element;
1929 a->is_keyword = is_keyword;
1930 return a;
1931}
1932
1933/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1934static int
1935_seq_number_of_starred_exprs(asdl_seq *seq)
1936{
1937 int n = 0;
1938 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1939 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1940 if (!k->is_keyword) {
1941 n++;
1942 }
1943 }
1944 return n;
1945}
1946
1947/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1948asdl_seq *
1949_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1950{
1951 int new_len = _seq_number_of_starred_exprs(kwargs);
1952 if (new_len == 0) {
1953 return NULL;
1954 }
1955 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1956 if (!new_seq) {
1957 return NULL;
1958 }
1959
1960 int idx = 0;
1961 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1962 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1963 if (!k->is_keyword) {
1964 asdl_seq_SET(new_seq, idx++, k->element);
1965 }
1966 }
1967 return new_seq;
1968}
1969
1970/* Return a new asdl_seq* with only the keywords in kwargs */
1971asdl_seq *
1972_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1973{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001974 Py_ssize_t len = asdl_seq_LEN(kwargs);
1975 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001976 if (new_len == 0) {
1977 return NULL;
1978 }
1979 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1980 if (!new_seq) {
1981 return NULL;
1982 }
1983
1984 int idx = 0;
1985 for (Py_ssize_t i = 0; i < len; i++) {
1986 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1987 if (k->is_keyword) {
1988 asdl_seq_SET(new_seq, idx++, k->element);
1989 }
1990 }
1991 return new_seq;
1992}
1993
1994expr_ty
1995_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1996{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001997 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001998 assert(len > 0);
1999
2000 Token *first = asdl_seq_GET(strings, 0);
2001 Token *last = asdl_seq_GET(strings, len - 1);
2002
2003 int bytesmode = 0;
2004 PyObject *bytes_str = NULL;
2005
2006 FstringParser state;
2007 _PyPegen_FstringParser_Init(&state);
2008
2009 for (Py_ssize_t i = 0; i < len; i++) {
2010 Token *t = asdl_seq_GET(strings, i);
2011
2012 int this_bytesmode;
2013 int this_rawmode;
2014 PyObject *s;
2015 const char *fstr;
2016 Py_ssize_t fstrlen = -1;
2017
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002018 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002019 goto error;
2020 }
2021
2022 /* Check that we are not mixing bytes with unicode. */
2023 if (i != 0 && bytesmode != this_bytesmode) {
2024 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2025 Py_XDECREF(s);
2026 goto error;
2027 }
2028 bytesmode = this_bytesmode;
2029
2030 if (fstr != NULL) {
2031 assert(s == NULL && !bytesmode);
2032
2033 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2034 this_rawmode, 0, first, t, last);
2035 if (result < 0) {
2036 goto error;
2037 }
2038 }
2039 else {
2040 /* String or byte string. */
2041 assert(s != NULL && fstr == NULL);
2042 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2043
2044 if (bytesmode) {
2045 if (i == 0) {
2046 bytes_str = s;
2047 }
2048 else {
2049 PyBytes_ConcatAndDel(&bytes_str, s);
2050 if (!bytes_str) {
2051 goto error;
2052 }
2053 }
2054 }
2055 else {
2056 /* This is a regular string. Concatenate it. */
2057 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2058 goto error;
2059 }
2060 }
2061 }
2062 }
2063
2064 if (bytesmode) {
2065 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2066 goto error;
2067 }
2068 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2069 last->end_col_offset, p->arena);
2070 }
2071
2072 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2073
2074error:
2075 Py_XDECREF(bytes_str);
2076 _PyPegen_FstringParser_Dealloc(&state);
2077 if (PyErr_Occurred()) {
2078 raise_decode_error(p);
2079 }
2080 return NULL;
2081}
Guido van Rossumc001c092020-04-30 12:12:19 -07002082
2083mod_ty
2084_PyPegen_make_module(Parser *p, asdl_seq *a) {
2085 asdl_seq *type_ignores = NULL;
2086 Py_ssize_t num = p->type_ignore_comments.num_items;
2087 if (num > 0) {
2088 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2089 type_ignores = _Py_asdl_seq_new(num, p->arena);
2090 if (type_ignores == NULL) {
2091 return NULL;
2092 }
2093 for (int i = 0; i < num; i++) {
2094 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2095 if (tag == NULL) {
2096 return NULL;
2097 }
2098 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2099 if (ti == NULL) {
2100 return NULL;
2101 }
2102 asdl_seq_SET(type_ignores, i, ti);
2103 }
2104 }
2105 return Module(a, type_ignores, p->arena);
2106}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002107
2108// Error reporting helpers
2109
2110expr_ty
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002111_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002112{
2113 if (e == NULL) {
2114 return NULL;
2115 }
2116
2117#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2118 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2119 for (Py_ssize_t i = 0; i < len; i++) {\
2120 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002121 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002122 if (child != NULL) {\
2123 return child;\
2124 }\
2125 }\
2126 } while (0)
2127
2128 // We only need to visit List and Tuple nodes recursively as those
2129 // are the only ones that can contain valid names in targets when
2130 // they are parsed as expressions. Any other kind of expression
2131 // that is a container (like Sets or Dicts) is directly invalid and
2132 // we don't need to visit it recursively.
2133
2134 switch (e->kind) {
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002135 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002136 VISIT_CONTAINER(e, List);
2137 return NULL;
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002138 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002139 VISIT_CONTAINER(e, Tuple);
2140 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002141 case Starred_kind:
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002142 if (targets_type == DEL_TARGETS) {
2143 return e;
2144 }
2145 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2146 case Compare_kind:
2147 // This is needed, because the `a in b` in `for a in b` gets parsed
2148 // as a comparison, and so we need to search the left side of the comparison
2149 // for invalid targets.
2150 if (targets_type == FOR_TARGETS) {
2151 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2152 if (cmpop == In) {
2153 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2154 }
2155 return NULL;
2156 }
2157 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002158 case Name_kind:
2159 case Subscript_kind:
2160 case Attribute_kind:
2161 return NULL;
2162 default:
2163 return e;
2164 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002165}
2166
2167void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2168 int kwarg_unpacking = 0;
2169 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2170 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2171 if (!keyword->arg) {
2172 kwarg_unpacking = 1;
2173 }
2174 }
2175
2176 const char *msg = NULL;
2177 if (kwarg_unpacking) {
2178 msg = "positional argument follows keyword argument unpacking";
2179 } else {
2180 msg = "positional argument follows keyword argument";
2181 }
2182
2183 return RAISE_SYNTAX_ERROR(msg);
2184}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002185
2186void *
2187_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2188{
2189 /* The rule that calls this function is 'args for_if_clauses'.
2190 For the input f(L, x for x in y), L and x are in args and
2191 the for is parsed as a for_if_clause. We have to check if
2192 len <= 1, so that input like dict((a, b) for a, b in x)
2193 gets successfully parsed and then we pass the last
2194 argument (x in the above example) as the location of the
2195 error */
2196 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2197 if (len <= 1) {
2198 return NULL;
2199 }
2200
2201 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2202 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2203 "Generator expression must be parenthesized"
2204 );
2205}