blob: e153e924e93119e798644a00ca36ae01ad674376 [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01003#include "tokenizer.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004
5#include "pegen.h"
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01006#include "string_parser.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01007
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 Galindofb61c422020-06-15 14:23:43 +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 Galindofb61c422020-06-15 14:23:43 +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
Pablo Galindo51c58962020-06-16 16:49:43 +0100143byte_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 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100149 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{
Pablo Galindo9f495902020-06-08 02:57:00 +0100162 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 Galindofb61c422020-06-15 14:23:43 +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 Galindofb61c422020-06-15 14:23:43 +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];
Pablo Galindo51c58962020-06-16 16:49:43 +0100366 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
383
384void *
385_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100386 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300387 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100388{
389 PyObject *value = NULL;
390 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300391 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100392 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300393 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100394
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100395 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100396 if (!errstr) {
397 goto error;
398 }
399
400 if (p->start_rule == Py_file_input) {
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300401 error_line = PyErr_ProgramTextObject(p->tok->filename, lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100402 }
403
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300404 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100405 Py_ssize_t size = p->tok->inp - p->tok->buf;
Pablo Galindobcc30362020-05-14 21:11:48 +0100406 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300407 if (!error_line) {
408 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300409 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100410 }
411
Pablo Galindo51c58962020-06-16 16:49:43 +0100412 Py_ssize_t col_number = col_offset;
413
414 if (p->tok->encoding != NULL) {
415 col_number = byte_offset_to_character_offset(error_line, col_offset);
416 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300417
418 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100419 if (!tmp) {
420 goto error;
421 }
422 value = PyTuple_Pack(2, errstr, tmp);
423 Py_DECREF(tmp);
424 if (!value) {
425 goto error;
426 }
427 PyErr_SetObject(errtype, value);
428
429 Py_DECREF(errstr);
430 Py_DECREF(value);
431 return NULL;
432
433error:
434 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300435 Py_XDECREF(error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100436 return NULL;
437}
438
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100439#if 0
440static const char *
441token_name(int type)
442{
443 if (0 <= type && type <= N_TOKENS) {
444 return _PyParser_TokenNames[type];
445 }
446 return "<Huh?>";
447}
448#endif
449
450// Here, mark is the start of the node, while p->mark is the end.
451// If node==NULL, they should be the same.
452int
453_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
454{
455 // Insert in front
456 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
457 if (m == NULL) {
458 return -1;
459 }
460 m->type = type;
461 m->node = node;
462 m->mark = p->mark;
463 m->next = p->tokens[mark]->memo;
464 p->tokens[mark]->memo = m;
465 return 0;
466}
467
468// Like _PyPegen_insert_memo(), but updates an existing node if found.
469int
470_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
471{
472 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
473 if (m->type == type) {
474 // Update existing node.
475 m->node = node;
476 m->mark = p->mark;
477 return 0;
478 }
479 }
480 // Insert new node.
481 return _PyPegen_insert_memo(p, mark, type, node);
482}
483
484// Return dummy NAME.
485void *
486_PyPegen_dummy_name(Parser *p, ...)
487{
488 static void *cache = NULL;
489
490 if (cache != NULL) {
491 return cache;
492 }
493
494 PyObject *id = _create_dummy_identifier(p);
495 if (!id) {
496 return NULL;
497 }
498 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
499 return cache;
500}
501
502static int
503_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
504{
505 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
506 return NAME;
507 }
508 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
509 if (strncmp(k->str, name, name_len) == 0) {
510 return k->type;
511 }
512 }
513 return NAME;
514}
515
Guido van Rossumc001c092020-04-30 12:12:19 -0700516static int
517growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
518 assert(initial_size > 0);
519 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
520 arr->size = initial_size;
521 arr->num_items = 0;
522
523 return arr->items != NULL;
524}
525
526static int
527growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
528 if (arr->num_items >= arr->size) {
529 size_t new_size = arr->size * 2;
530 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
531 if (!new_items_array) {
532 return 0;
533 }
534 arr->items = new_items_array;
535 arr->size = new_size;
536 }
537
538 arr->items[arr->num_items].lineno = lineno;
539 arr->items[arr->num_items].comment = comment; // Take ownership
540 arr->num_items++;
541 return 1;
542}
543
544static void
545growable_comment_array_deallocate(growable_comment_array *arr) {
546 for (unsigned i = 0; i < arr->num_items; i++) {
547 PyMem_Free(arr->items[i].comment);
548 }
549 PyMem_Free(arr->items);
550}
551
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100552int
553_PyPegen_fill_token(Parser *p)
554{
Pablo Galindofb61c422020-06-15 14:23:43 +0100555 const char *start;
556 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100557 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700558
559 // Record and skip '# type: ignore' comments
560 while (type == TYPE_IGNORE) {
561 Py_ssize_t len = end - start;
562 char *tag = PyMem_Malloc(len + 1);
563 if (tag == NULL) {
564 PyErr_NoMemory();
565 return -1;
566 }
567 strncpy(tag, start, len);
568 tag[len] = '\0';
569 // Ownership of tag passes to the growable array
570 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
571 PyErr_NoMemory();
572 return -1;
573 }
574 type = PyTokenizer_Get(p->tok, &start, &end);
575 }
576
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100577 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
578 type = NEWLINE; /* Add an extra newline */
579 p->parsing_started = 0;
580
Pablo Galindob94dbd72020-04-27 18:35:58 +0100581 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100582 p->tok->pendin = -p->tok->indent;
583 p->tok->indent = 0;
584 }
585 }
586 else {
587 p->parsing_started = 1;
588 }
589
590 if (p->fill == p->size) {
591 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300592 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
593 if (new_tokens == NULL) {
594 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100595 return -1;
596 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100597 p->tokens = new_tokens;
598
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100599 for (int i = p->size; i < newsize; i++) {
600 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300601 if (p->tokens[i] == NULL) {
602 p->size = i; // Needed, in order to cleanup correctly after parser fails
603 PyErr_NoMemory();
604 return -1;
605 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100606 memset(p->tokens[i], '\0', sizeof(Token));
607 }
608 p->size = newsize;
609 }
610
611 Token *t = p->tokens[p->fill];
612 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
613 t->bytes = PyBytes_FromStringAndSize(start, end - start);
614 if (t->bytes == NULL) {
615 return -1;
616 }
617 PyArena_AddPyObject(p->arena, t->bytes);
618
619 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
620 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100621 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100622 int col_offset = -1;
623 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100624 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100625 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100626 }
627 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100628 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100629 }
630
631 t->lineno = p->starting_lineno + lineno;
632 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
633 t->end_lineno = p->starting_lineno + end_lineno;
634 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
635
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100636 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300637
638 if (type == ERRORTOKEN) {
639 if (p->tok->done == E_DECODE) {
640 return raise_decode_error(p);
641 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100642 return tokenizer_error(p);
643
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300644 }
645
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100646 return 0;
647}
648
649// Instrumentation to count the effectiveness of memoization.
650// The array counts the number of tokens skipped by memoization,
651// indexed by type.
652
653#define NSTATISTICS 2000
654static long memo_statistics[NSTATISTICS];
655
656void
657_PyPegen_clear_memo_statistics()
658{
659 for (int i = 0; i < NSTATISTICS; i++) {
660 memo_statistics[i] = 0;
661 }
662}
663
664PyObject *
665_PyPegen_get_memo_statistics()
666{
667 PyObject *ret = PyList_New(NSTATISTICS);
668 if (ret == NULL) {
669 return NULL;
670 }
671 for (int i = 0; i < NSTATISTICS; i++) {
672 PyObject *value = PyLong_FromLong(memo_statistics[i]);
673 if (value == NULL) {
674 Py_DECREF(ret);
675 return NULL;
676 }
677 // PyList_SetItem borrows a reference to value.
678 if (PyList_SetItem(ret, i, value) < 0) {
679 Py_DECREF(ret);
680 return NULL;
681 }
682 }
683 return ret;
684}
685
686int // bool
687_PyPegen_is_memoized(Parser *p, int type, void *pres)
688{
689 if (p->mark == p->fill) {
690 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300691 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100692 return -1;
693 }
694 }
695
696 Token *t = p->tokens[p->mark];
697
698 for (Memo *m = t->memo; m != NULL; m = m->next) {
699 if (m->type == type) {
700 if (0 <= type && type < NSTATISTICS) {
701 long count = m->mark - p->mark;
702 // A memoized negative result counts for one.
703 if (count <= 0) {
704 count = 1;
705 }
706 memo_statistics[type] += count;
707 }
708 p->mark = m->mark;
709 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100710 return 1;
711 }
712 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100713 return 0;
714}
715
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100716
717int
718_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
719{
720 int mark = p->mark;
721 void *res = func(p);
722 p->mark = mark;
723 return (res != NULL) == positive;
724}
725
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100726int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100727_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
728{
729 int mark = p->mark;
730 void *res = func(p, arg);
731 p->mark = mark;
732 return (res != NULL) == positive;
733}
734
735int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100736_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
737{
738 int mark = p->mark;
739 void *res = func(p, arg);
740 p->mark = mark;
741 return (res != NULL) == positive;
742}
743
744int
745_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
746{
747 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100748 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100749 p->mark = mark;
750 return (res != NULL) == positive;
751}
752
753Token *
754_PyPegen_expect_token(Parser *p, int type)
755{
756 if (p->mark == p->fill) {
757 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300758 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100759 return NULL;
760 }
761 }
762 Token *t = p->tokens[p->mark];
763 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100764 return NULL;
765 }
766 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100767 return t;
768}
769
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700770expr_ty
771_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
772{
773 if (p->mark == p->fill) {
774 if (_PyPegen_fill_token(p) < 0) {
775 p->error_indicator = 1;
776 return NULL;
777 }
778 }
779 Token *t = p->tokens[p->mark];
780 if (t->type != NAME) {
781 return NULL;
782 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300783 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700784 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300785 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700786 return NULL;
787 }
788 if (strcmp(s, keyword) != 0) {
789 return NULL;
790 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300791 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700792}
793
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100794Token *
795_PyPegen_get_last_nonnwhitespace_token(Parser *p)
796{
797 assert(p->mark >= 0);
798 Token *token = NULL;
799 for (int m = p->mark - 1; m >= 0; m--) {
800 token = p->tokens[m];
801 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
802 break;
803 }
804 }
805 return token;
806}
807
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100808expr_ty
809_PyPegen_name_token(Parser *p)
810{
811 Token *t = _PyPegen_expect_token(p, NAME);
812 if (t == NULL) {
813 return NULL;
814 }
815 char* s = PyBytes_AsString(t->bytes);
816 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300817 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100818 return NULL;
819 }
820 PyObject *id = _PyPegen_new_identifier(p, s);
821 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300822 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100823 return NULL;
824 }
825 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
826 p->arena);
827}
828
829void *
830_PyPegen_string_token(Parser *p)
831{
832 return _PyPegen_expect_token(p, STRING);
833}
834
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100835static PyObject *
836parsenumber_raw(const char *s)
837{
838 const char *end;
839 long x;
840 double dx;
841 Py_complex compl;
842 int imflag;
843
844 assert(s != NULL);
845 errno = 0;
846 end = s + strlen(s) - 1;
847 imflag = *end == 'j' || *end == 'J';
848 if (s[0] == '0') {
849 x = (long)PyOS_strtoul(s, (char **)&end, 0);
850 if (x < 0 && errno == 0) {
851 return PyLong_FromString(s, (char **)0, 0);
852 }
853 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100854 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100855 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100856 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100857 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100858 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100859 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100860 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100861 return PyLong_FromLong(x);
862 }
863 /* XXX Huge floats may silently fail */
864 if (imflag) {
865 compl.real = 0.;
866 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100867 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100868 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100869 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100870 return PyComplex_FromCComplex(compl);
871 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100872 dx = PyOS_string_to_double(s, NULL, NULL);
873 if (dx == -1.0 && PyErr_Occurred()) {
874 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100875 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100876 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100877}
878
879static PyObject *
880parsenumber(const char *s)
881{
Pablo Galindofb61c422020-06-15 14:23:43 +0100882 char *dup;
883 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100884 PyObject *res = NULL;
885
886 assert(s != NULL);
887
888 if (strchr(s, '_') == NULL) {
889 return parsenumber_raw(s);
890 }
891 /* Create a duplicate without underscores. */
892 dup = PyMem_Malloc(strlen(s) + 1);
893 if (dup == NULL) {
894 return PyErr_NoMemory();
895 }
896 end = dup;
897 for (; *s; s++) {
898 if (*s != '_') {
899 *end++ = *s;
900 }
901 }
902 *end = '\0';
903 res = parsenumber_raw(dup);
904 PyMem_Free(dup);
905 return res;
906}
907
908expr_ty
909_PyPegen_number_token(Parser *p)
910{
911 Token *t = _PyPegen_expect_token(p, NUMBER);
912 if (t == NULL) {
913 return NULL;
914 }
915
916 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100917 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300918 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100919 return NULL;
920 }
921
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300922 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
923 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700924 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300925 "in Python 3.6 and greater");
926 }
927
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100928 PyObject *c = parsenumber(num_raw);
929
930 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300931 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100932 return NULL;
933 }
934
935 if (PyArena_AddPyObject(p->arena, c) < 0) {
936 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300937 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100938 return NULL;
939 }
940
941 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
942 p->arena);
943}
944
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300945static int // bool
946newline_in_string(Parser *p, const char *cur)
947{
Pablo Galindo2e6593d2020-06-06 00:52:27 +0100948 for (const char *c = cur; c >= p->tok->buf; c--) {
949 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300950 return 1;
951 }
952 }
953 return 0;
954}
955
956/* Check that the source for a single input statement really is a single
957 statement by looking at what is left in the buffer after parsing.
958 Trailing whitespace and comments are OK. */
959static int // bool
960bad_single_statement(Parser *p)
961{
962 const char *cur = strchr(p->tok->buf, '\n');
963
964 /* Newlines are allowed if preceded by a line continuation character
965 or if they appear inside a string. */
966 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
967 return 0;
968 }
969 char c = *cur;
970
971 for (;;) {
972 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
973 c = *++cur;
974 }
975
976 if (!c) {
977 return 0;
978 }
979
980 if (c != '#') {
981 return 1;
982 }
983
984 /* Suck up comment. */
985 while (c && c != '\n') {
986 c = *++cur;
987 }
988 }
989}
990
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100991void
992_PyPegen_Parser_Free(Parser *p)
993{
994 Py_XDECREF(p->normalize);
995 for (int i = 0; i < p->size; i++) {
996 PyMem_Free(p->tokens[i]);
997 }
998 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700999 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001000 PyMem_Free(p);
1001}
1002
Pablo Galindo2b74c832020-04-27 18:02:07 +01001003static int
1004compute_parser_flags(PyCompilerFlags *flags)
1005{
1006 int parser_flags = 0;
1007 if (!flags) {
1008 return 0;
1009 }
1010 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1011 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1012 }
1013 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1014 parser_flags |= PyPARSE_IGNORE_COOKIE;
1015 }
1016 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1017 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1018 }
1019 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1020 parser_flags |= PyPARSE_TYPE_COMMENTS;
1021 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001022 if (flags->cf_feature_version < 7) {
1023 parser_flags |= PyPARSE_ASYNC_HACKS;
1024 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001025 return parser_flags;
1026}
1027
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001028Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001029_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001030 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001031{
1032 Parser *p = PyMem_Malloc(sizeof(Parser));
1033 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001034 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001035 }
1036 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001037 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1038 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001039 p->tok = tok;
1040 p->keywords = NULL;
1041 p->n_keyword_lists = -1;
1042 p->tokens = PyMem_Malloc(sizeof(Token *));
1043 if (!p->tokens) {
1044 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001045 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001046 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001047 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001048 if (!p->tokens) {
1049 PyMem_Free(p->tokens);
1050 PyMem_Free(p);
1051 return (Parser *) PyErr_NoMemory();
1052 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001053 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1054 PyMem_Free(p->tokens[0]);
1055 PyMem_Free(p->tokens);
1056 PyMem_Free(p);
1057 return (Parser *) PyErr_NoMemory();
1058 }
1059
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001060 p->mark = 0;
1061 p->fill = 0;
1062 p->size = 1;
1063
1064 p->errcode = errcode;
1065 p->arena = arena;
1066 p->start_rule = start_rule;
1067 p->parsing_started = 0;
1068 p->normalize = NULL;
1069 p->error_indicator = 0;
1070
1071 p->starting_lineno = 0;
1072 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001073 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001074 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001075 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001076 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001077
1078 return p;
1079}
1080
1081void *
1082_PyPegen_run_parser(Parser *p)
1083{
1084 void *res = _PyPegen_parse(p);
1085 if (res == NULL) {
1086 if (PyErr_Occurred()) {
1087 return NULL;
1088 }
1089 if (p->fill == 0) {
1090 RAISE_SYNTAX_ERROR("error at start before reading any input");
1091 }
1092 else if (p->tok->done == E_EOF) {
1093 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1094 }
1095 else {
1096 if (p->tokens[p->fill-1]->type == INDENT) {
1097 RAISE_INDENTATION_ERROR("unexpected indent");
1098 }
1099 else if (p->tokens[p->fill-1]->type == DEDENT) {
1100 RAISE_INDENTATION_ERROR("unexpected unindent");
1101 }
1102 else {
1103 RAISE_SYNTAX_ERROR("invalid syntax");
1104 }
1105 }
1106 return NULL;
1107 }
1108
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001109 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1110 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1111 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1112 }
1113
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001114 return res;
1115}
1116
1117mod_ty
1118_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1119 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001120 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001121{
1122 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1123 if (tok == NULL) {
1124 if (PyErr_Occurred()) {
1125 raise_tokenizer_init_error(filename_ob);
1126 return NULL;
1127 }
1128 return NULL;
1129 }
1130 // This transfers the ownership to the tokenizer
1131 tok->filename = filename_ob;
1132 Py_INCREF(filename_ob);
1133
1134 // From here on we need to clean up even if there's an error
1135 mod_ty result = NULL;
1136
Pablo Galindo2b74c832020-04-27 18:02:07 +01001137 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001138 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1139 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001140 if (p == NULL) {
1141 goto error;
1142 }
1143
1144 result = _PyPegen_run_parser(p);
1145 _PyPegen_Parser_Free(p);
1146
1147error:
1148 PyTokenizer_Free(tok);
1149 return result;
1150}
1151
1152mod_ty
1153_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001154 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001155{
1156 FILE *fp = fopen(filename, "rb");
1157 if (fp == NULL) {
1158 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1159 return NULL;
1160 }
1161
1162 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001163 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001164
1165 fclose(fp);
1166 return result;
1167}
1168
1169mod_ty
1170_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001171 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001172{
1173 int exec_input = start_rule == Py_file_input;
1174
1175 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001176 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001177 tok = PyTokenizer_FromUTF8(str, exec_input);
1178 } else {
1179 tok = PyTokenizer_FromString(str, exec_input);
1180 }
1181 if (tok == NULL) {
1182 if (PyErr_Occurred()) {
1183 raise_tokenizer_init_error(filename_ob);
1184 }
1185 return NULL;
1186 }
1187 // This transfers the ownership to the tokenizer
1188 tok->filename = filename_ob;
1189 Py_INCREF(filename_ob);
1190
1191 // We need to clear up from here on
1192 mod_ty result = NULL;
1193
Pablo Galindo2b74c832020-04-27 18:02:07 +01001194 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001195 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001196 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1197 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001198 if (p == NULL) {
1199 goto error;
1200 }
1201
1202 result = _PyPegen_run_parser(p);
1203 _PyPegen_Parser_Free(p);
1204
1205error:
1206 PyTokenizer_Free(tok);
1207 return result;
1208}
1209
1210void *
1211_PyPegen_interactive_exit(Parser *p)
1212{
1213 if (p->errcode) {
1214 *(p->errcode) = E_EOF;
1215 }
1216 return NULL;
1217}
1218
1219/* Creates a single-element asdl_seq* that contains a */
1220asdl_seq *
1221_PyPegen_singleton_seq(Parser *p, void *a)
1222{
1223 assert(a != NULL);
1224 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1225 if (!seq) {
1226 return NULL;
1227 }
1228 asdl_seq_SET(seq, 0, a);
1229 return seq;
1230}
1231
1232/* Creates a copy of seq and prepends a to it */
1233asdl_seq *
1234_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1235{
1236 assert(a != NULL);
1237 if (!seq) {
1238 return _PyPegen_singleton_seq(p, a);
1239 }
1240
1241 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1242 if (!new_seq) {
1243 return NULL;
1244 }
1245
1246 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001247 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001248 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1249 }
1250 return new_seq;
1251}
1252
Guido van Rossumc001c092020-04-30 12:12:19 -07001253/* Creates a copy of seq and appends a to it */
1254asdl_seq *
1255_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1256{
1257 assert(a != NULL);
1258 if (!seq) {
1259 return _PyPegen_singleton_seq(p, a);
1260 }
1261
1262 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1263 if (!new_seq) {
1264 return NULL;
1265 }
1266
1267 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1268 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1269 }
1270 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1271 return new_seq;
1272}
1273
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001274static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001275_get_flattened_seq_size(asdl_seq *seqs)
1276{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001277 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001278 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1279 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1280 size += asdl_seq_LEN(inner_seq);
1281 }
1282 return size;
1283}
1284
1285/* Flattens an asdl_seq* of asdl_seq*s */
1286asdl_seq *
1287_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1288{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001289 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001290 assert(flattened_seq_size > 0);
1291
1292 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1293 if (!flattened_seq) {
1294 return NULL;
1295 }
1296
1297 int flattened_seq_idx = 0;
1298 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1299 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001300 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001301 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1302 }
1303 }
1304 assert(flattened_seq_idx == flattened_seq_size);
1305
1306 return flattened_seq;
1307}
1308
1309/* Creates a new name of the form <first_name>.<second_name> */
1310expr_ty
1311_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1312{
1313 assert(first_name != NULL && second_name != NULL);
1314 PyObject *first_identifier = first_name->v.Name.id;
1315 PyObject *second_identifier = second_name->v.Name.id;
1316
1317 if (PyUnicode_READY(first_identifier) == -1) {
1318 return NULL;
1319 }
1320 if (PyUnicode_READY(second_identifier) == -1) {
1321 return NULL;
1322 }
1323 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1324 if (!first_str) {
1325 return NULL;
1326 }
1327 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1328 if (!second_str) {
1329 return NULL;
1330 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001331 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001332
1333 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1334 if (!str) {
1335 return NULL;
1336 }
1337
1338 char *s = PyBytes_AS_STRING(str);
1339 if (!s) {
1340 return NULL;
1341 }
1342
1343 strcpy(s, first_str);
1344 s += strlen(first_str);
1345 *s++ = '.';
1346 strcpy(s, second_str);
1347 s += strlen(second_str);
1348 *s = '\0';
1349
1350 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1351 Py_DECREF(str);
1352 if (!uni) {
1353 return NULL;
1354 }
1355 PyUnicode_InternInPlace(&uni);
1356 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1357 Py_DECREF(uni);
1358 return NULL;
1359 }
1360
1361 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1362}
1363
1364/* Counts the total number of dots in seq's tokens */
1365int
1366_PyPegen_seq_count_dots(asdl_seq *seq)
1367{
1368 int number_of_dots = 0;
1369 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1370 Token *current_expr = asdl_seq_GET(seq, i);
1371 switch (current_expr->type) {
1372 case ELLIPSIS:
1373 number_of_dots += 3;
1374 break;
1375 case DOT:
1376 number_of_dots += 1;
1377 break;
1378 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001379 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001380 }
1381 }
1382
1383 return number_of_dots;
1384}
1385
1386/* Creates an alias with '*' as the identifier name */
1387alias_ty
1388_PyPegen_alias_for_star(Parser *p)
1389{
1390 PyObject *str = PyUnicode_InternFromString("*");
1391 if (!str) {
1392 return NULL;
1393 }
1394 if (PyArena_AddPyObject(p->arena, str) < 0) {
1395 Py_DECREF(str);
1396 return NULL;
1397 }
1398 return alias(str, NULL, p->arena);
1399}
1400
1401/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1402asdl_seq *
1403_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1404{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001405 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001406 assert(len > 0);
1407
1408 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1409 if (!new_seq) {
1410 return NULL;
1411 }
1412 for (Py_ssize_t i = 0; i < len; i++) {
1413 expr_ty e = asdl_seq_GET(seq, i);
1414 asdl_seq_SET(new_seq, i, e->v.Name.id);
1415 }
1416 return new_seq;
1417}
1418
1419/* Constructs a CmpopExprPair */
1420CmpopExprPair *
1421_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1422{
1423 assert(expr != NULL);
1424 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1425 if (!a) {
1426 return NULL;
1427 }
1428 a->cmpop = cmpop;
1429 a->expr = expr;
1430 return a;
1431}
1432
1433asdl_int_seq *
1434_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1435{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001436 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001437 assert(len > 0);
1438
1439 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1440 if (!new_seq) {
1441 return NULL;
1442 }
1443 for (Py_ssize_t i = 0; i < len; i++) {
1444 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1445 asdl_seq_SET(new_seq, i, pair->cmpop);
1446 }
1447 return new_seq;
1448}
1449
1450asdl_seq *
1451_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1452{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001453 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001454 assert(len > 0);
1455
1456 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1457 if (!new_seq) {
1458 return NULL;
1459 }
1460 for (Py_ssize_t i = 0; i < len; i++) {
1461 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1462 asdl_seq_SET(new_seq, i, pair->expr);
1463 }
1464 return new_seq;
1465}
1466
1467/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1468static asdl_seq *
1469_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1470{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001471 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001472 if (len == 0) {
1473 return NULL;
1474 }
1475
1476 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1477 if (!new_seq) {
1478 return NULL;
1479 }
1480 for (Py_ssize_t i = 0; i < len; i++) {
1481 expr_ty e = asdl_seq_GET(seq, i);
1482 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1483 }
1484 return new_seq;
1485}
1486
1487static expr_ty
1488_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1489{
1490 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1491}
1492
1493static expr_ty
1494_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1495{
1496 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1497}
1498
1499static expr_ty
1500_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1501{
1502 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1503}
1504
1505static expr_ty
1506_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1507{
1508 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1509}
1510
1511static expr_ty
1512_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1513{
1514 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1515}
1516
1517static expr_ty
1518_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1519{
1520 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1521}
1522
1523/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1524expr_ty
1525_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1526{
1527 assert(expr != NULL);
1528
1529 expr_ty new = NULL;
1530 switch (expr->kind) {
1531 case Name_kind:
1532 new = _set_name_context(p, expr, ctx);
1533 break;
1534 case Tuple_kind:
1535 new = _set_tuple_context(p, expr, ctx);
1536 break;
1537 case List_kind:
1538 new = _set_list_context(p, expr, ctx);
1539 break;
1540 case Subscript_kind:
1541 new = _set_subscript_context(p, expr, ctx);
1542 break;
1543 case Attribute_kind:
1544 new = _set_attribute_context(p, expr, ctx);
1545 break;
1546 case Starred_kind:
1547 new = _set_starred_context(p, expr, ctx);
1548 break;
1549 default:
1550 new = expr;
1551 }
1552 return new;
1553}
1554
1555/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1556KeyValuePair *
1557_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1558{
1559 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1560 if (!a) {
1561 return NULL;
1562 }
1563 a->key = key;
1564 a->value = value;
1565 return a;
1566}
1567
1568/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1569asdl_seq *
1570_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1571{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001572 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001573 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1574 if (!new_seq) {
1575 return NULL;
1576 }
1577 for (Py_ssize_t i = 0; i < len; i++) {
1578 KeyValuePair *pair = asdl_seq_GET(seq, i);
1579 asdl_seq_SET(new_seq, i, pair->key);
1580 }
1581 return new_seq;
1582}
1583
1584/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1585asdl_seq *
1586_PyPegen_get_values(Parser *p, asdl_seq *seq)
1587{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001588 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001589 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1590 if (!new_seq) {
1591 return NULL;
1592 }
1593 for (Py_ssize_t i = 0; i < len; i++) {
1594 KeyValuePair *pair = asdl_seq_GET(seq, i);
1595 asdl_seq_SET(new_seq, i, pair->value);
1596 }
1597 return new_seq;
1598}
1599
1600/* Constructs a NameDefaultPair */
1601NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001602_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001603{
1604 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1605 if (!a) {
1606 return NULL;
1607 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001608 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001609 a->value = value;
1610 return a;
1611}
1612
1613/* Constructs a SlashWithDefault */
1614SlashWithDefault *
1615_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1616{
1617 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1618 if (!a) {
1619 return NULL;
1620 }
1621 a->plain_names = plain_names;
1622 a->names_with_defaults = names_with_defaults;
1623 return a;
1624}
1625
1626/* Constructs a StarEtc */
1627StarEtc *
1628_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1629{
1630 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1631 if (!a) {
1632 return NULL;
1633 }
1634 a->vararg = vararg;
1635 a->kwonlyargs = kwonlyargs;
1636 a->kwarg = kwarg;
1637 return a;
1638}
1639
1640asdl_seq *
1641_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1642{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001643 Py_ssize_t first_len = asdl_seq_LEN(a);
1644 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001645 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1646 if (!new_seq) {
1647 return NULL;
1648 }
1649
1650 int k = 0;
1651 for (Py_ssize_t i = 0; i < first_len; i++) {
1652 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1653 }
1654 for (Py_ssize_t i = 0; i < second_len; i++) {
1655 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1656 }
1657
1658 return new_seq;
1659}
1660
1661static asdl_seq *
1662_get_names(Parser *p, asdl_seq *names_with_defaults)
1663{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001664 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001665 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1666 if (!seq) {
1667 return NULL;
1668 }
1669 for (Py_ssize_t i = 0; i < len; i++) {
1670 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1671 asdl_seq_SET(seq, i, pair->arg);
1672 }
1673 return seq;
1674}
1675
1676static asdl_seq *
1677_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1678{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001679 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001680 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1681 if (!seq) {
1682 return NULL;
1683 }
1684 for (Py_ssize_t i = 0; i < len; i++) {
1685 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1686 asdl_seq_SET(seq, i, pair->value);
1687 }
1688 return seq;
1689}
1690
1691/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1692arguments_ty
1693_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1694 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1695 asdl_seq *names_with_default, StarEtc *star_etc)
1696{
1697 asdl_seq *posonlyargs;
1698 if (slash_without_default != NULL) {
1699 posonlyargs = slash_without_default;
1700 }
1701 else if (slash_with_default != NULL) {
1702 asdl_seq *slash_with_default_names =
1703 _get_names(p, slash_with_default->names_with_defaults);
1704 if (!slash_with_default_names) {
1705 return NULL;
1706 }
1707 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1708 if (!posonlyargs) {
1709 return NULL;
1710 }
1711 }
1712 else {
1713 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1714 if (!posonlyargs) {
1715 return NULL;
1716 }
1717 }
1718
1719 asdl_seq *posargs;
1720 if (plain_names != NULL && names_with_default != NULL) {
1721 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1722 if (!names_with_default_names) {
1723 return NULL;
1724 }
1725 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1726 if (!posargs) {
1727 return NULL;
1728 }
1729 }
1730 else if (plain_names == NULL && names_with_default != NULL) {
1731 posargs = _get_names(p, names_with_default);
1732 if (!posargs) {
1733 return NULL;
1734 }
1735 }
1736 else if (plain_names != NULL && names_with_default == NULL) {
1737 posargs = plain_names;
1738 }
1739 else {
1740 posargs = _Py_asdl_seq_new(0, p->arena);
1741 if (!posargs) {
1742 return NULL;
1743 }
1744 }
1745
1746 asdl_seq *posdefaults;
1747 if (slash_with_default != NULL && names_with_default != NULL) {
1748 asdl_seq *slash_with_default_values =
1749 _get_defaults(p, slash_with_default->names_with_defaults);
1750 if (!slash_with_default_values) {
1751 return NULL;
1752 }
1753 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1754 if (!names_with_default_values) {
1755 return NULL;
1756 }
1757 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1758 if (!posdefaults) {
1759 return NULL;
1760 }
1761 }
1762 else if (slash_with_default == NULL && names_with_default != NULL) {
1763 posdefaults = _get_defaults(p, names_with_default);
1764 if (!posdefaults) {
1765 return NULL;
1766 }
1767 }
1768 else if (slash_with_default != NULL && names_with_default == NULL) {
1769 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1770 if (!posdefaults) {
1771 return NULL;
1772 }
1773 }
1774 else {
1775 posdefaults = _Py_asdl_seq_new(0, p->arena);
1776 if (!posdefaults) {
1777 return NULL;
1778 }
1779 }
1780
1781 arg_ty vararg = NULL;
1782 if (star_etc != NULL && star_etc->vararg != NULL) {
1783 vararg = star_etc->vararg;
1784 }
1785
1786 asdl_seq *kwonlyargs;
1787 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1788 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1789 if (!kwonlyargs) {
1790 return NULL;
1791 }
1792 }
1793 else {
1794 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1795 if (!kwonlyargs) {
1796 return NULL;
1797 }
1798 }
1799
1800 asdl_seq *kwdefaults;
1801 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1802 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1803 if (!kwdefaults) {
1804 return NULL;
1805 }
1806 }
1807 else {
1808 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1809 if (!kwdefaults) {
1810 return NULL;
1811 }
1812 }
1813
1814 arg_ty kwarg = NULL;
1815 if (star_etc != NULL && star_etc->kwarg != NULL) {
1816 kwarg = star_etc->kwarg;
1817 }
1818
1819 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1820 posdefaults, p->arena);
1821}
1822
1823/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1824 * arguments. */
1825arguments_ty
1826_PyPegen_empty_arguments(Parser *p)
1827{
1828 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1829 if (!posonlyargs) {
1830 return NULL;
1831 }
1832 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1833 if (!posargs) {
1834 return NULL;
1835 }
1836 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1837 if (!posdefaults) {
1838 return NULL;
1839 }
1840 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1841 if (!kwonlyargs) {
1842 return NULL;
1843 }
1844 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1845 if (!kwdefaults) {
1846 return NULL;
1847 }
1848
1849 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1850 p->arena);
1851}
1852
1853/* Encapsulates the value of an operator_ty into an AugOperator struct */
1854AugOperator *
1855_PyPegen_augoperator(Parser *p, operator_ty kind)
1856{
1857 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1858 if (!a) {
1859 return NULL;
1860 }
1861 a->kind = kind;
1862 return a;
1863}
1864
1865/* Construct a FunctionDef equivalent to function_def, but with decorators */
1866stmt_ty
1867_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1868{
1869 assert(function_def != NULL);
1870 if (function_def->kind == AsyncFunctionDef_kind) {
1871 return _Py_AsyncFunctionDef(
1872 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1873 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1874 function_def->v.FunctionDef.type_comment, function_def->lineno,
1875 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1876 p->arena);
1877 }
1878
1879 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1880 function_def->v.FunctionDef.body, decorators,
1881 function_def->v.FunctionDef.returns,
1882 function_def->v.FunctionDef.type_comment, function_def->lineno,
1883 function_def->col_offset, function_def->end_lineno,
1884 function_def->end_col_offset, p->arena);
1885}
1886
1887/* Construct a ClassDef equivalent to class_def, but with decorators */
1888stmt_ty
1889_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1890{
1891 assert(class_def != NULL);
1892 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1893 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1894 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1895 class_def->end_col_offset, p->arena);
1896}
1897
1898/* Construct a KeywordOrStarred */
1899KeywordOrStarred *
1900_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1901{
1902 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1903 if (!a) {
1904 return NULL;
1905 }
1906 a->element = element;
1907 a->is_keyword = is_keyword;
1908 return a;
1909}
1910
1911/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1912static int
1913_seq_number_of_starred_exprs(asdl_seq *seq)
1914{
1915 int n = 0;
1916 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1917 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1918 if (!k->is_keyword) {
1919 n++;
1920 }
1921 }
1922 return n;
1923}
1924
1925/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1926asdl_seq *
1927_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1928{
1929 int new_len = _seq_number_of_starred_exprs(kwargs);
1930 if (new_len == 0) {
1931 return NULL;
1932 }
1933 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1934 if (!new_seq) {
1935 return NULL;
1936 }
1937
1938 int idx = 0;
1939 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1940 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1941 if (!k->is_keyword) {
1942 asdl_seq_SET(new_seq, idx++, k->element);
1943 }
1944 }
1945 return new_seq;
1946}
1947
1948/* Return a new asdl_seq* with only the keywords in kwargs */
1949asdl_seq *
1950_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1951{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001952 Py_ssize_t len = asdl_seq_LEN(kwargs);
1953 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001954 if (new_len == 0) {
1955 return NULL;
1956 }
1957 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1958 if (!new_seq) {
1959 return NULL;
1960 }
1961
1962 int idx = 0;
1963 for (Py_ssize_t i = 0; i < len; i++) {
1964 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1965 if (k->is_keyword) {
1966 asdl_seq_SET(new_seq, idx++, k->element);
1967 }
1968 }
1969 return new_seq;
1970}
1971
1972expr_ty
1973_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1974{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001975 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001976 assert(len > 0);
1977
1978 Token *first = asdl_seq_GET(strings, 0);
1979 Token *last = asdl_seq_GET(strings, len - 1);
1980
1981 int bytesmode = 0;
1982 PyObject *bytes_str = NULL;
1983
1984 FstringParser state;
1985 _PyPegen_FstringParser_Init(&state);
1986
1987 for (Py_ssize_t i = 0; i < len; i++) {
1988 Token *t = asdl_seq_GET(strings, i);
1989
1990 int this_bytesmode;
1991 int this_rawmode;
1992 PyObject *s;
1993 const char *fstr;
1994 Py_ssize_t fstrlen = -1;
1995
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001996 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001997 goto error;
1998 }
1999
2000 /* Check that we are not mixing bytes with unicode. */
2001 if (i != 0 && bytesmode != this_bytesmode) {
2002 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2003 Py_XDECREF(s);
2004 goto error;
2005 }
2006 bytesmode = this_bytesmode;
2007
2008 if (fstr != NULL) {
2009 assert(s == NULL && !bytesmode);
2010
2011 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2012 this_rawmode, 0, first, t, last);
2013 if (result < 0) {
2014 goto error;
2015 }
2016 }
2017 else {
2018 /* String or byte string. */
2019 assert(s != NULL && fstr == NULL);
2020 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2021
2022 if (bytesmode) {
2023 if (i == 0) {
2024 bytes_str = s;
2025 }
2026 else {
2027 PyBytes_ConcatAndDel(&bytes_str, s);
2028 if (!bytes_str) {
2029 goto error;
2030 }
2031 }
2032 }
2033 else {
2034 /* This is a regular string. Concatenate it. */
2035 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2036 goto error;
2037 }
2038 }
2039 }
2040 }
2041
2042 if (bytesmode) {
2043 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2044 goto error;
2045 }
2046 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2047 last->end_col_offset, p->arena);
2048 }
2049
2050 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2051
2052error:
2053 Py_XDECREF(bytes_str);
2054 _PyPegen_FstringParser_Dealloc(&state);
2055 if (PyErr_Occurred()) {
2056 raise_decode_error(p);
2057 }
2058 return NULL;
2059}
Guido van Rossumc001c092020-04-30 12:12:19 -07002060
2061mod_ty
2062_PyPegen_make_module(Parser *p, asdl_seq *a) {
2063 asdl_seq *type_ignores = NULL;
2064 Py_ssize_t num = p->type_ignore_comments.num_items;
2065 if (num > 0) {
2066 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2067 type_ignores = _Py_asdl_seq_new(num, p->arena);
2068 if (type_ignores == NULL) {
2069 return NULL;
2070 }
2071 for (int i = 0; i < num; i++) {
2072 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2073 if (tag == NULL) {
2074 return NULL;
2075 }
2076 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2077 if (ti == NULL) {
2078 return NULL;
2079 }
2080 asdl_seq_SET(type_ignores, i, ti);
2081 }
2082 }
2083 return Module(a, type_ignores, p->arena);
2084}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002085
2086// Error reporting helpers
2087
2088expr_ty
2089_PyPegen_get_invalid_target(expr_ty e)
2090{
2091 if (e == NULL) {
2092 return NULL;
2093 }
2094
2095#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2096 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2097 for (Py_ssize_t i = 0; i < len; i++) {\
2098 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2099 expr_ty child = _PyPegen_get_invalid_target(other);\
2100 if (child != NULL) {\
2101 return child;\
2102 }\
2103 }\
2104 } while (0)
2105
2106 // We only need to visit List and Tuple nodes recursively as those
2107 // are the only ones that can contain valid names in targets when
2108 // they are parsed as expressions. Any other kind of expression
2109 // that is a container (like Sets or Dicts) is directly invalid and
2110 // we don't need to visit it recursively.
2111
2112 switch (e->kind) {
2113 case List_kind: {
2114 VISIT_CONTAINER(e, List);
2115 return NULL;
2116 }
2117 case Tuple_kind: {
2118 VISIT_CONTAINER(e, Tuple);
2119 return NULL;
2120 }
2121 case Starred_kind:
2122 return _PyPegen_get_invalid_target(e->v.Starred.value);
2123 case Name_kind:
2124 case Subscript_kind:
2125 case Attribute_kind:
2126 return NULL;
2127 default:
2128 return e;
2129 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002130}
2131
2132void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2133 int kwarg_unpacking = 0;
2134 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2135 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2136 if (!keyword->arg) {
2137 kwarg_unpacking = 1;
2138 }
2139 }
2140
2141 const char *msg = NULL;
2142 if (kwarg_unpacking) {
2143 msg = "positional argument follows keyword argument unpacking";
2144 } else {
2145 msg = "positional argument follows keyword argument";
2146 }
2147
2148 return RAISE_SYNTAX_ERROR(msg);
2149}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002150
2151void *
2152_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2153{
2154 /* The rule that calls this function is 'args for_if_clauses'.
2155 For the input f(L, x for x in y), L and x are in args and
2156 the for is parsed as a for_if_clause. We have to check if
2157 len <= 1, so that input like dict((a, b) for a, b in x)
2158 gets successfully parsed and then we pass the last
2159 argument (x in the above example) as the location of the
2160 error */
2161 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2162 if (len <= 1) {
2163 return NULL;
2164 }
2165
2166 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2167 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2168 "Generator expression must be parenthesized"
2169 );
2170}