blob: 9513f917b30fbf9e9baab6034c31b7b36af0804a [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
3#include "../tokenizer.h"
4
5#include "pegen.h"
6#include "parse_string.h"
7
Guido van Rossumc001c092020-04-30 12:12:19 -07008PyObject *
9_PyPegen_new_type_comment(Parser *p, char *s)
10{
11 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
12 if (res == NULL) {
13 return NULL;
14 }
15 if (PyArena_AddPyObject(p->arena, res) < 0) {
16 Py_DECREF(res);
17 return NULL;
18 }
19 return res;
20}
21
22arg_ty
23_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
24{
25 if (tc == NULL) {
26 return a;
27 }
28 char *bytes = PyBytes_AsString(tc->bytes);
29 if (bytes == NULL) {
30 return NULL;
31 }
32 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
33 if (tco == NULL) {
34 return NULL;
35 }
36 return arg(a->arg, a->annotation, tco,
37 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
38 p->arena);
39}
40
Pablo Galindoc5fc1562020-04-22 23:29:27 +010041static int
42init_normalization(Parser *p)
43{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030044 if (p->normalize) {
45 return 1;
46 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010047 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
48 if (!m)
49 {
50 return 0;
51 }
52 p->normalize = PyObject_GetAttrString(m, "normalize");
53 Py_DECREF(m);
54 if (!p->normalize)
55 {
56 return 0;
57 }
58 return 1;
59}
60
Pablo Galindo2b74c832020-04-27 18:02:07 +010061/* Checks if the NOTEQUAL token is valid given the current parser flags
620 indicates success and nonzero indicates failure (an exception may be set) */
63int
64_PyPegen_check_barry_as_flufl(Parser *p) {
65 Token *t = p->tokens[p->fill - 1];
66 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindo30b59fd2020-06-15 15:08:00 +010070 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010071 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
Pablo Galindo30b59fd2020-06-15 15:08:00 +010073 }
74 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010075 return strcmp(tok_str, "!=");
76 }
77 return 0;
78}
79
Pablo Galindoc5fc1562020-04-22 23:29:27 +010080PyObject *
81_PyPegen_new_identifier(Parser *p, char *n)
82{
83 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
84 if (!id) {
85 goto error;
86 }
87 /* PyUnicode_DecodeUTF8 should always return a ready string. */
88 assert(PyUnicode_IS_READY(id));
89 /* Check whether there are non-ASCII characters in the
90 identifier; if so, normalize to NFKC. */
91 if (!PyUnicode_IS_ASCII(id))
92 {
93 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030094 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010095 {
96 Py_DECREF(id);
97 goto error;
98 }
99 PyObject *form = PyUnicode_InternFromString("NFKC");
100 if (form == NULL)
101 {
102 Py_DECREF(id);
103 goto error;
104 }
105 PyObject *args[2] = {form, id};
106 id2 = _PyObject_FastCall(p->normalize, args, 2);
107 Py_DECREF(id);
108 Py_DECREF(form);
109 if (!id2) {
110 goto error;
111 }
112 if (!PyUnicode_Check(id2))
113 {
114 PyErr_Format(PyExc_TypeError,
115 "unicodedata.normalize() must return a string, not "
116 "%.200s",
117 _PyType_Name(Py_TYPE(id2)));
118 Py_DECREF(id2);
119 goto error;
120 }
121 id = id2;
122 }
123 PyUnicode_InternInPlace(&id);
124 if (PyArena_AddPyObject(p->arena, id) < 0)
125 {
126 Py_DECREF(id);
127 goto error;
128 }
129 return id;
130
131error:
132 p->error_indicator = 1;
133 return NULL;
134}
135
136static PyObject *
137_create_dummy_identifier(Parser *p)
138{
139 return _PyPegen_new_identifier(p, "");
140}
141
142static inline Py_ssize_t
143byte_offset_to_character_offset(PyObject *line, int col_offset)
144{
145 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300146 if (!str) {
147 return 0;
148 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300149 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100150 if (!text) {
151 return 0;
152 }
153 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300154 str = PyUnicode_AsUTF8(text);
155 if (str != NULL && (int)strlen(str) == col_offset) {
156 size = strlen(str);
157 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100158 Py_DECREF(text);
159 return size;
160}
161
162const char *
163_PyPegen_get_expr_name(expr_ty e)
164{
Miss Islington (bot)8df4f392020-06-08 02:22:06 -0700165 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100166 switch (e->kind) {
167 case Attribute_kind:
168 return "attribute";
169 case Subscript_kind:
170 return "subscript";
171 case Starred_kind:
172 return "starred";
173 case Name_kind:
174 return "name";
175 case List_kind:
176 return "list";
177 case Tuple_kind:
178 return "tuple";
179 case Lambda_kind:
180 return "lambda";
181 case Call_kind:
182 return "function call";
183 case BoolOp_kind:
184 case BinOp_kind:
185 case UnaryOp_kind:
186 return "operator";
187 case GeneratorExp_kind:
188 return "generator expression";
189 case Yield_kind:
190 case YieldFrom_kind:
191 return "yield expression";
192 case Await_kind:
193 return "await expression";
194 case ListComp_kind:
195 return "list comprehension";
196 case SetComp_kind:
197 return "set comprehension";
198 case DictComp_kind:
199 return "dict comprehension";
200 case Dict_kind:
201 return "dict display";
202 case Set_kind:
203 return "set display";
204 case JoinedStr_kind:
205 case FormattedValue_kind:
206 return "f-string expression";
207 case Constant_kind: {
208 PyObject *value = e->v.Constant.value;
209 if (value == Py_None) {
210 return "None";
211 }
212 if (value == Py_False) {
213 return "False";
214 }
215 if (value == Py_True) {
216 return "True";
217 }
218 if (value == Py_Ellipsis) {
219 return "Ellipsis";
220 }
221 return "literal";
222 }
223 case Compare_kind:
224 return "comparison";
225 case IfExp_kind:
226 return "conditional expression";
227 case NamedExpr_kind:
228 return "named expression";
229 default:
230 PyErr_Format(PyExc_SystemError,
231 "unexpected expression in assignment %d (line %d)",
232 e->kind, e->lineno);
233 return NULL;
234 }
235}
236
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300237static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100238raise_decode_error(Parser *p)
239{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300240 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100241 const char *errtype = NULL;
242 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
243 errtype = "unicode error";
244 }
245 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
246 errtype = "value error";
247 }
248 if (errtype) {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100249 PyObject *type;
250 PyObject *value;
251 PyObject *tback;
252 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100253 PyErr_Fetch(&type, &value, &tback);
254 errstr = PyObject_Str(value);
255 if (errstr) {
256 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
257 Py_DECREF(errstr);
258 }
259 else {
260 PyErr_Clear();
261 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
262 }
263 Py_XDECREF(type);
264 Py_XDECREF(value);
265 Py_XDECREF(tback);
266 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300267
268 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100269}
270
271static void
272raise_tokenizer_init_error(PyObject *filename)
273{
274 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
275 || PyErr_ExceptionMatches(PyExc_ValueError)
276 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
277 return;
278 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300279 PyObject *errstr = NULL;
280 PyObject *tuple = NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100281 PyObject *type;
282 PyObject *value;
283 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100284 PyErr_Fetch(&type, &value, &tback);
285 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300286 if (!errstr) {
287 goto error;
288 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100289
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300290 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100291 if (!tmp) {
292 goto error;
293 }
294
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300295 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100296 Py_DECREF(tmp);
297 if (!value) {
298 goto error;
299 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300300 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100301
302error:
303 Py_XDECREF(type);
304 Py_XDECREF(value);
305 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300306 Py_XDECREF(errstr);
307 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308}
309
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100310static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100311tokenizer_error(Parser *p)
312{
313 if (PyErr_Occurred()) {
314 return -1;
315 }
316
317 const char *msg = NULL;
318 PyObject* errtype = PyExc_SyntaxError;
319 switch (p->tok->done) {
320 case E_TOKEN:
321 msg = "invalid token";
322 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100323 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300324 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
325 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100326 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300327 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
328 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300329 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300330 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
331 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300333 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
334 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100335 case E_INTR:
336 if (!PyErr_Occurred()) {
337 PyErr_SetNone(PyExc_KeyboardInterrupt);
338 }
339 return -1;
340 case E_NOMEM:
341 PyErr_NoMemory();
342 return -1;
343 case E_TABSPACE:
344 errtype = PyExc_TabError;
345 msg = "inconsistent use of tabs and spaces in indentation";
346 break;
347 case E_TOODEEP:
348 errtype = PyExc_IndentationError;
349 msg = "too many levels of indentation";
350 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100351 case E_LINECONT:
352 msg = "unexpected character after line continuation character";
353 break;
354 default:
355 msg = "unknown parsing error";
356 }
357
358 PyErr_Format(errtype, msg);
359 // There is no reliable column information for this error
360 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
361
362 return -1;
363}
364
365void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300366_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
367{
368 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
369 int col_offset;
370 if (t->col_offset == -1) {
371 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
372 intptr_t, int);
373 } else {
374 col_offset = t->col_offset + 1;
375 }
376
377 va_list va;
378 va_start(va, errmsg);
379 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
380 col_offset, errmsg, va);
381 va_end(va);
382
383 return NULL;
384}
385
386
387void *
388_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
389 int lineno, int col_offset,
390 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391{
392 PyObject *value = NULL;
393 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300394 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100395 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300396 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100397
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100398 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100399 if (!errstr) {
400 goto error;
401 }
402
403 if (p->start_rule == Py_file_input) {
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300404 error_line = PyErr_ProgramTextObject(p->tok->filename, lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100405 }
406
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300407 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100408 Py_ssize_t size = p->tok->inp - p->tok->buf;
409 if (size && p->tok->buf[size-1] == '\n') {
410 size--;
411 }
412 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300413 if (!error_line) {
414 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300415 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100416 }
417
Miss Islington (bot)11fb6052020-05-23 22:20:44 -0700418 Py_ssize_t col_number = byte_offset_to_character_offset(error_line, col_offset);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300419
420 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100421 if (!tmp) {
422 goto error;
423 }
424 value = PyTuple_Pack(2, errstr, tmp);
425 Py_DECREF(tmp);
426 if (!value) {
427 goto error;
428 }
429 PyErr_SetObject(errtype, value);
430
431 Py_DECREF(errstr);
432 Py_DECREF(value);
433 return NULL;
434
435error:
436 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300437 Py_XDECREF(error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100438 return NULL;
439}
440
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100441#if 0
442static const char *
443token_name(int type)
444{
445 if (0 <= type && type <= N_TOKENS) {
446 return _PyParser_TokenNames[type];
447 }
448 return "<Huh?>";
449}
450#endif
451
452// Here, mark is the start of the node, while p->mark is the end.
453// If node==NULL, they should be the same.
454int
455_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
456{
457 // Insert in front
458 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
459 if (m == NULL) {
460 return -1;
461 }
462 m->type = type;
463 m->node = node;
464 m->mark = p->mark;
465 m->next = p->tokens[mark]->memo;
466 p->tokens[mark]->memo = m;
467 return 0;
468}
469
470// Like _PyPegen_insert_memo(), but updates an existing node if found.
471int
472_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
473{
474 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
475 if (m->type == type) {
476 // Update existing node.
477 m->node = node;
478 m->mark = p->mark;
479 return 0;
480 }
481 }
482 // Insert new node.
483 return _PyPegen_insert_memo(p, mark, type, node);
484}
485
486// Return dummy NAME.
487void *
488_PyPegen_dummy_name(Parser *p, ...)
489{
490 static void *cache = NULL;
491
492 if (cache != NULL) {
493 return cache;
494 }
495
496 PyObject *id = _create_dummy_identifier(p);
497 if (!id) {
498 return NULL;
499 }
500 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
501 return cache;
502}
503
504static int
505_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
506{
507 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
508 return NAME;
509 }
510 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
511 if (strncmp(k->str, name, name_len) == 0) {
512 return k->type;
513 }
514 }
515 return NAME;
516}
517
Guido van Rossumc001c092020-04-30 12:12:19 -0700518static int
519growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
520 assert(initial_size > 0);
521 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
522 arr->size = initial_size;
523 arr->num_items = 0;
524
525 return arr->items != NULL;
526}
527
528static int
529growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
530 if (arr->num_items >= arr->size) {
531 size_t new_size = arr->size * 2;
532 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
533 if (!new_items_array) {
534 return 0;
535 }
536 arr->items = new_items_array;
537 arr->size = new_size;
538 }
539
540 arr->items[arr->num_items].lineno = lineno;
541 arr->items[arr->num_items].comment = comment; // Take ownership
542 arr->num_items++;
543 return 1;
544}
545
546static void
547growable_comment_array_deallocate(growable_comment_array *arr) {
548 for (unsigned i = 0; i < arr->num_items; i++) {
549 PyMem_Free(arr->items[i].comment);
550 }
551 PyMem_Free(arr->items);
552}
553
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100554int
555_PyPegen_fill_token(Parser *p)
556{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100557 const char *start;
558 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100559 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700560
561 // Record and skip '# type: ignore' comments
562 while (type == TYPE_IGNORE) {
563 Py_ssize_t len = end - start;
564 char *tag = PyMem_Malloc(len + 1);
565 if (tag == NULL) {
566 PyErr_NoMemory();
567 return -1;
568 }
569 strncpy(tag, start, len);
570 tag[len] = '\0';
571 // Ownership of tag passes to the growable array
572 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
573 PyErr_NoMemory();
574 return -1;
575 }
576 type = PyTokenizer_Get(p->tok, &start, &end);
577 }
578
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100579 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
580 type = NEWLINE; /* Add an extra newline */
581 p->parsing_started = 0;
582
Pablo Galindob94dbd72020-04-27 18:35:58 +0100583 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100584 p->tok->pendin = -p->tok->indent;
585 p->tok->indent = 0;
586 }
587 }
588 else {
589 p->parsing_started = 1;
590 }
591
592 if (p->fill == p->size) {
593 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300594 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
595 if (new_tokens == NULL) {
596 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100597 return -1;
598 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100599 p->tokens = new_tokens;
600
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100601 for (int i = p->size; i < newsize; i++) {
602 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300603 if (p->tokens[i] == NULL) {
604 p->size = i; // Needed, in order to cleanup correctly after parser fails
605 PyErr_NoMemory();
606 return -1;
607 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100608 memset(p->tokens[i], '\0', sizeof(Token));
609 }
610 p->size = newsize;
611 }
612
613 Token *t = p->tokens[p->fill];
614 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
615 t->bytes = PyBytes_FromStringAndSize(start, end - start);
616 if (t->bytes == NULL) {
617 return -1;
618 }
619 PyArena_AddPyObject(p->arena, t->bytes);
620
621 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
622 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100623 int end_lineno = p->tok->lineno;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100624 int col_offset = -1;
625 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100626 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100627 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100628 }
629 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100630 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100631 }
632
633 t->lineno = p->starting_lineno + lineno;
634 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
635 t->end_lineno = p->starting_lineno + end_lineno;
636 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
637
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100638 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300639
640 if (type == ERRORTOKEN) {
641 if (p->tok->done == E_DECODE) {
642 return raise_decode_error(p);
643 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100644 return tokenizer_error(p);
645
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300646 }
647
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100648 return 0;
649}
650
651// Instrumentation to count the effectiveness of memoization.
652// The array counts the number of tokens skipped by memoization,
653// indexed by type.
654
655#define NSTATISTICS 2000
656static long memo_statistics[NSTATISTICS];
657
658void
659_PyPegen_clear_memo_statistics()
660{
661 for (int i = 0; i < NSTATISTICS; i++) {
662 memo_statistics[i] = 0;
663 }
664}
665
666PyObject *
667_PyPegen_get_memo_statistics()
668{
669 PyObject *ret = PyList_New(NSTATISTICS);
670 if (ret == NULL) {
671 return NULL;
672 }
673 for (int i = 0; i < NSTATISTICS; i++) {
674 PyObject *value = PyLong_FromLong(memo_statistics[i]);
675 if (value == NULL) {
676 Py_DECREF(ret);
677 return NULL;
678 }
679 // PyList_SetItem borrows a reference to value.
680 if (PyList_SetItem(ret, i, value) < 0) {
681 Py_DECREF(ret);
682 return NULL;
683 }
684 }
685 return ret;
686}
687
688int // bool
689_PyPegen_is_memoized(Parser *p, int type, void *pres)
690{
691 if (p->mark == p->fill) {
692 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300693 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100694 return -1;
695 }
696 }
697
698 Token *t = p->tokens[p->mark];
699
700 for (Memo *m = t->memo; m != NULL; m = m->next) {
701 if (m->type == type) {
702 if (0 <= type && type < NSTATISTICS) {
703 long count = m->mark - p->mark;
704 // A memoized negative result counts for one.
705 if (count <= 0) {
706 count = 1;
707 }
708 memo_statistics[type] += count;
709 }
710 p->mark = m->mark;
711 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100712 return 1;
713 }
714 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100715 return 0;
716}
717
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100718int
719_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
720{
721 int mark = p->mark;
722 void *res = func(p);
723 p->mark = mark;
724 return (res != NULL) == positive;
725}
726
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100727int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300728_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
729{
730 int mark = p->mark;
731 void *res = func(p, arg);
732 p->mark = mark;
733 return (res != NULL) == positive;
734}
735
736int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100737_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
738{
739 int mark = p->mark;
740 void *res = func(p, arg);
741 p->mark = mark;
742 return (res != NULL) == positive;
743}
744
745int
746_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
747{
748 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100749 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100750 p->mark = mark;
751 return (res != NULL) == positive;
752}
753
754Token *
755_PyPegen_expect_token(Parser *p, int type)
756{
757 if (p->mark == p->fill) {
758 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300759 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100760 return NULL;
761 }
762 }
763 Token *t = p->tokens[p->mark];
764 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100765 return NULL;
766 }
767 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100768 return t;
769}
770
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300771expr_ty
772_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
773{
774 if (p->mark == p->fill) {
775 if (_PyPegen_fill_token(p) < 0) {
776 p->error_indicator = 1;
777 return NULL;
778 }
779 }
780 Token *t = p->tokens[p->mark];
781 if (t->type != NAME) {
782 return NULL;
783 }
784 char* s = PyBytes_AsString(t->bytes);
785 if (!s) {
786 p->error_indicator = 1;
787 return NULL;
788 }
789 if (strcmp(s, keyword) != 0) {
790 return NULL;
791 }
792 return _PyPegen_name_token(p);
793}
794
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100795Token *
796_PyPegen_get_last_nonnwhitespace_token(Parser *p)
797{
798 assert(p->mark >= 0);
799 Token *token = NULL;
800 for (int m = p->mark - 1; m >= 0; m--) {
801 token = p->tokens[m];
802 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
803 break;
804 }
805 }
806 return token;
807}
808
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100809expr_ty
810_PyPegen_name_token(Parser *p)
811{
812 Token *t = _PyPegen_expect_token(p, NAME);
813 if (t == NULL) {
814 return NULL;
815 }
816 char* s = PyBytes_AsString(t->bytes);
817 if (!s) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300818 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100819 return NULL;
820 }
821 PyObject *id = _PyPegen_new_identifier(p, s);
822 if (id == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300823 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100824 return NULL;
825 }
826 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
827 p->arena);
828}
829
830void *
831_PyPegen_string_token(Parser *p)
832{
833 return _PyPegen_expect_token(p, STRING);
834}
835
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100836static PyObject *
837parsenumber_raw(const char *s)
838{
839 const char *end;
840 long x;
841 double dx;
842 Py_complex compl;
843 int imflag;
844
845 assert(s != NULL);
846 errno = 0;
847 end = s + strlen(s) - 1;
848 imflag = *end == 'j' || *end == 'J';
849 if (s[0] == '0') {
850 x = (long)PyOS_strtoul(s, (char **)&end, 0);
851 if (x < 0 && errno == 0) {
852 return PyLong_FromString(s, (char **)0, 0);
853 }
854 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100855 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100856 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100857 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100858 if (*end == '\0') {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100859 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100860 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100861 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100862 return PyLong_FromLong(x);
863 }
864 /* XXX Huge floats may silently fail */
865 if (imflag) {
866 compl.real = 0.;
867 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100868 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100869 return NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100870 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100871 return PyComplex_FromCComplex(compl);
872 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100873 dx = PyOS_string_to_double(s, NULL, NULL);
874 if (dx == -1.0 && PyErr_Occurred()) {
875 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100876 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100877 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100878}
879
880static PyObject *
881parsenumber(const char *s)
882{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100883 char *dup;
884 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100885 PyObject *res = NULL;
886
887 assert(s != NULL);
888
889 if (strchr(s, '_') == NULL) {
890 return parsenumber_raw(s);
891 }
892 /* Create a duplicate without underscores. */
893 dup = PyMem_Malloc(strlen(s) + 1);
894 if (dup == NULL) {
895 return PyErr_NoMemory();
896 }
897 end = dup;
898 for (; *s; s++) {
899 if (*s != '_') {
900 *end++ = *s;
901 }
902 }
903 *end = '\0';
904 res = parsenumber_raw(dup);
905 PyMem_Free(dup);
906 return res;
907}
908
909expr_ty
910_PyPegen_number_token(Parser *p)
911{
912 Token *t = _PyPegen_expect_token(p, NUMBER);
913 if (t == NULL) {
914 return NULL;
915 }
916
917 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100918 if (num_raw == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300919 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100920 return NULL;
921 }
922
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300923 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
924 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700925 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300926 "in Python 3.6 and greater");
927 }
928
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100929 PyObject *c = parsenumber(num_raw);
930
931 if (c == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300932 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100933 return NULL;
934 }
935
936 if (PyArena_AddPyObject(p->arena, c) < 0) {
937 Py_DECREF(c);
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300938 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100939 return NULL;
940 }
941
942 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
943 p->arena);
944}
945
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300946static int // bool
947newline_in_string(Parser *p, const char *cur)
948{
Miss Islington (bot)15fec562020-06-05 17:13:14 -0700949 for (const char *c = cur; c >= p->tok->buf; c--) {
950 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300951 return 1;
952 }
953 }
954 return 0;
955}
956
957/* Check that the source for a single input statement really is a single
958 statement by looking at what is left in the buffer after parsing.
959 Trailing whitespace and comments are OK. */
960static int // bool
961bad_single_statement(Parser *p)
962{
963 const char *cur = strchr(p->tok->buf, '\n');
964
965 /* Newlines are allowed if preceded by a line continuation character
966 or if they appear inside a string. */
967 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
968 return 0;
969 }
970 char c = *cur;
971
972 for (;;) {
973 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
974 c = *++cur;
975 }
976
977 if (!c) {
978 return 0;
979 }
980
981 if (c != '#') {
982 return 1;
983 }
984
985 /* Suck up comment. */
986 while (c && c != '\n') {
987 c = *++cur;
988 }
989 }
990}
991
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100992void
993_PyPegen_Parser_Free(Parser *p)
994{
995 Py_XDECREF(p->normalize);
996 for (int i = 0; i < p->size; i++) {
997 PyMem_Free(p->tokens[i]);
998 }
999 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001000 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001001 PyMem_Free(p);
1002}
1003
Pablo Galindo2b74c832020-04-27 18:02:07 +01001004static int
1005compute_parser_flags(PyCompilerFlags *flags)
1006{
1007 int parser_flags = 0;
1008 if (!flags) {
1009 return 0;
1010 }
1011 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1012 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1013 }
1014 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1015 parser_flags |= PyPARSE_IGNORE_COOKIE;
1016 }
1017 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1018 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1019 }
1020 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1021 parser_flags |= PyPARSE_TYPE_COMMENTS;
1022 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001023 if (flags->cf_feature_version < 7) {
1024 parser_flags |= PyPARSE_ASYNC_HACKS;
1025 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001026 return parser_flags;
1027}
1028
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001029Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001030_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001031 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001032{
1033 Parser *p = PyMem_Malloc(sizeof(Parser));
1034 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001035 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001036 }
1037 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001038 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1039 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001040 p->tok = tok;
1041 p->keywords = NULL;
1042 p->n_keyword_lists = -1;
1043 p->tokens = PyMem_Malloc(sizeof(Token *));
1044 if (!p->tokens) {
1045 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001046 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001047 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001048 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001049 if (!p->tokens) {
1050 PyMem_Free(p->tokens);
1051 PyMem_Free(p);
1052 return (Parser *) PyErr_NoMemory();
1053 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001054 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1055 PyMem_Free(p->tokens[0]);
1056 PyMem_Free(p->tokens);
1057 PyMem_Free(p);
1058 return (Parser *) PyErr_NoMemory();
1059 }
1060
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001061 p->mark = 0;
1062 p->fill = 0;
1063 p->size = 1;
1064
1065 p->errcode = errcode;
1066 p->arena = arena;
1067 p->start_rule = start_rule;
1068 p->parsing_started = 0;
1069 p->normalize = NULL;
1070 p->error_indicator = 0;
1071
1072 p->starting_lineno = 0;
1073 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001074 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001075 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001076 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001077 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001078
1079 return p;
1080}
1081
1082void *
1083_PyPegen_run_parser(Parser *p)
1084{
1085 void *res = _PyPegen_parse(p);
1086 if (res == NULL) {
1087 if (PyErr_Occurred()) {
1088 return NULL;
1089 }
1090 if (p->fill == 0) {
1091 RAISE_SYNTAX_ERROR("error at start before reading any input");
1092 }
1093 else if (p->tok->done == E_EOF) {
1094 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1095 }
1096 else {
1097 if (p->tokens[p->fill-1]->type == INDENT) {
1098 RAISE_INDENTATION_ERROR("unexpected indent");
1099 }
1100 else if (p->tokens[p->fill-1]->type == DEDENT) {
1101 RAISE_INDENTATION_ERROR("unexpected unindent");
1102 }
1103 else {
1104 RAISE_SYNTAX_ERROR("invalid syntax");
1105 }
1106 }
1107 return NULL;
1108 }
1109
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001110 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1111 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1112 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1113 }
1114
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001115 return res;
1116}
1117
1118mod_ty
1119_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1120 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001121 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001122{
1123 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1124 if (tok == NULL) {
1125 if (PyErr_Occurred()) {
1126 raise_tokenizer_init_error(filename_ob);
1127 return NULL;
1128 }
1129 return NULL;
1130 }
1131 // This transfers the ownership to the tokenizer
1132 tok->filename = filename_ob;
1133 Py_INCREF(filename_ob);
1134
1135 // From here on we need to clean up even if there's an error
1136 mod_ty result = NULL;
1137
Pablo Galindo2b74c832020-04-27 18:02:07 +01001138 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001139 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1140 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001141 if (p == NULL) {
1142 goto error;
1143 }
1144
1145 result = _PyPegen_run_parser(p);
1146 _PyPegen_Parser_Free(p);
1147
1148error:
1149 PyTokenizer_Free(tok);
1150 return result;
1151}
1152
1153mod_ty
1154_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001155 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001156{
1157 FILE *fp = fopen(filename, "rb");
1158 if (fp == NULL) {
1159 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1160 return NULL;
1161 }
1162
1163 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001164 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001165
1166 fclose(fp);
1167 return result;
1168}
1169
1170mod_ty
1171_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001172 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001173{
1174 int exec_input = start_rule == Py_file_input;
1175
1176 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001177 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001178 tok = PyTokenizer_FromUTF8(str, exec_input);
1179 } else {
1180 tok = PyTokenizer_FromString(str, exec_input);
1181 }
1182 if (tok == NULL) {
1183 if (PyErr_Occurred()) {
1184 raise_tokenizer_init_error(filename_ob);
1185 }
1186 return NULL;
1187 }
1188 // This transfers the ownership to the tokenizer
1189 tok->filename = filename_ob;
1190 Py_INCREF(filename_ob);
1191
1192 // We need to clear up from here on
1193 mod_ty result = NULL;
1194
Pablo Galindo2b74c832020-04-27 18:02:07 +01001195 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001196 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001197 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1198 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001199 if (p == NULL) {
1200 goto error;
1201 }
1202
1203 result = _PyPegen_run_parser(p);
1204 _PyPegen_Parser_Free(p);
1205
1206error:
1207 PyTokenizer_Free(tok);
1208 return result;
1209}
1210
1211void *
1212_PyPegen_interactive_exit(Parser *p)
1213{
1214 if (p->errcode) {
1215 *(p->errcode) = E_EOF;
1216 }
1217 return NULL;
1218}
1219
1220/* Creates a single-element asdl_seq* that contains a */
1221asdl_seq *
1222_PyPegen_singleton_seq(Parser *p, void *a)
1223{
1224 assert(a != NULL);
1225 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1226 if (!seq) {
1227 return NULL;
1228 }
1229 asdl_seq_SET(seq, 0, a);
1230 return seq;
1231}
1232
1233/* Creates a copy of seq and prepends a to it */
1234asdl_seq *
1235_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1236{
1237 assert(a != NULL);
1238 if (!seq) {
1239 return _PyPegen_singleton_seq(p, a);
1240 }
1241
1242 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1243 if (!new_seq) {
1244 return NULL;
1245 }
1246
1247 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001248 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001249 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1250 }
1251 return new_seq;
1252}
1253
Guido van Rossumc001c092020-04-30 12:12:19 -07001254/* Creates a copy of seq and appends a to it */
1255asdl_seq *
1256_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1257{
1258 assert(a != NULL);
1259 if (!seq) {
1260 return _PyPegen_singleton_seq(p, a);
1261 }
1262
1263 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1264 if (!new_seq) {
1265 return NULL;
1266 }
1267
1268 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1269 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1270 }
1271 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1272 return new_seq;
1273}
1274
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001275static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001276_get_flattened_seq_size(asdl_seq *seqs)
1277{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001278 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001279 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1280 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1281 size += asdl_seq_LEN(inner_seq);
1282 }
1283 return size;
1284}
1285
1286/* Flattens an asdl_seq* of asdl_seq*s */
1287asdl_seq *
1288_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1289{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001290 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001291 assert(flattened_seq_size > 0);
1292
1293 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1294 if (!flattened_seq) {
1295 return NULL;
1296 }
1297
1298 int flattened_seq_idx = 0;
1299 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1300 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001301 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001302 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1303 }
1304 }
1305 assert(flattened_seq_idx == flattened_seq_size);
1306
1307 return flattened_seq;
1308}
1309
1310/* Creates a new name of the form <first_name>.<second_name> */
1311expr_ty
1312_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1313{
1314 assert(first_name != NULL && second_name != NULL);
1315 PyObject *first_identifier = first_name->v.Name.id;
1316 PyObject *second_identifier = second_name->v.Name.id;
1317
1318 if (PyUnicode_READY(first_identifier) == -1) {
1319 return NULL;
1320 }
1321 if (PyUnicode_READY(second_identifier) == -1) {
1322 return NULL;
1323 }
1324 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1325 if (!first_str) {
1326 return NULL;
1327 }
1328 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1329 if (!second_str) {
1330 return NULL;
1331 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001332 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001333
1334 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1335 if (!str) {
1336 return NULL;
1337 }
1338
1339 char *s = PyBytes_AS_STRING(str);
1340 if (!s) {
1341 return NULL;
1342 }
1343
1344 strcpy(s, first_str);
1345 s += strlen(first_str);
1346 *s++ = '.';
1347 strcpy(s, second_str);
1348 s += strlen(second_str);
1349 *s = '\0';
1350
1351 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1352 Py_DECREF(str);
1353 if (!uni) {
1354 return NULL;
1355 }
1356 PyUnicode_InternInPlace(&uni);
1357 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1358 Py_DECREF(uni);
1359 return NULL;
1360 }
1361
1362 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1363}
1364
1365/* Counts the total number of dots in seq's tokens */
1366int
1367_PyPegen_seq_count_dots(asdl_seq *seq)
1368{
1369 int number_of_dots = 0;
1370 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1371 Token *current_expr = asdl_seq_GET(seq, i);
1372 switch (current_expr->type) {
1373 case ELLIPSIS:
1374 number_of_dots += 3;
1375 break;
1376 case DOT:
1377 number_of_dots += 1;
1378 break;
1379 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001380 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001381 }
1382 }
1383
1384 return number_of_dots;
1385}
1386
1387/* Creates an alias with '*' as the identifier name */
1388alias_ty
1389_PyPegen_alias_for_star(Parser *p)
1390{
1391 PyObject *str = PyUnicode_InternFromString("*");
1392 if (!str) {
1393 return NULL;
1394 }
1395 if (PyArena_AddPyObject(p->arena, str) < 0) {
1396 Py_DECREF(str);
1397 return NULL;
1398 }
1399 return alias(str, NULL, p->arena);
1400}
1401
1402/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1403asdl_seq *
1404_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1405{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001406 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001407 assert(len > 0);
1408
1409 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1410 if (!new_seq) {
1411 return NULL;
1412 }
1413 for (Py_ssize_t i = 0; i < len; i++) {
1414 expr_ty e = asdl_seq_GET(seq, i);
1415 asdl_seq_SET(new_seq, i, e->v.Name.id);
1416 }
1417 return new_seq;
1418}
1419
1420/* Constructs a CmpopExprPair */
1421CmpopExprPair *
1422_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1423{
1424 assert(expr != NULL);
1425 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1426 if (!a) {
1427 return NULL;
1428 }
1429 a->cmpop = cmpop;
1430 a->expr = expr;
1431 return a;
1432}
1433
1434asdl_int_seq *
1435_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1436{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001437 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001438 assert(len > 0);
1439
1440 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1441 if (!new_seq) {
1442 return NULL;
1443 }
1444 for (Py_ssize_t i = 0; i < len; i++) {
1445 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1446 asdl_seq_SET(new_seq, i, pair->cmpop);
1447 }
1448 return new_seq;
1449}
1450
1451asdl_seq *
1452_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1453{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001454 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001455 assert(len > 0);
1456
1457 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1458 if (!new_seq) {
1459 return NULL;
1460 }
1461 for (Py_ssize_t i = 0; i < len; i++) {
1462 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1463 asdl_seq_SET(new_seq, i, pair->expr);
1464 }
1465 return new_seq;
1466}
1467
1468/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1469static asdl_seq *
1470_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1471{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001472 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001473 if (len == 0) {
1474 return NULL;
1475 }
1476
1477 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1478 if (!new_seq) {
1479 return NULL;
1480 }
1481 for (Py_ssize_t i = 0; i < len; i++) {
1482 expr_ty e = asdl_seq_GET(seq, i);
1483 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1484 }
1485 return new_seq;
1486}
1487
1488static expr_ty
1489_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1490{
1491 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1492}
1493
1494static expr_ty
1495_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1496{
1497 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1498}
1499
1500static expr_ty
1501_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1502{
1503 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1504}
1505
1506static expr_ty
1507_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1508{
1509 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1510}
1511
1512static expr_ty
1513_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1514{
1515 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1516}
1517
1518static expr_ty
1519_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1520{
1521 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1522}
1523
1524/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1525expr_ty
1526_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1527{
1528 assert(expr != NULL);
1529
1530 expr_ty new = NULL;
1531 switch (expr->kind) {
1532 case Name_kind:
1533 new = _set_name_context(p, expr, ctx);
1534 break;
1535 case Tuple_kind:
1536 new = _set_tuple_context(p, expr, ctx);
1537 break;
1538 case List_kind:
1539 new = _set_list_context(p, expr, ctx);
1540 break;
1541 case Subscript_kind:
1542 new = _set_subscript_context(p, expr, ctx);
1543 break;
1544 case Attribute_kind:
1545 new = _set_attribute_context(p, expr, ctx);
1546 break;
1547 case Starred_kind:
1548 new = _set_starred_context(p, expr, ctx);
1549 break;
1550 default:
1551 new = expr;
1552 }
1553 return new;
1554}
1555
1556/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1557KeyValuePair *
1558_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1559{
1560 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1561 if (!a) {
1562 return NULL;
1563 }
1564 a->key = key;
1565 a->value = value;
1566 return a;
1567}
1568
1569/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1570asdl_seq *
1571_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1572{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001573 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001574 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1575 if (!new_seq) {
1576 return NULL;
1577 }
1578 for (Py_ssize_t i = 0; i < len; i++) {
1579 KeyValuePair *pair = asdl_seq_GET(seq, i);
1580 asdl_seq_SET(new_seq, i, pair->key);
1581 }
1582 return new_seq;
1583}
1584
1585/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1586asdl_seq *
1587_PyPegen_get_values(Parser *p, asdl_seq *seq)
1588{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001589 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001590 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1591 if (!new_seq) {
1592 return NULL;
1593 }
1594 for (Py_ssize_t i = 0; i < len; i++) {
1595 KeyValuePair *pair = asdl_seq_GET(seq, i);
1596 asdl_seq_SET(new_seq, i, pair->value);
1597 }
1598 return new_seq;
1599}
1600
1601/* Constructs a NameDefaultPair */
1602NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001603_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001604{
1605 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1606 if (!a) {
1607 return NULL;
1608 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001609 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001610 a->value = value;
1611 return a;
1612}
1613
1614/* Constructs a SlashWithDefault */
1615SlashWithDefault *
1616_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1617{
1618 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1619 if (!a) {
1620 return NULL;
1621 }
1622 a->plain_names = plain_names;
1623 a->names_with_defaults = names_with_defaults;
1624 return a;
1625}
1626
1627/* Constructs a StarEtc */
1628StarEtc *
1629_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1630{
1631 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1632 if (!a) {
1633 return NULL;
1634 }
1635 a->vararg = vararg;
1636 a->kwonlyargs = kwonlyargs;
1637 a->kwarg = kwarg;
1638 return a;
1639}
1640
1641asdl_seq *
1642_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1643{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001644 Py_ssize_t first_len = asdl_seq_LEN(a);
1645 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001646 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1647 if (!new_seq) {
1648 return NULL;
1649 }
1650
1651 int k = 0;
1652 for (Py_ssize_t i = 0; i < first_len; i++) {
1653 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1654 }
1655 for (Py_ssize_t i = 0; i < second_len; i++) {
1656 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1657 }
1658
1659 return new_seq;
1660}
1661
1662static asdl_seq *
1663_get_names(Parser *p, asdl_seq *names_with_defaults)
1664{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001665 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001666 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1667 if (!seq) {
1668 return NULL;
1669 }
1670 for (Py_ssize_t i = 0; i < len; i++) {
1671 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1672 asdl_seq_SET(seq, i, pair->arg);
1673 }
1674 return seq;
1675}
1676
1677static asdl_seq *
1678_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1679{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001680 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001681 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1682 if (!seq) {
1683 return NULL;
1684 }
1685 for (Py_ssize_t i = 0; i < len; i++) {
1686 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1687 asdl_seq_SET(seq, i, pair->value);
1688 }
1689 return seq;
1690}
1691
1692/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1693arguments_ty
1694_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1695 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1696 asdl_seq *names_with_default, StarEtc *star_etc)
1697{
1698 asdl_seq *posonlyargs;
1699 if (slash_without_default != NULL) {
1700 posonlyargs = slash_without_default;
1701 }
1702 else if (slash_with_default != NULL) {
1703 asdl_seq *slash_with_default_names =
1704 _get_names(p, slash_with_default->names_with_defaults);
1705 if (!slash_with_default_names) {
1706 return NULL;
1707 }
1708 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1709 if (!posonlyargs) {
1710 return NULL;
1711 }
1712 }
1713 else {
1714 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1715 if (!posonlyargs) {
1716 return NULL;
1717 }
1718 }
1719
1720 asdl_seq *posargs;
1721 if (plain_names != NULL && names_with_default != NULL) {
1722 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1723 if (!names_with_default_names) {
1724 return NULL;
1725 }
1726 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1727 if (!posargs) {
1728 return NULL;
1729 }
1730 }
1731 else if (plain_names == NULL && names_with_default != NULL) {
1732 posargs = _get_names(p, names_with_default);
1733 if (!posargs) {
1734 return NULL;
1735 }
1736 }
1737 else if (plain_names != NULL && names_with_default == NULL) {
1738 posargs = plain_names;
1739 }
1740 else {
1741 posargs = _Py_asdl_seq_new(0, p->arena);
1742 if (!posargs) {
1743 return NULL;
1744 }
1745 }
1746
1747 asdl_seq *posdefaults;
1748 if (slash_with_default != NULL && names_with_default != NULL) {
1749 asdl_seq *slash_with_default_values =
1750 _get_defaults(p, slash_with_default->names_with_defaults);
1751 if (!slash_with_default_values) {
1752 return NULL;
1753 }
1754 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1755 if (!names_with_default_values) {
1756 return NULL;
1757 }
1758 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1759 if (!posdefaults) {
1760 return NULL;
1761 }
1762 }
1763 else if (slash_with_default == NULL && names_with_default != NULL) {
1764 posdefaults = _get_defaults(p, names_with_default);
1765 if (!posdefaults) {
1766 return NULL;
1767 }
1768 }
1769 else if (slash_with_default != NULL && names_with_default == NULL) {
1770 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1771 if (!posdefaults) {
1772 return NULL;
1773 }
1774 }
1775 else {
1776 posdefaults = _Py_asdl_seq_new(0, p->arena);
1777 if (!posdefaults) {
1778 return NULL;
1779 }
1780 }
1781
1782 arg_ty vararg = NULL;
1783 if (star_etc != NULL && star_etc->vararg != NULL) {
1784 vararg = star_etc->vararg;
1785 }
1786
1787 asdl_seq *kwonlyargs;
1788 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1789 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1790 if (!kwonlyargs) {
1791 return NULL;
1792 }
1793 }
1794 else {
1795 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1796 if (!kwonlyargs) {
1797 return NULL;
1798 }
1799 }
1800
1801 asdl_seq *kwdefaults;
1802 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1803 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1804 if (!kwdefaults) {
1805 return NULL;
1806 }
1807 }
1808 else {
1809 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1810 if (!kwdefaults) {
1811 return NULL;
1812 }
1813 }
1814
1815 arg_ty kwarg = NULL;
1816 if (star_etc != NULL && star_etc->kwarg != NULL) {
1817 kwarg = star_etc->kwarg;
1818 }
1819
1820 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1821 posdefaults, p->arena);
1822}
1823
1824/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1825 * arguments. */
1826arguments_ty
1827_PyPegen_empty_arguments(Parser *p)
1828{
1829 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1830 if (!posonlyargs) {
1831 return NULL;
1832 }
1833 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1834 if (!posargs) {
1835 return NULL;
1836 }
1837 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1838 if (!posdefaults) {
1839 return NULL;
1840 }
1841 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1842 if (!kwonlyargs) {
1843 return NULL;
1844 }
1845 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1846 if (!kwdefaults) {
1847 return NULL;
1848 }
1849
1850 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1851 p->arena);
1852}
1853
1854/* Encapsulates the value of an operator_ty into an AugOperator struct */
1855AugOperator *
1856_PyPegen_augoperator(Parser *p, operator_ty kind)
1857{
1858 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1859 if (!a) {
1860 return NULL;
1861 }
1862 a->kind = kind;
1863 return a;
1864}
1865
1866/* Construct a FunctionDef equivalent to function_def, but with decorators */
1867stmt_ty
1868_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1869{
1870 assert(function_def != NULL);
1871 if (function_def->kind == AsyncFunctionDef_kind) {
1872 return _Py_AsyncFunctionDef(
1873 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1874 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1875 function_def->v.FunctionDef.type_comment, function_def->lineno,
1876 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1877 p->arena);
1878 }
1879
1880 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1881 function_def->v.FunctionDef.body, decorators,
1882 function_def->v.FunctionDef.returns,
1883 function_def->v.FunctionDef.type_comment, function_def->lineno,
1884 function_def->col_offset, function_def->end_lineno,
1885 function_def->end_col_offset, p->arena);
1886}
1887
1888/* Construct a ClassDef equivalent to class_def, but with decorators */
1889stmt_ty
1890_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1891{
1892 assert(class_def != NULL);
1893 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1894 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1895 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1896 class_def->end_col_offset, p->arena);
1897}
1898
1899/* Construct a KeywordOrStarred */
1900KeywordOrStarred *
1901_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1902{
1903 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1904 if (!a) {
1905 return NULL;
1906 }
1907 a->element = element;
1908 a->is_keyword = is_keyword;
1909 return a;
1910}
1911
1912/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1913static int
1914_seq_number_of_starred_exprs(asdl_seq *seq)
1915{
1916 int n = 0;
1917 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1918 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1919 if (!k->is_keyword) {
1920 n++;
1921 }
1922 }
1923 return n;
1924}
1925
1926/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1927asdl_seq *
1928_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1929{
1930 int new_len = _seq_number_of_starred_exprs(kwargs);
1931 if (new_len == 0) {
1932 return NULL;
1933 }
1934 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1935 if (!new_seq) {
1936 return NULL;
1937 }
1938
1939 int idx = 0;
1940 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1941 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1942 if (!k->is_keyword) {
1943 asdl_seq_SET(new_seq, idx++, k->element);
1944 }
1945 }
1946 return new_seq;
1947}
1948
1949/* Return a new asdl_seq* with only the keywords in kwargs */
1950asdl_seq *
1951_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1952{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001953 Py_ssize_t len = asdl_seq_LEN(kwargs);
1954 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001955 if (new_len == 0) {
1956 return NULL;
1957 }
1958 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1959 if (!new_seq) {
1960 return NULL;
1961 }
1962
1963 int idx = 0;
1964 for (Py_ssize_t i = 0; i < len; i++) {
1965 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1966 if (k->is_keyword) {
1967 asdl_seq_SET(new_seq, idx++, k->element);
1968 }
1969 }
1970 return new_seq;
1971}
1972
1973expr_ty
1974_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1975{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001976 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001977 assert(len > 0);
1978
1979 Token *first = asdl_seq_GET(strings, 0);
1980 Token *last = asdl_seq_GET(strings, len - 1);
1981
1982 int bytesmode = 0;
1983 PyObject *bytes_str = NULL;
1984
1985 FstringParser state;
1986 _PyPegen_FstringParser_Init(&state);
1987
1988 for (Py_ssize_t i = 0; i < len; i++) {
1989 Token *t = asdl_seq_GET(strings, i);
1990
1991 int this_bytesmode;
1992 int this_rawmode;
1993 PyObject *s;
1994 const char *fstr;
1995 Py_ssize_t fstrlen = -1;
1996
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001997 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001998 goto error;
1999 }
2000
2001 /* Check that we are not mixing bytes with unicode. */
2002 if (i != 0 && bytesmode != this_bytesmode) {
2003 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2004 Py_XDECREF(s);
2005 goto error;
2006 }
2007 bytesmode = this_bytesmode;
2008
2009 if (fstr != NULL) {
2010 assert(s == NULL && !bytesmode);
2011
2012 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2013 this_rawmode, 0, first, t, last);
2014 if (result < 0) {
2015 goto error;
2016 }
2017 }
2018 else {
2019 /* String or byte string. */
2020 assert(s != NULL && fstr == NULL);
2021 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2022
2023 if (bytesmode) {
2024 if (i == 0) {
2025 bytes_str = s;
2026 }
2027 else {
2028 PyBytes_ConcatAndDel(&bytes_str, s);
2029 if (!bytes_str) {
2030 goto error;
2031 }
2032 }
2033 }
2034 else {
2035 /* This is a regular string. Concatenate it. */
2036 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2037 goto error;
2038 }
2039 }
2040 }
2041 }
2042
2043 if (bytesmode) {
2044 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2045 goto error;
2046 }
2047 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2048 last->end_col_offset, p->arena);
2049 }
2050
2051 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2052
2053error:
2054 Py_XDECREF(bytes_str);
2055 _PyPegen_FstringParser_Dealloc(&state);
2056 if (PyErr_Occurred()) {
2057 raise_decode_error(p);
2058 }
2059 return NULL;
2060}
Guido van Rossumc001c092020-04-30 12:12:19 -07002061
2062mod_ty
2063_PyPegen_make_module(Parser *p, asdl_seq *a) {
2064 asdl_seq *type_ignores = NULL;
2065 Py_ssize_t num = p->type_ignore_comments.num_items;
2066 if (num > 0) {
2067 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2068 type_ignores = _Py_asdl_seq_new(num, p->arena);
2069 if (type_ignores == NULL) {
2070 return NULL;
2071 }
2072 for (int i = 0; i < num; i++) {
2073 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2074 if (tag == NULL) {
2075 return NULL;
2076 }
2077 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2078 if (ti == NULL) {
2079 return NULL;
2080 }
2081 asdl_seq_SET(type_ignores, i, ti);
2082 }
2083 }
2084 return Module(a, type_ignores, p->arena);
2085}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002086
2087// Error reporting helpers
2088
2089expr_ty
2090_PyPegen_get_invalid_target(expr_ty e)
2091{
2092 if (e == NULL) {
2093 return NULL;
2094 }
2095
2096#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2097 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2098 for (Py_ssize_t i = 0; i < len; i++) {\
2099 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2100 expr_ty child = _PyPegen_get_invalid_target(other);\
2101 if (child != NULL) {\
2102 return child;\
2103 }\
2104 }\
2105 } while (0)
2106
2107 // We only need to visit List and Tuple nodes recursively as those
2108 // are the only ones that can contain valid names in targets when
2109 // they are parsed as expressions. Any other kind of expression
2110 // that is a container (like Sets or Dicts) is directly invalid and
2111 // we don't need to visit it recursively.
2112
2113 switch (e->kind) {
2114 case List_kind: {
2115 VISIT_CONTAINER(e, List);
2116 return NULL;
2117 }
2118 case Tuple_kind: {
2119 VISIT_CONTAINER(e, Tuple);
2120 return NULL;
2121 }
2122 case Starred_kind:
2123 return _PyPegen_get_invalid_target(e->v.Starred.value);
2124 case Name_kind:
2125 case Subscript_kind:
2126 case Attribute_kind:
2127 return NULL;
2128 default:
2129 return e;
2130 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002131}
2132
2133void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2134 int kwarg_unpacking = 0;
2135 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2136 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2137 if (!keyword->arg) {
2138 kwarg_unpacking = 1;
2139 }
2140 }
2141
2142 const char *msg = NULL;
2143 if (kwarg_unpacking) {
2144 msg = "positional argument follows keyword argument unpacking";
2145 } else {
2146 msg = "positional argument follows keyword argument";
2147 }
2148
2149 return RAISE_SYNTAX_ERROR(msg);
2150}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002151
2152void *
2153_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2154{
2155 /* The rule that calls this function is 'args for_if_clauses'.
2156 For the input f(L, x for x in y), L and x are in args and
2157 the for is parsed as a for_if_clause. We have to check if
2158 len <= 1, so that input like dict((a, b) for a, b in x)
2159 gets successfully parsed and then we pass the last
2160 argument (x in the above example) as the location of the
2161 error */
2162 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2163 if (len <= 1) {
2164 return NULL;
2165 }
2166
2167 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2168 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2169 "Generator expression must be parenthesized"
2170 );
2171}