blob: 53e3d4913830689099af2153466e884f328dc9c7 [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
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300383void *
384_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100385 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
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300394 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
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300398 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300399 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) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300415 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
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300426 if (p->start_rule == Py_fstring_input) {
427 col_offset -= p->starting_col_offset;
428 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100429 Py_ssize_t col_number = col_offset;
430
431 if (p->tok->encoding != NULL) {
432 col_number = byte_offset_to_character_offset(error_line, col_offset);
433 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300434
435 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100436 if (!tmp) {
437 goto error;
438 }
439 value = PyTuple_Pack(2, errstr, tmp);
440 Py_DECREF(tmp);
441 if (!value) {
442 goto error;
443 }
444 PyErr_SetObject(errtype, value);
445
446 Py_DECREF(errstr);
447 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300448 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300449 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300450 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100451 return NULL;
452
453error:
454 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300455 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300456 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300457 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300458 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100459 return NULL;
460}
461
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100462#if 0
463static const char *
464token_name(int type)
465{
466 if (0 <= type && type <= N_TOKENS) {
467 return _PyParser_TokenNames[type];
468 }
469 return "<Huh?>";
470}
471#endif
472
473// Here, mark is the start of the node, while p->mark is the end.
474// If node==NULL, they should be the same.
475int
476_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
477{
478 // Insert in front
479 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
480 if (m == NULL) {
481 return -1;
482 }
483 m->type = type;
484 m->node = node;
485 m->mark = p->mark;
486 m->next = p->tokens[mark]->memo;
487 p->tokens[mark]->memo = m;
488 return 0;
489}
490
491// Like _PyPegen_insert_memo(), but updates an existing node if found.
492int
493_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
494{
495 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
496 if (m->type == type) {
497 // Update existing node.
498 m->node = node;
499 m->mark = p->mark;
500 return 0;
501 }
502 }
503 // Insert new node.
504 return _PyPegen_insert_memo(p, mark, type, node);
505}
506
507// Return dummy NAME.
508void *
509_PyPegen_dummy_name(Parser *p, ...)
510{
511 static void *cache = NULL;
512
513 if (cache != NULL) {
514 return cache;
515 }
516
517 PyObject *id = _create_dummy_identifier(p);
518 if (!id) {
519 return NULL;
520 }
521 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
522 return cache;
523}
524
525static int
526_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
527{
528 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
529 return NAME;
530 }
531 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
532 if (strncmp(k->str, name, name_len) == 0) {
533 return k->type;
534 }
535 }
536 return NAME;
537}
538
Guido van Rossumc001c092020-04-30 12:12:19 -0700539static int
540growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
541 assert(initial_size > 0);
542 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
543 arr->size = initial_size;
544 arr->num_items = 0;
545
546 return arr->items != NULL;
547}
548
549static int
550growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
551 if (arr->num_items >= arr->size) {
552 size_t new_size = arr->size * 2;
553 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
554 if (!new_items_array) {
555 return 0;
556 }
557 arr->items = new_items_array;
558 arr->size = new_size;
559 }
560
561 arr->items[arr->num_items].lineno = lineno;
562 arr->items[arr->num_items].comment = comment; // Take ownership
563 arr->num_items++;
564 return 1;
565}
566
567static void
568growable_comment_array_deallocate(growable_comment_array *arr) {
569 for (unsigned i = 0; i < arr->num_items; i++) {
570 PyMem_Free(arr->items[i].comment);
571 }
572 PyMem_Free(arr->items);
573}
574
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100575int
576_PyPegen_fill_token(Parser *p)
577{
Pablo Galindofb61c422020-06-15 14:23:43 +0100578 const char *start;
579 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100580 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700581
582 // Record and skip '# type: ignore' comments
583 while (type == TYPE_IGNORE) {
584 Py_ssize_t len = end - start;
585 char *tag = PyMem_Malloc(len + 1);
586 if (tag == NULL) {
587 PyErr_NoMemory();
588 return -1;
589 }
590 strncpy(tag, start, len);
591 tag[len] = '\0';
592 // Ownership of tag passes to the growable array
593 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
594 PyErr_NoMemory();
595 return -1;
596 }
597 type = PyTokenizer_Get(p->tok, &start, &end);
598 }
599
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100600 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
601 type = NEWLINE; /* Add an extra newline */
602 p->parsing_started = 0;
603
Pablo Galindob94dbd72020-04-27 18:35:58 +0100604 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100605 p->tok->pendin = -p->tok->indent;
606 p->tok->indent = 0;
607 }
608 }
609 else {
610 p->parsing_started = 1;
611 }
612
613 if (p->fill == p->size) {
614 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300615 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
616 if (new_tokens == NULL) {
617 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100618 return -1;
619 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100620 p->tokens = new_tokens;
621
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100622 for (int i = p->size; i < newsize; i++) {
623 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300624 if (p->tokens[i] == NULL) {
625 p->size = i; // Needed, in order to cleanup correctly after parser fails
626 PyErr_NoMemory();
627 return -1;
628 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100629 memset(p->tokens[i], '\0', sizeof(Token));
630 }
631 p->size = newsize;
632 }
633
634 Token *t = p->tokens[p->fill];
635 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
636 t->bytes = PyBytes_FromStringAndSize(start, end - start);
637 if (t->bytes == NULL) {
638 return -1;
639 }
640 PyArena_AddPyObject(p->arena, t->bytes);
641
642 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
643 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100644 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100645 int col_offset = -1;
646 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100647 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100648 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100649 }
650 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100651 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100652 }
653
654 t->lineno = p->starting_lineno + lineno;
655 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
656 t->end_lineno = p->starting_lineno + end_lineno;
657 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
658
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100659 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300660
661 if (type == ERRORTOKEN) {
662 if (p->tok->done == E_DECODE) {
663 return raise_decode_error(p);
664 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100665 return tokenizer_error(p);
666
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300667 }
668
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100669 return 0;
670}
671
672// Instrumentation to count the effectiveness of memoization.
673// The array counts the number of tokens skipped by memoization,
674// indexed by type.
675
676#define NSTATISTICS 2000
677static long memo_statistics[NSTATISTICS];
678
679void
680_PyPegen_clear_memo_statistics()
681{
682 for (int i = 0; i < NSTATISTICS; i++) {
683 memo_statistics[i] = 0;
684 }
685}
686
687PyObject *
688_PyPegen_get_memo_statistics()
689{
690 PyObject *ret = PyList_New(NSTATISTICS);
691 if (ret == NULL) {
692 return NULL;
693 }
694 for (int i = 0; i < NSTATISTICS; i++) {
695 PyObject *value = PyLong_FromLong(memo_statistics[i]);
696 if (value == NULL) {
697 Py_DECREF(ret);
698 return NULL;
699 }
700 // PyList_SetItem borrows a reference to value.
701 if (PyList_SetItem(ret, i, value) < 0) {
702 Py_DECREF(ret);
703 return NULL;
704 }
705 }
706 return ret;
707}
708
709int // bool
710_PyPegen_is_memoized(Parser *p, int type, void *pres)
711{
712 if (p->mark == p->fill) {
713 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300714 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100715 return -1;
716 }
717 }
718
719 Token *t = p->tokens[p->mark];
720
721 for (Memo *m = t->memo; m != NULL; m = m->next) {
722 if (m->type == type) {
723 if (0 <= type && type < NSTATISTICS) {
724 long count = m->mark - p->mark;
725 // A memoized negative result counts for one.
726 if (count <= 0) {
727 count = 1;
728 }
729 memo_statistics[type] += count;
730 }
731 p->mark = m->mark;
732 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100733 return 1;
734 }
735 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100736 return 0;
737}
738
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100739
740int
741_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
742{
743 int mark = p->mark;
744 void *res = func(p);
745 p->mark = mark;
746 return (res != NULL) == positive;
747}
748
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100749int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100750_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
751{
752 int mark = p->mark;
753 void *res = func(p, arg);
754 p->mark = mark;
755 return (res != NULL) == positive;
756}
757
758int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100759_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
760{
761 int mark = p->mark;
762 void *res = func(p, arg);
763 p->mark = mark;
764 return (res != NULL) == positive;
765}
766
767int
768_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
769{
770 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100771 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100772 p->mark = mark;
773 return (res != NULL) == positive;
774}
775
776Token *
777_PyPegen_expect_token(Parser *p, int type)
778{
779 if (p->mark == p->fill) {
780 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300781 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100782 return NULL;
783 }
784 }
785 Token *t = p->tokens[p->mark];
786 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100787 return NULL;
788 }
789 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100790 return t;
791}
792
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700793expr_ty
794_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
795{
796 if (p->mark == p->fill) {
797 if (_PyPegen_fill_token(p) < 0) {
798 p->error_indicator = 1;
799 return NULL;
800 }
801 }
802 Token *t = p->tokens[p->mark];
803 if (t->type != NAME) {
804 return NULL;
805 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300806 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700807 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300808 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700809 return NULL;
810 }
811 if (strcmp(s, keyword) != 0) {
812 return NULL;
813 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300814 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700815}
816
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100817Token *
818_PyPegen_get_last_nonnwhitespace_token(Parser *p)
819{
820 assert(p->mark >= 0);
821 Token *token = NULL;
822 for (int m = p->mark - 1; m >= 0; m--) {
823 token = p->tokens[m];
824 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
825 break;
826 }
827 }
828 return token;
829}
830
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100831expr_ty
832_PyPegen_name_token(Parser *p)
833{
834 Token *t = _PyPegen_expect_token(p, NAME);
835 if (t == NULL) {
836 return NULL;
837 }
838 char* s = PyBytes_AsString(t->bytes);
839 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300840 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100841 return NULL;
842 }
843 PyObject *id = _PyPegen_new_identifier(p, s);
844 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300845 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100846 return NULL;
847 }
848 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
849 p->arena);
850}
851
852void *
853_PyPegen_string_token(Parser *p)
854{
855 return _PyPegen_expect_token(p, STRING);
856}
857
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100858static PyObject *
859parsenumber_raw(const char *s)
860{
861 const char *end;
862 long x;
863 double dx;
864 Py_complex compl;
865 int imflag;
866
867 assert(s != NULL);
868 errno = 0;
869 end = s + strlen(s) - 1;
870 imflag = *end == 'j' || *end == 'J';
871 if (s[0] == '0') {
872 x = (long)PyOS_strtoul(s, (char **)&end, 0);
873 if (x < 0 && errno == 0) {
874 return PyLong_FromString(s, (char **)0, 0);
875 }
876 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100877 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100878 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100879 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100880 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100881 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100882 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100883 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100884 return PyLong_FromLong(x);
885 }
886 /* XXX Huge floats may silently fail */
887 if (imflag) {
888 compl.real = 0.;
889 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100890 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100891 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100892 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100893 return PyComplex_FromCComplex(compl);
894 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100895 dx = PyOS_string_to_double(s, NULL, NULL);
896 if (dx == -1.0 && PyErr_Occurred()) {
897 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100898 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100899 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100900}
901
902static PyObject *
903parsenumber(const char *s)
904{
Pablo Galindofb61c422020-06-15 14:23:43 +0100905 char *dup;
906 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100907 PyObject *res = NULL;
908
909 assert(s != NULL);
910
911 if (strchr(s, '_') == NULL) {
912 return parsenumber_raw(s);
913 }
914 /* Create a duplicate without underscores. */
915 dup = PyMem_Malloc(strlen(s) + 1);
916 if (dup == NULL) {
917 return PyErr_NoMemory();
918 }
919 end = dup;
920 for (; *s; s++) {
921 if (*s != '_') {
922 *end++ = *s;
923 }
924 }
925 *end = '\0';
926 res = parsenumber_raw(dup);
927 PyMem_Free(dup);
928 return res;
929}
930
931expr_ty
932_PyPegen_number_token(Parser *p)
933{
934 Token *t = _PyPegen_expect_token(p, NUMBER);
935 if (t == NULL) {
936 return NULL;
937 }
938
939 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100940 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300941 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100942 return NULL;
943 }
944
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300945 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
946 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700947 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300948 "in Python 3.6 and greater");
949 }
950
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100951 PyObject *c = parsenumber(num_raw);
952
953 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300954 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100955 return NULL;
956 }
957
958 if (PyArena_AddPyObject(p->arena, c) < 0) {
959 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300960 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100961 return NULL;
962 }
963
964 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
965 p->arena);
966}
967
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300968static int // bool
969newline_in_string(Parser *p, const char *cur)
970{
Pablo Galindo2e6593d2020-06-06 00:52:27 +0100971 for (const char *c = cur; c >= p->tok->buf; c--) {
972 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300973 return 1;
974 }
975 }
976 return 0;
977}
978
979/* Check that the source for a single input statement really is a single
980 statement by looking at what is left in the buffer after parsing.
981 Trailing whitespace and comments are OK. */
982static int // bool
983bad_single_statement(Parser *p)
984{
985 const char *cur = strchr(p->tok->buf, '\n');
986
987 /* Newlines are allowed if preceded by a line continuation character
988 or if they appear inside a string. */
989 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
990 return 0;
991 }
992 char c = *cur;
993
994 for (;;) {
995 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
996 c = *++cur;
997 }
998
999 if (!c) {
1000 return 0;
1001 }
1002
1003 if (c != '#') {
1004 return 1;
1005 }
1006
1007 /* Suck up comment. */
1008 while (c && c != '\n') {
1009 c = *++cur;
1010 }
1011 }
1012}
1013
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001014void
1015_PyPegen_Parser_Free(Parser *p)
1016{
1017 Py_XDECREF(p->normalize);
1018 for (int i = 0; i < p->size; i++) {
1019 PyMem_Free(p->tokens[i]);
1020 }
1021 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001022 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001023 PyMem_Free(p);
1024}
1025
Pablo Galindo2b74c832020-04-27 18:02:07 +01001026static int
1027compute_parser_flags(PyCompilerFlags *flags)
1028{
1029 int parser_flags = 0;
1030 if (!flags) {
1031 return 0;
1032 }
1033 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1034 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1035 }
1036 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1037 parser_flags |= PyPARSE_IGNORE_COOKIE;
1038 }
1039 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1040 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1041 }
1042 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1043 parser_flags |= PyPARSE_TYPE_COMMENTS;
1044 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001045 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001046 parser_flags |= PyPARSE_ASYNC_HACKS;
1047 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001048 return parser_flags;
1049}
1050
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001051Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001052_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001053 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001054{
1055 Parser *p = PyMem_Malloc(sizeof(Parser));
1056 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001057 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001058 }
1059 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001060 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1061 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001062 p->tok = tok;
1063 p->keywords = NULL;
1064 p->n_keyword_lists = -1;
1065 p->tokens = PyMem_Malloc(sizeof(Token *));
1066 if (!p->tokens) {
1067 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001068 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001069 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001070 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001071 if (!p->tokens) {
1072 PyMem_Free(p->tokens);
1073 PyMem_Free(p);
1074 return (Parser *) PyErr_NoMemory();
1075 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001076 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1077 PyMem_Free(p->tokens[0]);
1078 PyMem_Free(p->tokens);
1079 PyMem_Free(p);
1080 return (Parser *) PyErr_NoMemory();
1081 }
1082
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001083 p->mark = 0;
1084 p->fill = 0;
1085 p->size = 1;
1086
1087 p->errcode = errcode;
1088 p->arena = arena;
1089 p->start_rule = start_rule;
1090 p->parsing_started = 0;
1091 p->normalize = NULL;
1092 p->error_indicator = 0;
1093
1094 p->starting_lineno = 0;
1095 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001096 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001097 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001098 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001099 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001100
1101 return p;
1102}
1103
1104void *
1105_PyPegen_run_parser(Parser *p)
1106{
1107 void *res = _PyPegen_parse(p);
1108 if (res == NULL) {
1109 if (PyErr_Occurred()) {
1110 return NULL;
1111 }
1112 if (p->fill == 0) {
1113 RAISE_SYNTAX_ERROR("error at start before reading any input");
1114 }
1115 else if (p->tok->done == E_EOF) {
1116 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1117 }
1118 else {
1119 if (p->tokens[p->fill-1]->type == INDENT) {
1120 RAISE_INDENTATION_ERROR("unexpected indent");
1121 }
1122 else if (p->tokens[p->fill-1]->type == DEDENT) {
1123 RAISE_INDENTATION_ERROR("unexpected unindent");
1124 }
1125 else {
1126 RAISE_SYNTAX_ERROR("invalid syntax");
1127 }
1128 }
1129 return NULL;
1130 }
1131
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001132 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1133 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1134 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1135 }
1136
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001137 return res;
1138}
1139
1140mod_ty
1141_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1142 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001143 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001144{
1145 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1146 if (tok == NULL) {
1147 if (PyErr_Occurred()) {
1148 raise_tokenizer_init_error(filename_ob);
1149 return NULL;
1150 }
1151 return NULL;
1152 }
1153 // This transfers the ownership to the tokenizer
1154 tok->filename = filename_ob;
1155 Py_INCREF(filename_ob);
1156
1157 // From here on we need to clean up even if there's an error
1158 mod_ty result = NULL;
1159
Pablo Galindo2b74c832020-04-27 18:02:07 +01001160 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001161 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1162 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001163 if (p == NULL) {
1164 goto error;
1165 }
1166
1167 result = _PyPegen_run_parser(p);
1168 _PyPegen_Parser_Free(p);
1169
1170error:
1171 PyTokenizer_Free(tok);
1172 return result;
1173}
1174
1175mod_ty
1176_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001177 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001178{
1179 FILE *fp = fopen(filename, "rb");
1180 if (fp == NULL) {
1181 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1182 return NULL;
1183 }
1184
1185 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001186 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001187
1188 fclose(fp);
1189 return result;
1190}
1191
1192mod_ty
1193_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001194 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001195{
1196 int exec_input = start_rule == Py_file_input;
1197
1198 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001199 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001200 tok = PyTokenizer_FromUTF8(str, exec_input);
1201 } else {
1202 tok = PyTokenizer_FromString(str, exec_input);
1203 }
1204 if (tok == NULL) {
1205 if (PyErr_Occurred()) {
1206 raise_tokenizer_init_error(filename_ob);
1207 }
1208 return NULL;
1209 }
1210 // This transfers the ownership to the tokenizer
1211 tok->filename = filename_ob;
1212 Py_INCREF(filename_ob);
1213
1214 // We need to clear up from here on
1215 mod_ty result = NULL;
1216
Pablo Galindo2b74c832020-04-27 18:02:07 +01001217 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001218 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1219 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001220 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1221 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001222 if (p == NULL) {
1223 goto error;
1224 }
1225
1226 result = _PyPegen_run_parser(p);
1227 _PyPegen_Parser_Free(p);
1228
1229error:
1230 PyTokenizer_Free(tok);
1231 return result;
1232}
1233
1234void *
1235_PyPegen_interactive_exit(Parser *p)
1236{
1237 if (p->errcode) {
1238 *(p->errcode) = E_EOF;
1239 }
1240 return NULL;
1241}
1242
1243/* Creates a single-element asdl_seq* that contains a */
1244asdl_seq *
1245_PyPegen_singleton_seq(Parser *p, void *a)
1246{
1247 assert(a != NULL);
1248 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1249 if (!seq) {
1250 return NULL;
1251 }
1252 asdl_seq_SET(seq, 0, a);
1253 return seq;
1254}
1255
1256/* Creates a copy of seq and prepends a to it */
1257asdl_seq *
1258_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1259{
1260 assert(a != NULL);
1261 if (!seq) {
1262 return _PyPegen_singleton_seq(p, a);
1263 }
1264
1265 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1266 if (!new_seq) {
1267 return NULL;
1268 }
1269
1270 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001271 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001272 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1273 }
1274 return new_seq;
1275}
1276
Guido van Rossumc001c092020-04-30 12:12:19 -07001277/* Creates a copy of seq and appends a to it */
1278asdl_seq *
1279_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1280{
1281 assert(a != NULL);
1282 if (!seq) {
1283 return _PyPegen_singleton_seq(p, a);
1284 }
1285
1286 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1287 if (!new_seq) {
1288 return NULL;
1289 }
1290
1291 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1292 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1293 }
1294 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1295 return new_seq;
1296}
1297
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001298static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001299_get_flattened_seq_size(asdl_seq *seqs)
1300{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001301 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001302 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1303 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1304 size += asdl_seq_LEN(inner_seq);
1305 }
1306 return size;
1307}
1308
1309/* Flattens an asdl_seq* of asdl_seq*s */
1310asdl_seq *
1311_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1312{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001313 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001314 assert(flattened_seq_size > 0);
1315
1316 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1317 if (!flattened_seq) {
1318 return NULL;
1319 }
1320
1321 int flattened_seq_idx = 0;
1322 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1323 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001324 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001325 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1326 }
1327 }
1328 assert(flattened_seq_idx == flattened_seq_size);
1329
1330 return flattened_seq;
1331}
1332
1333/* Creates a new name of the form <first_name>.<second_name> */
1334expr_ty
1335_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1336{
1337 assert(first_name != NULL && second_name != NULL);
1338 PyObject *first_identifier = first_name->v.Name.id;
1339 PyObject *second_identifier = second_name->v.Name.id;
1340
1341 if (PyUnicode_READY(first_identifier) == -1) {
1342 return NULL;
1343 }
1344 if (PyUnicode_READY(second_identifier) == -1) {
1345 return NULL;
1346 }
1347 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1348 if (!first_str) {
1349 return NULL;
1350 }
1351 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1352 if (!second_str) {
1353 return NULL;
1354 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001355 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001356
1357 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1358 if (!str) {
1359 return NULL;
1360 }
1361
1362 char *s = PyBytes_AS_STRING(str);
1363 if (!s) {
1364 return NULL;
1365 }
1366
1367 strcpy(s, first_str);
1368 s += strlen(first_str);
1369 *s++ = '.';
1370 strcpy(s, second_str);
1371 s += strlen(second_str);
1372 *s = '\0';
1373
1374 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1375 Py_DECREF(str);
1376 if (!uni) {
1377 return NULL;
1378 }
1379 PyUnicode_InternInPlace(&uni);
1380 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1381 Py_DECREF(uni);
1382 return NULL;
1383 }
1384
1385 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1386}
1387
1388/* Counts the total number of dots in seq's tokens */
1389int
1390_PyPegen_seq_count_dots(asdl_seq *seq)
1391{
1392 int number_of_dots = 0;
1393 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1394 Token *current_expr = asdl_seq_GET(seq, i);
1395 switch (current_expr->type) {
1396 case ELLIPSIS:
1397 number_of_dots += 3;
1398 break;
1399 case DOT:
1400 number_of_dots += 1;
1401 break;
1402 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001403 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001404 }
1405 }
1406
1407 return number_of_dots;
1408}
1409
1410/* Creates an alias with '*' as the identifier name */
1411alias_ty
1412_PyPegen_alias_for_star(Parser *p)
1413{
1414 PyObject *str = PyUnicode_InternFromString("*");
1415 if (!str) {
1416 return NULL;
1417 }
1418 if (PyArena_AddPyObject(p->arena, str) < 0) {
1419 Py_DECREF(str);
1420 return NULL;
1421 }
1422 return alias(str, NULL, p->arena);
1423}
1424
1425/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1426asdl_seq *
1427_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1428{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001429 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001430 assert(len > 0);
1431
1432 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1433 if (!new_seq) {
1434 return NULL;
1435 }
1436 for (Py_ssize_t i = 0; i < len; i++) {
1437 expr_ty e = asdl_seq_GET(seq, i);
1438 asdl_seq_SET(new_seq, i, e->v.Name.id);
1439 }
1440 return new_seq;
1441}
1442
1443/* Constructs a CmpopExprPair */
1444CmpopExprPair *
1445_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1446{
1447 assert(expr != NULL);
1448 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1449 if (!a) {
1450 return NULL;
1451 }
1452 a->cmpop = cmpop;
1453 a->expr = expr;
1454 return a;
1455}
1456
1457asdl_int_seq *
1458_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1459{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001460 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001461 assert(len > 0);
1462
1463 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1464 if (!new_seq) {
1465 return NULL;
1466 }
1467 for (Py_ssize_t i = 0; i < len; i++) {
1468 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1469 asdl_seq_SET(new_seq, i, pair->cmpop);
1470 }
1471 return new_seq;
1472}
1473
1474asdl_seq *
1475_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1476{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001477 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001478 assert(len > 0);
1479
1480 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1481 if (!new_seq) {
1482 return NULL;
1483 }
1484 for (Py_ssize_t i = 0; i < len; i++) {
1485 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1486 asdl_seq_SET(new_seq, i, pair->expr);
1487 }
1488 return new_seq;
1489}
1490
1491/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1492static asdl_seq *
1493_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1494{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001495 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001496 if (len == 0) {
1497 return NULL;
1498 }
1499
1500 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1501 if (!new_seq) {
1502 return NULL;
1503 }
1504 for (Py_ssize_t i = 0; i < len; i++) {
1505 expr_ty e = asdl_seq_GET(seq, i);
1506 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1507 }
1508 return new_seq;
1509}
1510
1511static expr_ty
1512_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1513{
1514 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1515}
1516
1517static expr_ty
1518_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1519{
1520 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1521}
1522
1523static expr_ty
1524_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1525{
1526 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1527}
1528
1529static expr_ty
1530_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1531{
1532 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1533}
1534
1535static expr_ty
1536_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1537{
1538 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1539}
1540
1541static expr_ty
1542_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1543{
1544 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1545}
1546
1547/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1548expr_ty
1549_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1550{
1551 assert(expr != NULL);
1552
1553 expr_ty new = NULL;
1554 switch (expr->kind) {
1555 case Name_kind:
1556 new = _set_name_context(p, expr, ctx);
1557 break;
1558 case Tuple_kind:
1559 new = _set_tuple_context(p, expr, ctx);
1560 break;
1561 case List_kind:
1562 new = _set_list_context(p, expr, ctx);
1563 break;
1564 case Subscript_kind:
1565 new = _set_subscript_context(p, expr, ctx);
1566 break;
1567 case Attribute_kind:
1568 new = _set_attribute_context(p, expr, ctx);
1569 break;
1570 case Starred_kind:
1571 new = _set_starred_context(p, expr, ctx);
1572 break;
1573 default:
1574 new = expr;
1575 }
1576 return new;
1577}
1578
1579/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1580KeyValuePair *
1581_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1582{
1583 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1584 if (!a) {
1585 return NULL;
1586 }
1587 a->key = key;
1588 a->value = value;
1589 return a;
1590}
1591
1592/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1593asdl_seq *
1594_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1595{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001596 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001597 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1598 if (!new_seq) {
1599 return NULL;
1600 }
1601 for (Py_ssize_t i = 0; i < len; i++) {
1602 KeyValuePair *pair = asdl_seq_GET(seq, i);
1603 asdl_seq_SET(new_seq, i, pair->key);
1604 }
1605 return new_seq;
1606}
1607
1608/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1609asdl_seq *
1610_PyPegen_get_values(Parser *p, asdl_seq *seq)
1611{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001612 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001613 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1614 if (!new_seq) {
1615 return NULL;
1616 }
1617 for (Py_ssize_t i = 0; i < len; i++) {
1618 KeyValuePair *pair = asdl_seq_GET(seq, i);
1619 asdl_seq_SET(new_seq, i, pair->value);
1620 }
1621 return new_seq;
1622}
1623
1624/* Constructs a NameDefaultPair */
1625NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001626_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001627{
1628 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1629 if (!a) {
1630 return NULL;
1631 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001632 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001633 a->value = value;
1634 return a;
1635}
1636
1637/* Constructs a SlashWithDefault */
1638SlashWithDefault *
1639_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1640{
1641 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1642 if (!a) {
1643 return NULL;
1644 }
1645 a->plain_names = plain_names;
1646 a->names_with_defaults = names_with_defaults;
1647 return a;
1648}
1649
1650/* Constructs a StarEtc */
1651StarEtc *
1652_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1653{
1654 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1655 if (!a) {
1656 return NULL;
1657 }
1658 a->vararg = vararg;
1659 a->kwonlyargs = kwonlyargs;
1660 a->kwarg = kwarg;
1661 return a;
1662}
1663
1664asdl_seq *
1665_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1666{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001667 Py_ssize_t first_len = asdl_seq_LEN(a);
1668 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001669 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1670 if (!new_seq) {
1671 return NULL;
1672 }
1673
1674 int k = 0;
1675 for (Py_ssize_t i = 0; i < first_len; i++) {
1676 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1677 }
1678 for (Py_ssize_t i = 0; i < second_len; i++) {
1679 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1680 }
1681
1682 return new_seq;
1683}
1684
1685static asdl_seq *
1686_get_names(Parser *p, asdl_seq *names_with_defaults)
1687{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001688 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001689 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1690 if (!seq) {
1691 return NULL;
1692 }
1693 for (Py_ssize_t i = 0; i < len; i++) {
1694 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1695 asdl_seq_SET(seq, i, pair->arg);
1696 }
1697 return seq;
1698}
1699
1700static asdl_seq *
1701_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1702{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001703 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001704 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1705 if (!seq) {
1706 return NULL;
1707 }
1708 for (Py_ssize_t i = 0; i < len; i++) {
1709 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1710 asdl_seq_SET(seq, i, pair->value);
1711 }
1712 return seq;
1713}
1714
1715/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1716arguments_ty
1717_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1718 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1719 asdl_seq *names_with_default, StarEtc *star_etc)
1720{
1721 asdl_seq *posonlyargs;
1722 if (slash_without_default != NULL) {
1723 posonlyargs = slash_without_default;
1724 }
1725 else if (slash_with_default != NULL) {
1726 asdl_seq *slash_with_default_names =
1727 _get_names(p, slash_with_default->names_with_defaults);
1728 if (!slash_with_default_names) {
1729 return NULL;
1730 }
1731 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1732 if (!posonlyargs) {
1733 return NULL;
1734 }
1735 }
1736 else {
1737 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1738 if (!posonlyargs) {
1739 return NULL;
1740 }
1741 }
1742
1743 asdl_seq *posargs;
1744 if (plain_names != NULL && names_with_default != NULL) {
1745 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1746 if (!names_with_default_names) {
1747 return NULL;
1748 }
1749 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1750 if (!posargs) {
1751 return NULL;
1752 }
1753 }
1754 else if (plain_names == NULL && names_with_default != NULL) {
1755 posargs = _get_names(p, names_with_default);
1756 if (!posargs) {
1757 return NULL;
1758 }
1759 }
1760 else if (plain_names != NULL && names_with_default == NULL) {
1761 posargs = plain_names;
1762 }
1763 else {
1764 posargs = _Py_asdl_seq_new(0, p->arena);
1765 if (!posargs) {
1766 return NULL;
1767 }
1768 }
1769
1770 asdl_seq *posdefaults;
1771 if (slash_with_default != NULL && names_with_default != NULL) {
1772 asdl_seq *slash_with_default_values =
1773 _get_defaults(p, slash_with_default->names_with_defaults);
1774 if (!slash_with_default_values) {
1775 return NULL;
1776 }
1777 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1778 if (!names_with_default_values) {
1779 return NULL;
1780 }
1781 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1782 if (!posdefaults) {
1783 return NULL;
1784 }
1785 }
1786 else if (slash_with_default == NULL && names_with_default != NULL) {
1787 posdefaults = _get_defaults(p, names_with_default);
1788 if (!posdefaults) {
1789 return NULL;
1790 }
1791 }
1792 else if (slash_with_default != NULL && names_with_default == NULL) {
1793 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1794 if (!posdefaults) {
1795 return NULL;
1796 }
1797 }
1798 else {
1799 posdefaults = _Py_asdl_seq_new(0, p->arena);
1800 if (!posdefaults) {
1801 return NULL;
1802 }
1803 }
1804
1805 arg_ty vararg = NULL;
1806 if (star_etc != NULL && star_etc->vararg != NULL) {
1807 vararg = star_etc->vararg;
1808 }
1809
1810 asdl_seq *kwonlyargs;
1811 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1812 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1813 if (!kwonlyargs) {
1814 return NULL;
1815 }
1816 }
1817 else {
1818 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1819 if (!kwonlyargs) {
1820 return NULL;
1821 }
1822 }
1823
1824 asdl_seq *kwdefaults;
1825 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1826 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1827 if (!kwdefaults) {
1828 return NULL;
1829 }
1830 }
1831 else {
1832 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1833 if (!kwdefaults) {
1834 return NULL;
1835 }
1836 }
1837
1838 arg_ty kwarg = NULL;
1839 if (star_etc != NULL && star_etc->kwarg != NULL) {
1840 kwarg = star_etc->kwarg;
1841 }
1842
1843 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1844 posdefaults, p->arena);
1845}
1846
1847/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1848 * arguments. */
1849arguments_ty
1850_PyPegen_empty_arguments(Parser *p)
1851{
1852 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1853 if (!posonlyargs) {
1854 return NULL;
1855 }
1856 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1857 if (!posargs) {
1858 return NULL;
1859 }
1860 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1861 if (!posdefaults) {
1862 return NULL;
1863 }
1864 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1865 if (!kwonlyargs) {
1866 return NULL;
1867 }
1868 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1869 if (!kwdefaults) {
1870 return NULL;
1871 }
1872
1873 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1874 p->arena);
1875}
1876
1877/* Encapsulates the value of an operator_ty into an AugOperator struct */
1878AugOperator *
1879_PyPegen_augoperator(Parser *p, operator_ty kind)
1880{
1881 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1882 if (!a) {
1883 return NULL;
1884 }
1885 a->kind = kind;
1886 return a;
1887}
1888
1889/* Construct a FunctionDef equivalent to function_def, but with decorators */
1890stmt_ty
1891_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1892{
1893 assert(function_def != NULL);
1894 if (function_def->kind == AsyncFunctionDef_kind) {
1895 return _Py_AsyncFunctionDef(
1896 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1897 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1898 function_def->v.FunctionDef.type_comment, function_def->lineno,
1899 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1900 p->arena);
1901 }
1902
1903 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1904 function_def->v.FunctionDef.body, decorators,
1905 function_def->v.FunctionDef.returns,
1906 function_def->v.FunctionDef.type_comment, function_def->lineno,
1907 function_def->col_offset, function_def->end_lineno,
1908 function_def->end_col_offset, p->arena);
1909}
1910
1911/* Construct a ClassDef equivalent to class_def, but with decorators */
1912stmt_ty
1913_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1914{
1915 assert(class_def != NULL);
1916 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1917 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1918 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1919 class_def->end_col_offset, p->arena);
1920}
1921
1922/* Construct a KeywordOrStarred */
1923KeywordOrStarred *
1924_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1925{
1926 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1927 if (!a) {
1928 return NULL;
1929 }
1930 a->element = element;
1931 a->is_keyword = is_keyword;
1932 return a;
1933}
1934
1935/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1936static int
1937_seq_number_of_starred_exprs(asdl_seq *seq)
1938{
1939 int n = 0;
1940 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1941 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1942 if (!k->is_keyword) {
1943 n++;
1944 }
1945 }
1946 return n;
1947}
1948
1949/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1950asdl_seq *
1951_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1952{
1953 int new_len = _seq_number_of_starred_exprs(kwargs);
1954 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, len = asdl_seq_LEN(kwargs); 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
1972/* Return a new asdl_seq* with only the keywords in kwargs */
1973asdl_seq *
1974_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1975{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001976 Py_ssize_t len = asdl_seq_LEN(kwargs);
1977 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001978 if (new_len == 0) {
1979 return NULL;
1980 }
1981 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1982 if (!new_seq) {
1983 return NULL;
1984 }
1985
1986 int idx = 0;
1987 for (Py_ssize_t i = 0; i < len; i++) {
1988 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1989 if (k->is_keyword) {
1990 asdl_seq_SET(new_seq, idx++, k->element);
1991 }
1992 }
1993 return new_seq;
1994}
1995
1996expr_ty
1997_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1998{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001999 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002000 assert(len > 0);
2001
2002 Token *first = asdl_seq_GET(strings, 0);
2003 Token *last = asdl_seq_GET(strings, len - 1);
2004
2005 int bytesmode = 0;
2006 PyObject *bytes_str = NULL;
2007
2008 FstringParser state;
2009 _PyPegen_FstringParser_Init(&state);
2010
2011 for (Py_ssize_t i = 0; i < len; i++) {
2012 Token *t = asdl_seq_GET(strings, i);
2013
2014 int this_bytesmode;
2015 int this_rawmode;
2016 PyObject *s;
2017 const char *fstr;
2018 Py_ssize_t fstrlen = -1;
2019
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002020 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002021 goto error;
2022 }
2023
2024 /* Check that we are not mixing bytes with unicode. */
2025 if (i != 0 && bytesmode != this_bytesmode) {
2026 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2027 Py_XDECREF(s);
2028 goto error;
2029 }
2030 bytesmode = this_bytesmode;
2031
2032 if (fstr != NULL) {
2033 assert(s == NULL && !bytesmode);
2034
2035 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2036 this_rawmode, 0, first, t, last);
2037 if (result < 0) {
2038 goto error;
2039 }
2040 }
2041 else {
2042 /* String or byte string. */
2043 assert(s != NULL && fstr == NULL);
2044 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2045
2046 if (bytesmode) {
2047 if (i == 0) {
2048 bytes_str = s;
2049 }
2050 else {
2051 PyBytes_ConcatAndDel(&bytes_str, s);
2052 if (!bytes_str) {
2053 goto error;
2054 }
2055 }
2056 }
2057 else {
2058 /* This is a regular string. Concatenate it. */
2059 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2060 goto error;
2061 }
2062 }
2063 }
2064 }
2065
2066 if (bytesmode) {
2067 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2068 goto error;
2069 }
2070 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2071 last->end_col_offset, p->arena);
2072 }
2073
2074 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2075
2076error:
2077 Py_XDECREF(bytes_str);
2078 _PyPegen_FstringParser_Dealloc(&state);
2079 if (PyErr_Occurred()) {
2080 raise_decode_error(p);
2081 }
2082 return NULL;
2083}
Guido van Rossumc001c092020-04-30 12:12:19 -07002084
2085mod_ty
2086_PyPegen_make_module(Parser *p, asdl_seq *a) {
2087 asdl_seq *type_ignores = NULL;
2088 Py_ssize_t num = p->type_ignore_comments.num_items;
2089 if (num > 0) {
2090 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2091 type_ignores = _Py_asdl_seq_new(num, p->arena);
2092 if (type_ignores == NULL) {
2093 return NULL;
2094 }
2095 for (int i = 0; i < num; i++) {
2096 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2097 if (tag == NULL) {
2098 return NULL;
2099 }
2100 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2101 if (ti == NULL) {
2102 return NULL;
2103 }
2104 asdl_seq_SET(type_ignores, i, ti);
2105 }
2106 }
2107 return Module(a, type_ignores, p->arena);
2108}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002109
2110// Error reporting helpers
2111
2112expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002113_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002114{
2115 if (e == NULL) {
2116 return NULL;
2117 }
2118
2119#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2120 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2121 for (Py_ssize_t i = 0; i < len; i++) {\
2122 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002123 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002124 if (child != NULL) {\
2125 return child;\
2126 }\
2127 }\
2128 } while (0)
2129
2130 // We only need to visit List and Tuple nodes recursively as those
2131 // are the only ones that can contain valid names in targets when
2132 // they are parsed as expressions. Any other kind of expression
2133 // that is a container (like Sets or Dicts) is directly invalid and
2134 // we don't need to visit it recursively.
2135
2136 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002137 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002138 VISIT_CONTAINER(e, List);
2139 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002140 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002141 VISIT_CONTAINER(e, Tuple);
2142 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002143 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002144 if (targets_type == DEL_TARGETS) {
2145 return e;
2146 }
2147 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2148 case Compare_kind:
2149 // This is needed, because the `a in b` in `for a in b` gets parsed
2150 // as a comparison, and so we need to search the left side of the comparison
2151 // for invalid targets.
2152 if (targets_type == FOR_TARGETS) {
2153 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2154 if (cmpop == In) {
2155 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2156 }
2157 return NULL;
2158 }
2159 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002160 case Name_kind:
2161 case Subscript_kind:
2162 case Attribute_kind:
2163 return NULL;
2164 default:
2165 return e;
2166 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002167}
2168
2169void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2170 int kwarg_unpacking = 0;
2171 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2172 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2173 if (!keyword->arg) {
2174 kwarg_unpacking = 1;
2175 }
2176 }
2177
2178 const char *msg = NULL;
2179 if (kwarg_unpacking) {
2180 msg = "positional argument follows keyword argument unpacking";
2181 } else {
2182 msg = "positional argument follows keyword argument";
2183 }
2184
2185 return RAISE_SYNTAX_ERROR(msg);
2186}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002187
2188void *
2189_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2190{
2191 /* The rule that calls this function is 'args for_if_clauses'.
2192 For the input f(L, x for x in y), L and x are in args and
2193 the for is parsed as a for_if_clause. We have to check if
2194 len <= 1, so that input like dict((a, b) for a, b in x)
2195 gets successfully parsed and then we pass the last
2196 argument (x in the above example) as the location of the
2197 error */
2198 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2199 if (len <= 1) {
2200 return NULL;
2201 }
2202
2203 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2204 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2205 "Generator expression must be parenthesized"
2206 );
2207}