blob: 53591d2c79fe1bad11a71e84d84bd39858286221 [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
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700426 Py_ssize_t col_number = col_offset;
427
428 if (p->tok->encoding != NULL) {
429 col_number = byte_offset_to_character_offset(error_line, col_offset);
430 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300431
432 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100433 if (!tmp) {
434 goto error;
435 }
436 value = PyTuple_Pack(2, errstr, tmp);
437 Py_DECREF(tmp);
438 if (!value) {
439 goto error;
440 }
441 PyErr_SetObject(errtype, value);
442
443 Py_DECREF(errstr);
444 Py_DECREF(value);
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700445 if (p->start_rule == Py_fstring_input) {
446 PyMem_RawFree((void *)errmsg);
447 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100448 return NULL;
449
450error:
451 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300452 Py_XDECREF(error_line);
Miss Islington (bot)cb0dc522020-06-27 12:43:49 -0700453 if (p->start_rule == Py_fstring_input) {
454 PyMem_RawFree((void *)errmsg);
455 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100456 return NULL;
457}
458
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100459#if 0
460static const char *
461token_name(int type)
462{
463 if (0 <= type && type <= N_TOKENS) {
464 return _PyParser_TokenNames[type];
465 }
466 return "<Huh?>";
467}
468#endif
469
470// Here, mark is the start of the node, while p->mark is the end.
471// If node==NULL, they should be the same.
472int
473_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
474{
475 // Insert in front
476 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
477 if (m == NULL) {
478 return -1;
479 }
480 m->type = type;
481 m->node = node;
482 m->mark = p->mark;
483 m->next = p->tokens[mark]->memo;
484 p->tokens[mark]->memo = m;
485 return 0;
486}
487
488// Like _PyPegen_insert_memo(), but updates an existing node if found.
489int
490_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
491{
492 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
493 if (m->type == type) {
494 // Update existing node.
495 m->node = node;
496 m->mark = p->mark;
497 return 0;
498 }
499 }
500 // Insert new node.
501 return _PyPegen_insert_memo(p, mark, type, node);
502}
503
504// Return dummy NAME.
505void *
506_PyPegen_dummy_name(Parser *p, ...)
507{
508 static void *cache = NULL;
509
510 if (cache != NULL) {
511 return cache;
512 }
513
514 PyObject *id = _create_dummy_identifier(p);
515 if (!id) {
516 return NULL;
517 }
518 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
519 return cache;
520}
521
522static int
523_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
524{
525 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
526 return NAME;
527 }
528 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
529 if (strncmp(k->str, name, name_len) == 0) {
530 return k->type;
531 }
532 }
533 return NAME;
534}
535
Guido van Rossumc001c092020-04-30 12:12:19 -0700536static int
537growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
538 assert(initial_size > 0);
539 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
540 arr->size = initial_size;
541 arr->num_items = 0;
542
543 return arr->items != NULL;
544}
545
546static int
547growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
548 if (arr->num_items >= arr->size) {
549 size_t new_size = arr->size * 2;
550 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
551 if (!new_items_array) {
552 return 0;
553 }
554 arr->items = new_items_array;
555 arr->size = new_size;
556 }
557
558 arr->items[arr->num_items].lineno = lineno;
559 arr->items[arr->num_items].comment = comment; // Take ownership
560 arr->num_items++;
561 return 1;
562}
563
564static void
565growable_comment_array_deallocate(growable_comment_array *arr) {
566 for (unsigned i = 0; i < arr->num_items; i++) {
567 PyMem_Free(arr->items[i].comment);
568 }
569 PyMem_Free(arr->items);
570}
571
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100572int
573_PyPegen_fill_token(Parser *p)
574{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100575 const char *start;
576 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100577 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700578
579 // Record and skip '# type: ignore' comments
580 while (type == TYPE_IGNORE) {
581 Py_ssize_t len = end - start;
582 char *tag = PyMem_Malloc(len + 1);
583 if (tag == NULL) {
584 PyErr_NoMemory();
585 return -1;
586 }
587 strncpy(tag, start, len);
588 tag[len] = '\0';
589 // Ownership of tag passes to the growable array
590 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
591 PyErr_NoMemory();
592 return -1;
593 }
594 type = PyTokenizer_Get(p->tok, &start, &end);
595 }
596
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100597 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
598 type = NEWLINE; /* Add an extra newline */
599 p->parsing_started = 0;
600
Pablo Galindob94dbd72020-04-27 18:35:58 +0100601 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100602 p->tok->pendin = -p->tok->indent;
603 p->tok->indent = 0;
604 }
605 }
606 else {
607 p->parsing_started = 1;
608 }
609
610 if (p->fill == p->size) {
611 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300612 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
613 if (new_tokens == NULL) {
614 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100615 return -1;
616 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100617 p->tokens = new_tokens;
618
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100619 for (int i = p->size; i < newsize; i++) {
620 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300621 if (p->tokens[i] == NULL) {
622 p->size = i; // Needed, in order to cleanup correctly after parser fails
623 PyErr_NoMemory();
624 return -1;
625 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100626 memset(p->tokens[i], '\0', sizeof(Token));
627 }
628 p->size = newsize;
629 }
630
631 Token *t = p->tokens[p->fill];
632 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
633 t->bytes = PyBytes_FromStringAndSize(start, end - start);
634 if (t->bytes == NULL) {
635 return -1;
636 }
637 PyArena_AddPyObject(p->arena, t->bytes);
638
639 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
640 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100641 int end_lineno = p->tok->lineno;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100642 int col_offset = -1;
643 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100644 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100645 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100646 }
647 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100648 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100649 }
650
651 t->lineno = p->starting_lineno + lineno;
652 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
653 t->end_lineno = p->starting_lineno + end_lineno;
654 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
655
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100656 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300657
658 if (type == ERRORTOKEN) {
659 if (p->tok->done == E_DECODE) {
660 return raise_decode_error(p);
661 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100662 return tokenizer_error(p);
663
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300664 }
665
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100666 return 0;
667}
668
669// Instrumentation to count the effectiveness of memoization.
670// The array counts the number of tokens skipped by memoization,
671// indexed by type.
672
673#define NSTATISTICS 2000
674static long memo_statistics[NSTATISTICS];
675
676void
677_PyPegen_clear_memo_statistics()
678{
679 for (int i = 0; i < NSTATISTICS; i++) {
680 memo_statistics[i] = 0;
681 }
682}
683
684PyObject *
685_PyPegen_get_memo_statistics()
686{
687 PyObject *ret = PyList_New(NSTATISTICS);
688 if (ret == NULL) {
689 return NULL;
690 }
691 for (int i = 0; i < NSTATISTICS; i++) {
692 PyObject *value = PyLong_FromLong(memo_statistics[i]);
693 if (value == NULL) {
694 Py_DECREF(ret);
695 return NULL;
696 }
697 // PyList_SetItem borrows a reference to value.
698 if (PyList_SetItem(ret, i, value) < 0) {
699 Py_DECREF(ret);
700 return NULL;
701 }
702 }
703 return ret;
704}
705
706int // bool
707_PyPegen_is_memoized(Parser *p, int type, void *pres)
708{
709 if (p->mark == p->fill) {
710 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300711 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100712 return -1;
713 }
714 }
715
716 Token *t = p->tokens[p->mark];
717
718 for (Memo *m = t->memo; m != NULL; m = m->next) {
719 if (m->type == type) {
720 if (0 <= type && type < NSTATISTICS) {
721 long count = m->mark - p->mark;
722 // A memoized negative result counts for one.
723 if (count <= 0) {
724 count = 1;
725 }
726 memo_statistics[type] += count;
727 }
728 p->mark = m->mark;
729 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100730 return 1;
731 }
732 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100733 return 0;
734}
735
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100736int
737_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
738{
739 int mark = p->mark;
740 void *res = func(p);
741 p->mark = mark;
742 return (res != NULL) == positive;
743}
744
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100745int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300746_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
747{
748 int mark = p->mark;
749 void *res = func(p, arg);
750 p->mark = mark;
751 return (res != NULL) == positive;
752}
753
754int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100755_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
756{
757 int mark = p->mark;
758 void *res = func(p, arg);
759 p->mark = mark;
760 return (res != NULL) == positive;
761}
762
763int
764_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
765{
766 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100767 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100768 p->mark = mark;
769 return (res != NULL) == positive;
770}
771
772Token *
773_PyPegen_expect_token(Parser *p, int type)
774{
775 if (p->mark == p->fill) {
776 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300777 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100778 return NULL;
779 }
780 }
781 Token *t = p->tokens[p->mark];
782 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100783 return NULL;
784 }
785 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100786 return t;
787}
788
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300789expr_ty
790_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
791{
792 if (p->mark == p->fill) {
793 if (_PyPegen_fill_token(p) < 0) {
794 p->error_indicator = 1;
795 return NULL;
796 }
797 }
798 Token *t = p->tokens[p->mark];
799 if (t->type != NAME) {
800 return NULL;
801 }
802 char* s = PyBytes_AsString(t->bytes);
803 if (!s) {
804 p->error_indicator = 1;
805 return NULL;
806 }
807 if (strcmp(s, keyword) != 0) {
808 return NULL;
809 }
810 return _PyPegen_name_token(p);
811}
812
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100813Token *
814_PyPegen_get_last_nonnwhitespace_token(Parser *p)
815{
816 assert(p->mark >= 0);
817 Token *token = NULL;
818 for (int m = p->mark - 1; m >= 0; m--) {
819 token = p->tokens[m];
820 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
821 break;
822 }
823 }
824 return token;
825}
826
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100827expr_ty
828_PyPegen_name_token(Parser *p)
829{
830 Token *t = _PyPegen_expect_token(p, NAME);
831 if (t == NULL) {
832 return NULL;
833 }
834 char* s = PyBytes_AsString(t->bytes);
835 if (!s) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300836 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100837 return NULL;
838 }
839 PyObject *id = _PyPegen_new_identifier(p, s);
840 if (id == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300841 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100842 return NULL;
843 }
844 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
845 p->arena);
846}
847
848void *
849_PyPegen_string_token(Parser *p)
850{
851 return _PyPegen_expect_token(p, STRING);
852}
853
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100854static PyObject *
855parsenumber_raw(const char *s)
856{
857 const char *end;
858 long x;
859 double dx;
860 Py_complex compl;
861 int imflag;
862
863 assert(s != NULL);
864 errno = 0;
865 end = s + strlen(s) - 1;
866 imflag = *end == 'j' || *end == 'J';
867 if (s[0] == '0') {
868 x = (long)PyOS_strtoul(s, (char **)&end, 0);
869 if (x < 0 && errno == 0) {
870 return PyLong_FromString(s, (char **)0, 0);
871 }
872 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100873 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100874 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100875 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100876 if (*end == '\0') {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100877 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100878 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100879 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100880 return PyLong_FromLong(x);
881 }
882 /* XXX Huge floats may silently fail */
883 if (imflag) {
884 compl.real = 0.;
885 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100886 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100887 return NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100888 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100889 return PyComplex_FromCComplex(compl);
890 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100891 dx = PyOS_string_to_double(s, NULL, NULL);
892 if (dx == -1.0 && PyErr_Occurred()) {
893 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100894 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100895 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100896}
897
898static PyObject *
899parsenumber(const char *s)
900{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100901 char *dup;
902 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100903 PyObject *res = NULL;
904
905 assert(s != NULL);
906
907 if (strchr(s, '_') == NULL) {
908 return parsenumber_raw(s);
909 }
910 /* Create a duplicate without underscores. */
911 dup = PyMem_Malloc(strlen(s) + 1);
912 if (dup == NULL) {
913 return PyErr_NoMemory();
914 }
915 end = dup;
916 for (; *s; s++) {
917 if (*s != '_') {
918 *end++ = *s;
919 }
920 }
921 *end = '\0';
922 res = parsenumber_raw(dup);
923 PyMem_Free(dup);
924 return res;
925}
926
927expr_ty
928_PyPegen_number_token(Parser *p)
929{
930 Token *t = _PyPegen_expect_token(p, NUMBER);
931 if (t == NULL) {
932 return NULL;
933 }
934
935 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100936 if (num_raw == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300937 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100938 return NULL;
939 }
940
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300941 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
942 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700943 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300944 "in Python 3.6 and greater");
945 }
946
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100947 PyObject *c = parsenumber(num_raw);
948
949 if (c == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300950 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100951 return NULL;
952 }
953
954 if (PyArena_AddPyObject(p->arena, c) < 0) {
955 Py_DECREF(c);
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 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
961 p->arena);
962}
963
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300964static int // bool
965newline_in_string(Parser *p, const char *cur)
966{
Miss Islington (bot)15fec562020-06-05 17:13:14 -0700967 for (const char *c = cur; c >= p->tok->buf; c--) {
968 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300969 return 1;
970 }
971 }
972 return 0;
973}
974
975/* Check that the source for a single input statement really is a single
976 statement by looking at what is left in the buffer after parsing.
977 Trailing whitespace and comments are OK. */
978static int // bool
979bad_single_statement(Parser *p)
980{
981 const char *cur = strchr(p->tok->buf, '\n');
982
983 /* Newlines are allowed if preceded by a line continuation character
984 or if they appear inside a string. */
985 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
986 return 0;
987 }
988 char c = *cur;
989
990 for (;;) {
991 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
992 c = *++cur;
993 }
994
995 if (!c) {
996 return 0;
997 }
998
999 if (c != '#') {
1000 return 1;
1001 }
1002
1003 /* Suck up comment. */
1004 while (c && c != '\n') {
1005 c = *++cur;
1006 }
1007 }
1008}
1009
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001010void
1011_PyPegen_Parser_Free(Parser *p)
1012{
1013 Py_XDECREF(p->normalize);
1014 for (int i = 0; i < p->size; i++) {
1015 PyMem_Free(p->tokens[i]);
1016 }
1017 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001018 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001019 PyMem_Free(p);
1020}
1021
Pablo Galindo2b74c832020-04-27 18:02:07 +01001022static int
1023compute_parser_flags(PyCompilerFlags *flags)
1024{
1025 int parser_flags = 0;
1026 if (!flags) {
1027 return 0;
1028 }
1029 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1030 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1031 }
1032 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1033 parser_flags |= PyPARSE_IGNORE_COOKIE;
1034 }
1035 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1036 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1037 }
1038 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1039 parser_flags |= PyPARSE_TYPE_COMMENTS;
1040 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001041 if (flags->cf_feature_version < 7) {
1042 parser_flags |= PyPARSE_ASYNC_HACKS;
1043 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001044 return parser_flags;
1045}
1046
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001047Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001048_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001049 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001050{
1051 Parser *p = PyMem_Malloc(sizeof(Parser));
1052 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001053 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001054 }
1055 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001056 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1057 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001058 p->tok = tok;
1059 p->keywords = NULL;
1060 p->n_keyword_lists = -1;
1061 p->tokens = PyMem_Malloc(sizeof(Token *));
1062 if (!p->tokens) {
1063 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001064 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001065 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001066 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001067 if (!p->tokens) {
1068 PyMem_Free(p->tokens);
1069 PyMem_Free(p);
1070 return (Parser *) PyErr_NoMemory();
1071 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001072 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1073 PyMem_Free(p->tokens[0]);
1074 PyMem_Free(p->tokens);
1075 PyMem_Free(p);
1076 return (Parser *) PyErr_NoMemory();
1077 }
1078
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001079 p->mark = 0;
1080 p->fill = 0;
1081 p->size = 1;
1082
1083 p->errcode = errcode;
1084 p->arena = arena;
1085 p->start_rule = start_rule;
1086 p->parsing_started = 0;
1087 p->normalize = NULL;
1088 p->error_indicator = 0;
1089
1090 p->starting_lineno = 0;
1091 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001092 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001093 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001094 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001095 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001096
1097 return p;
1098}
1099
1100void *
1101_PyPegen_run_parser(Parser *p)
1102{
1103 void *res = _PyPegen_parse(p);
1104 if (res == NULL) {
1105 if (PyErr_Occurred()) {
1106 return NULL;
1107 }
1108 if (p->fill == 0) {
1109 RAISE_SYNTAX_ERROR("error at start before reading any input");
1110 }
1111 else if (p->tok->done == E_EOF) {
1112 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1113 }
1114 else {
1115 if (p->tokens[p->fill-1]->type == INDENT) {
1116 RAISE_INDENTATION_ERROR("unexpected indent");
1117 }
1118 else if (p->tokens[p->fill-1]->type == DEDENT) {
1119 RAISE_INDENTATION_ERROR("unexpected unindent");
1120 }
1121 else {
1122 RAISE_SYNTAX_ERROR("invalid syntax");
1123 }
1124 }
1125 return NULL;
1126 }
1127
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001128 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1129 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1130 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1131 }
1132
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001133 return res;
1134}
1135
1136mod_ty
1137_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1138 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001139 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001140{
1141 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1142 if (tok == NULL) {
1143 if (PyErr_Occurred()) {
1144 raise_tokenizer_init_error(filename_ob);
1145 return NULL;
1146 }
1147 return NULL;
1148 }
1149 // This transfers the ownership to the tokenizer
1150 tok->filename = filename_ob;
1151 Py_INCREF(filename_ob);
1152
1153 // From here on we need to clean up even if there's an error
1154 mod_ty result = NULL;
1155
Pablo Galindo2b74c832020-04-27 18:02:07 +01001156 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001157 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1158 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001159 if (p == NULL) {
1160 goto error;
1161 }
1162
1163 result = _PyPegen_run_parser(p);
1164 _PyPegen_Parser_Free(p);
1165
1166error:
1167 PyTokenizer_Free(tok);
1168 return result;
1169}
1170
1171mod_ty
1172_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001173 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001174{
1175 FILE *fp = fopen(filename, "rb");
1176 if (fp == NULL) {
1177 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1178 return NULL;
1179 }
1180
1181 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001182 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001183
1184 fclose(fp);
1185 return result;
1186}
1187
1188mod_ty
1189_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001190 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001191{
1192 int exec_input = start_rule == Py_file_input;
1193
1194 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001195 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001196 tok = PyTokenizer_FromUTF8(str, exec_input);
1197 } else {
1198 tok = PyTokenizer_FromString(str, exec_input);
1199 }
1200 if (tok == NULL) {
1201 if (PyErr_Occurred()) {
1202 raise_tokenizer_init_error(filename_ob);
1203 }
1204 return NULL;
1205 }
1206 // This transfers the ownership to the tokenizer
1207 tok->filename = filename_ob;
1208 Py_INCREF(filename_ob);
1209
1210 // We need to clear up from here on
1211 mod_ty result = NULL;
1212
Pablo Galindo2b74c832020-04-27 18:02:07 +01001213 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001214 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001215 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1216 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001217 if (p == NULL) {
1218 goto error;
1219 }
1220
1221 result = _PyPegen_run_parser(p);
1222 _PyPegen_Parser_Free(p);
1223
1224error:
1225 PyTokenizer_Free(tok);
1226 return result;
1227}
1228
1229void *
1230_PyPegen_interactive_exit(Parser *p)
1231{
1232 if (p->errcode) {
1233 *(p->errcode) = E_EOF;
1234 }
1235 return NULL;
1236}
1237
1238/* Creates a single-element asdl_seq* that contains a */
1239asdl_seq *
1240_PyPegen_singleton_seq(Parser *p, void *a)
1241{
1242 assert(a != NULL);
1243 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1244 if (!seq) {
1245 return NULL;
1246 }
1247 asdl_seq_SET(seq, 0, a);
1248 return seq;
1249}
1250
1251/* Creates a copy of seq and prepends a to it */
1252asdl_seq *
1253_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1254{
1255 assert(a != NULL);
1256 if (!seq) {
1257 return _PyPegen_singleton_seq(p, a);
1258 }
1259
1260 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1261 if (!new_seq) {
1262 return NULL;
1263 }
1264
1265 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001266 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001267 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1268 }
1269 return new_seq;
1270}
1271
Guido van Rossumc001c092020-04-30 12:12:19 -07001272/* Creates a copy of seq and appends a to it */
1273asdl_seq *
1274_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1275{
1276 assert(a != NULL);
1277 if (!seq) {
1278 return _PyPegen_singleton_seq(p, a);
1279 }
1280
1281 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1282 if (!new_seq) {
1283 return NULL;
1284 }
1285
1286 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1287 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1288 }
1289 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1290 return new_seq;
1291}
1292
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001293static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001294_get_flattened_seq_size(asdl_seq *seqs)
1295{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001296 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001297 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1298 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1299 size += asdl_seq_LEN(inner_seq);
1300 }
1301 return size;
1302}
1303
1304/* Flattens an asdl_seq* of asdl_seq*s */
1305asdl_seq *
1306_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1307{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001308 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001309 assert(flattened_seq_size > 0);
1310
1311 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1312 if (!flattened_seq) {
1313 return NULL;
1314 }
1315
1316 int flattened_seq_idx = 0;
1317 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1318 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001319 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001320 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1321 }
1322 }
1323 assert(flattened_seq_idx == flattened_seq_size);
1324
1325 return flattened_seq;
1326}
1327
1328/* Creates a new name of the form <first_name>.<second_name> */
1329expr_ty
1330_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1331{
1332 assert(first_name != NULL && second_name != NULL);
1333 PyObject *first_identifier = first_name->v.Name.id;
1334 PyObject *second_identifier = second_name->v.Name.id;
1335
1336 if (PyUnicode_READY(first_identifier) == -1) {
1337 return NULL;
1338 }
1339 if (PyUnicode_READY(second_identifier) == -1) {
1340 return NULL;
1341 }
1342 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1343 if (!first_str) {
1344 return NULL;
1345 }
1346 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1347 if (!second_str) {
1348 return NULL;
1349 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001350 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001351
1352 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1353 if (!str) {
1354 return NULL;
1355 }
1356
1357 char *s = PyBytes_AS_STRING(str);
1358 if (!s) {
1359 return NULL;
1360 }
1361
1362 strcpy(s, first_str);
1363 s += strlen(first_str);
1364 *s++ = '.';
1365 strcpy(s, second_str);
1366 s += strlen(second_str);
1367 *s = '\0';
1368
1369 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1370 Py_DECREF(str);
1371 if (!uni) {
1372 return NULL;
1373 }
1374 PyUnicode_InternInPlace(&uni);
1375 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1376 Py_DECREF(uni);
1377 return NULL;
1378 }
1379
1380 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1381}
1382
1383/* Counts the total number of dots in seq's tokens */
1384int
1385_PyPegen_seq_count_dots(asdl_seq *seq)
1386{
1387 int number_of_dots = 0;
1388 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1389 Token *current_expr = asdl_seq_GET(seq, i);
1390 switch (current_expr->type) {
1391 case ELLIPSIS:
1392 number_of_dots += 3;
1393 break;
1394 case DOT:
1395 number_of_dots += 1;
1396 break;
1397 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001398 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001399 }
1400 }
1401
1402 return number_of_dots;
1403}
1404
1405/* Creates an alias with '*' as the identifier name */
1406alias_ty
1407_PyPegen_alias_for_star(Parser *p)
1408{
1409 PyObject *str = PyUnicode_InternFromString("*");
1410 if (!str) {
1411 return NULL;
1412 }
1413 if (PyArena_AddPyObject(p->arena, str) < 0) {
1414 Py_DECREF(str);
1415 return NULL;
1416 }
1417 return alias(str, NULL, p->arena);
1418}
1419
1420/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1421asdl_seq *
1422_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1423{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001424 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001425 assert(len > 0);
1426
1427 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1428 if (!new_seq) {
1429 return NULL;
1430 }
1431 for (Py_ssize_t i = 0; i < len; i++) {
1432 expr_ty e = asdl_seq_GET(seq, i);
1433 asdl_seq_SET(new_seq, i, e->v.Name.id);
1434 }
1435 return new_seq;
1436}
1437
1438/* Constructs a CmpopExprPair */
1439CmpopExprPair *
1440_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1441{
1442 assert(expr != NULL);
1443 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1444 if (!a) {
1445 return NULL;
1446 }
1447 a->cmpop = cmpop;
1448 a->expr = expr;
1449 return a;
1450}
1451
1452asdl_int_seq *
1453_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1454{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001455 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001456 assert(len > 0);
1457
1458 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1459 if (!new_seq) {
1460 return NULL;
1461 }
1462 for (Py_ssize_t i = 0; i < len; i++) {
1463 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1464 asdl_seq_SET(new_seq, i, pair->cmpop);
1465 }
1466 return new_seq;
1467}
1468
1469asdl_seq *
1470_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1471{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001472 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001473 assert(len > 0);
1474
1475 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1476 if (!new_seq) {
1477 return NULL;
1478 }
1479 for (Py_ssize_t i = 0; i < len; i++) {
1480 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1481 asdl_seq_SET(new_seq, i, pair->expr);
1482 }
1483 return new_seq;
1484}
1485
1486/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1487static asdl_seq *
1488_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1489{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001490 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001491 if (len == 0) {
1492 return NULL;
1493 }
1494
1495 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1496 if (!new_seq) {
1497 return NULL;
1498 }
1499 for (Py_ssize_t i = 0; i < len; i++) {
1500 expr_ty e = asdl_seq_GET(seq, i);
1501 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1502 }
1503 return new_seq;
1504}
1505
1506static expr_ty
1507_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1508{
1509 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1510}
1511
1512static expr_ty
1513_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1514{
1515 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1516}
1517
1518static expr_ty
1519_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1520{
1521 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1522}
1523
1524static expr_ty
1525_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1526{
1527 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1528}
1529
1530static expr_ty
1531_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1532{
1533 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1534}
1535
1536static expr_ty
1537_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1538{
1539 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1540}
1541
1542/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1543expr_ty
1544_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1545{
1546 assert(expr != NULL);
1547
1548 expr_ty new = NULL;
1549 switch (expr->kind) {
1550 case Name_kind:
1551 new = _set_name_context(p, expr, ctx);
1552 break;
1553 case Tuple_kind:
1554 new = _set_tuple_context(p, expr, ctx);
1555 break;
1556 case List_kind:
1557 new = _set_list_context(p, expr, ctx);
1558 break;
1559 case Subscript_kind:
1560 new = _set_subscript_context(p, expr, ctx);
1561 break;
1562 case Attribute_kind:
1563 new = _set_attribute_context(p, expr, ctx);
1564 break;
1565 case Starred_kind:
1566 new = _set_starred_context(p, expr, ctx);
1567 break;
1568 default:
1569 new = expr;
1570 }
1571 return new;
1572}
1573
1574/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1575KeyValuePair *
1576_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1577{
1578 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1579 if (!a) {
1580 return NULL;
1581 }
1582 a->key = key;
1583 a->value = value;
1584 return a;
1585}
1586
1587/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1588asdl_seq *
1589_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1590{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001591 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001592 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1593 if (!new_seq) {
1594 return NULL;
1595 }
1596 for (Py_ssize_t i = 0; i < len; i++) {
1597 KeyValuePair *pair = asdl_seq_GET(seq, i);
1598 asdl_seq_SET(new_seq, i, pair->key);
1599 }
1600 return new_seq;
1601}
1602
1603/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1604asdl_seq *
1605_PyPegen_get_values(Parser *p, asdl_seq *seq)
1606{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001607 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001608 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1609 if (!new_seq) {
1610 return NULL;
1611 }
1612 for (Py_ssize_t i = 0; i < len; i++) {
1613 KeyValuePair *pair = asdl_seq_GET(seq, i);
1614 asdl_seq_SET(new_seq, i, pair->value);
1615 }
1616 return new_seq;
1617}
1618
1619/* Constructs a NameDefaultPair */
1620NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001621_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001622{
1623 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1624 if (!a) {
1625 return NULL;
1626 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001627 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001628 a->value = value;
1629 return a;
1630}
1631
1632/* Constructs a SlashWithDefault */
1633SlashWithDefault *
1634_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1635{
1636 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1637 if (!a) {
1638 return NULL;
1639 }
1640 a->plain_names = plain_names;
1641 a->names_with_defaults = names_with_defaults;
1642 return a;
1643}
1644
1645/* Constructs a StarEtc */
1646StarEtc *
1647_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1648{
1649 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1650 if (!a) {
1651 return NULL;
1652 }
1653 a->vararg = vararg;
1654 a->kwonlyargs = kwonlyargs;
1655 a->kwarg = kwarg;
1656 return a;
1657}
1658
1659asdl_seq *
1660_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1661{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001662 Py_ssize_t first_len = asdl_seq_LEN(a);
1663 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001664 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1665 if (!new_seq) {
1666 return NULL;
1667 }
1668
1669 int k = 0;
1670 for (Py_ssize_t i = 0; i < first_len; i++) {
1671 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1672 }
1673 for (Py_ssize_t i = 0; i < second_len; i++) {
1674 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1675 }
1676
1677 return new_seq;
1678}
1679
1680static asdl_seq *
1681_get_names(Parser *p, asdl_seq *names_with_defaults)
1682{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001683 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001684 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1685 if (!seq) {
1686 return NULL;
1687 }
1688 for (Py_ssize_t i = 0; i < len; i++) {
1689 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1690 asdl_seq_SET(seq, i, pair->arg);
1691 }
1692 return seq;
1693}
1694
1695static asdl_seq *
1696_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1697{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001698 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001699 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1700 if (!seq) {
1701 return NULL;
1702 }
1703 for (Py_ssize_t i = 0; i < len; i++) {
1704 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1705 asdl_seq_SET(seq, i, pair->value);
1706 }
1707 return seq;
1708}
1709
1710/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1711arguments_ty
1712_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1713 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1714 asdl_seq *names_with_default, StarEtc *star_etc)
1715{
1716 asdl_seq *posonlyargs;
1717 if (slash_without_default != NULL) {
1718 posonlyargs = slash_without_default;
1719 }
1720 else if (slash_with_default != NULL) {
1721 asdl_seq *slash_with_default_names =
1722 _get_names(p, slash_with_default->names_with_defaults);
1723 if (!slash_with_default_names) {
1724 return NULL;
1725 }
1726 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1727 if (!posonlyargs) {
1728 return NULL;
1729 }
1730 }
1731 else {
1732 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1733 if (!posonlyargs) {
1734 return NULL;
1735 }
1736 }
1737
1738 asdl_seq *posargs;
1739 if (plain_names != NULL && names_with_default != NULL) {
1740 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1741 if (!names_with_default_names) {
1742 return NULL;
1743 }
1744 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1745 if (!posargs) {
1746 return NULL;
1747 }
1748 }
1749 else if (plain_names == NULL && names_with_default != NULL) {
1750 posargs = _get_names(p, names_with_default);
1751 if (!posargs) {
1752 return NULL;
1753 }
1754 }
1755 else if (plain_names != NULL && names_with_default == NULL) {
1756 posargs = plain_names;
1757 }
1758 else {
1759 posargs = _Py_asdl_seq_new(0, p->arena);
1760 if (!posargs) {
1761 return NULL;
1762 }
1763 }
1764
1765 asdl_seq *posdefaults;
1766 if (slash_with_default != NULL && names_with_default != NULL) {
1767 asdl_seq *slash_with_default_values =
1768 _get_defaults(p, slash_with_default->names_with_defaults);
1769 if (!slash_with_default_values) {
1770 return NULL;
1771 }
1772 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1773 if (!names_with_default_values) {
1774 return NULL;
1775 }
1776 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1777 if (!posdefaults) {
1778 return NULL;
1779 }
1780 }
1781 else if (slash_with_default == NULL && names_with_default != NULL) {
1782 posdefaults = _get_defaults(p, names_with_default);
1783 if (!posdefaults) {
1784 return NULL;
1785 }
1786 }
1787 else if (slash_with_default != NULL && names_with_default == NULL) {
1788 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1789 if (!posdefaults) {
1790 return NULL;
1791 }
1792 }
1793 else {
1794 posdefaults = _Py_asdl_seq_new(0, p->arena);
1795 if (!posdefaults) {
1796 return NULL;
1797 }
1798 }
1799
1800 arg_ty vararg = NULL;
1801 if (star_etc != NULL && star_etc->vararg != NULL) {
1802 vararg = star_etc->vararg;
1803 }
1804
1805 asdl_seq *kwonlyargs;
1806 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1807 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1808 if (!kwonlyargs) {
1809 return NULL;
1810 }
1811 }
1812 else {
1813 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1814 if (!kwonlyargs) {
1815 return NULL;
1816 }
1817 }
1818
1819 asdl_seq *kwdefaults;
1820 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1821 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1822 if (!kwdefaults) {
1823 return NULL;
1824 }
1825 }
1826 else {
1827 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1828 if (!kwdefaults) {
1829 return NULL;
1830 }
1831 }
1832
1833 arg_ty kwarg = NULL;
1834 if (star_etc != NULL && star_etc->kwarg != NULL) {
1835 kwarg = star_etc->kwarg;
1836 }
1837
1838 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1839 posdefaults, p->arena);
1840}
1841
1842/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1843 * arguments. */
1844arguments_ty
1845_PyPegen_empty_arguments(Parser *p)
1846{
1847 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1848 if (!posonlyargs) {
1849 return NULL;
1850 }
1851 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1852 if (!posargs) {
1853 return NULL;
1854 }
1855 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1856 if (!posdefaults) {
1857 return NULL;
1858 }
1859 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1860 if (!kwonlyargs) {
1861 return NULL;
1862 }
1863 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1864 if (!kwdefaults) {
1865 return NULL;
1866 }
1867
1868 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1869 p->arena);
1870}
1871
1872/* Encapsulates the value of an operator_ty into an AugOperator struct */
1873AugOperator *
1874_PyPegen_augoperator(Parser *p, operator_ty kind)
1875{
1876 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1877 if (!a) {
1878 return NULL;
1879 }
1880 a->kind = kind;
1881 return a;
1882}
1883
1884/* Construct a FunctionDef equivalent to function_def, but with decorators */
1885stmt_ty
1886_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1887{
1888 assert(function_def != NULL);
1889 if (function_def->kind == AsyncFunctionDef_kind) {
1890 return _Py_AsyncFunctionDef(
1891 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1892 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1893 function_def->v.FunctionDef.type_comment, function_def->lineno,
1894 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1895 p->arena);
1896 }
1897
1898 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1899 function_def->v.FunctionDef.body, decorators,
1900 function_def->v.FunctionDef.returns,
1901 function_def->v.FunctionDef.type_comment, function_def->lineno,
1902 function_def->col_offset, function_def->end_lineno,
1903 function_def->end_col_offset, p->arena);
1904}
1905
1906/* Construct a ClassDef equivalent to class_def, but with decorators */
1907stmt_ty
1908_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1909{
1910 assert(class_def != NULL);
1911 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1912 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1913 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1914 class_def->end_col_offset, p->arena);
1915}
1916
1917/* Construct a KeywordOrStarred */
1918KeywordOrStarred *
1919_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1920{
1921 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1922 if (!a) {
1923 return NULL;
1924 }
1925 a->element = element;
1926 a->is_keyword = is_keyword;
1927 return a;
1928}
1929
1930/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1931static int
1932_seq_number_of_starred_exprs(asdl_seq *seq)
1933{
1934 int n = 0;
1935 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1936 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1937 if (!k->is_keyword) {
1938 n++;
1939 }
1940 }
1941 return n;
1942}
1943
1944/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1945asdl_seq *
1946_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1947{
1948 int new_len = _seq_number_of_starred_exprs(kwargs);
1949 if (new_len == 0) {
1950 return NULL;
1951 }
1952 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1953 if (!new_seq) {
1954 return NULL;
1955 }
1956
1957 int idx = 0;
1958 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1959 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1960 if (!k->is_keyword) {
1961 asdl_seq_SET(new_seq, idx++, k->element);
1962 }
1963 }
1964 return new_seq;
1965}
1966
1967/* Return a new asdl_seq* with only the keywords in kwargs */
1968asdl_seq *
1969_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1970{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001971 Py_ssize_t len = asdl_seq_LEN(kwargs);
1972 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001973 if (new_len == 0) {
1974 return NULL;
1975 }
1976 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1977 if (!new_seq) {
1978 return NULL;
1979 }
1980
1981 int idx = 0;
1982 for (Py_ssize_t i = 0; i < len; i++) {
1983 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1984 if (k->is_keyword) {
1985 asdl_seq_SET(new_seq, idx++, k->element);
1986 }
1987 }
1988 return new_seq;
1989}
1990
1991expr_ty
1992_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1993{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001994 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001995 assert(len > 0);
1996
1997 Token *first = asdl_seq_GET(strings, 0);
1998 Token *last = asdl_seq_GET(strings, len - 1);
1999
2000 int bytesmode = 0;
2001 PyObject *bytes_str = NULL;
2002
2003 FstringParser state;
2004 _PyPegen_FstringParser_Init(&state);
2005
2006 for (Py_ssize_t i = 0; i < len; i++) {
2007 Token *t = asdl_seq_GET(strings, i);
2008
2009 int this_bytesmode;
2010 int this_rawmode;
2011 PyObject *s;
2012 const char *fstr;
2013 Py_ssize_t fstrlen = -1;
2014
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002015 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002016 goto error;
2017 }
2018
2019 /* Check that we are not mixing bytes with unicode. */
2020 if (i != 0 && bytesmode != this_bytesmode) {
2021 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2022 Py_XDECREF(s);
2023 goto error;
2024 }
2025 bytesmode = this_bytesmode;
2026
2027 if (fstr != NULL) {
2028 assert(s == NULL && !bytesmode);
2029
2030 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2031 this_rawmode, 0, first, t, last);
2032 if (result < 0) {
2033 goto error;
2034 }
2035 }
2036 else {
2037 /* String or byte string. */
2038 assert(s != NULL && fstr == NULL);
2039 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2040
2041 if (bytesmode) {
2042 if (i == 0) {
2043 bytes_str = s;
2044 }
2045 else {
2046 PyBytes_ConcatAndDel(&bytes_str, s);
2047 if (!bytes_str) {
2048 goto error;
2049 }
2050 }
2051 }
2052 else {
2053 /* This is a regular string. Concatenate it. */
2054 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2055 goto error;
2056 }
2057 }
2058 }
2059 }
2060
2061 if (bytesmode) {
2062 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2063 goto error;
2064 }
2065 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2066 last->end_col_offset, p->arena);
2067 }
2068
2069 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2070
2071error:
2072 Py_XDECREF(bytes_str);
2073 _PyPegen_FstringParser_Dealloc(&state);
2074 if (PyErr_Occurred()) {
2075 raise_decode_error(p);
2076 }
2077 return NULL;
2078}
Guido van Rossumc001c092020-04-30 12:12:19 -07002079
2080mod_ty
2081_PyPegen_make_module(Parser *p, asdl_seq *a) {
2082 asdl_seq *type_ignores = NULL;
2083 Py_ssize_t num = p->type_ignore_comments.num_items;
2084 if (num > 0) {
2085 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2086 type_ignores = _Py_asdl_seq_new(num, p->arena);
2087 if (type_ignores == NULL) {
2088 return NULL;
2089 }
2090 for (int i = 0; i < num; i++) {
2091 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2092 if (tag == NULL) {
2093 return NULL;
2094 }
2095 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2096 if (ti == NULL) {
2097 return NULL;
2098 }
2099 asdl_seq_SET(type_ignores, i, ti);
2100 }
2101 }
2102 return Module(a, type_ignores, p->arena);
2103}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002104
2105// Error reporting helpers
2106
2107expr_ty
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002108_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002109{
2110 if (e == NULL) {
2111 return NULL;
2112 }
2113
2114#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2115 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2116 for (Py_ssize_t i = 0; i < len; i++) {\
2117 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002118 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002119 if (child != NULL) {\
2120 return child;\
2121 }\
2122 }\
2123 } while (0)
2124
2125 // We only need to visit List and Tuple nodes recursively as those
2126 // are the only ones that can contain valid names in targets when
2127 // they are parsed as expressions. Any other kind of expression
2128 // that is a container (like Sets or Dicts) is directly invalid and
2129 // we don't need to visit it recursively.
2130
2131 switch (e->kind) {
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002132 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002133 VISIT_CONTAINER(e, List);
2134 return NULL;
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002135 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002136 VISIT_CONTAINER(e, Tuple);
2137 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002138 case Starred_kind:
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002139 if (targets_type == DEL_TARGETS) {
2140 return e;
2141 }
2142 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2143 case Compare_kind:
2144 // This is needed, because the `a in b` in `for a in b` gets parsed
2145 // as a comparison, and so we need to search the left side of the comparison
2146 // for invalid targets.
2147 if (targets_type == FOR_TARGETS) {
2148 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2149 if (cmpop == In) {
2150 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2151 }
2152 return NULL;
2153 }
2154 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002155 case Name_kind:
2156 case Subscript_kind:
2157 case Attribute_kind:
2158 return NULL;
2159 default:
2160 return e;
2161 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002162}
2163
2164void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2165 int kwarg_unpacking = 0;
2166 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2167 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2168 if (!keyword->arg) {
2169 kwarg_unpacking = 1;
2170 }
2171 }
2172
2173 const char *msg = NULL;
2174 if (kwarg_unpacking) {
2175 msg = "positional argument follows keyword argument unpacking";
2176 } else {
2177 msg = "positional argument follows keyword argument";
2178 }
2179
2180 return RAISE_SYNTAX_ERROR(msg);
2181}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002182
2183void *
2184_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2185{
2186 /* The rule that calls this function is 'args for_if_clauses'.
2187 For the input f(L, x for x in y), L and x are in args and
2188 the for is parsed as a for_if_clause. We have to check if
2189 len <= 1, so that input like dict((a, b) for a, b in x)
2190 gets successfully parsed and then we pass the last
2191 argument (x in the above example) as the location of the
2192 error */
2193 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2194 if (len <= 1) {
2195 return NULL;
2196 }
2197
2198 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2199 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2200 "Generator expression must be parenthesized"
2201 );
2202}