blob: e63e5a8aed719e3244e6052451228c40afaa4d6b [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
3#include "../tokenizer.h"
4
5#include "pegen.h"
6#include "parse_string.h"
7
Guido van Rossumc001c092020-04-30 12:12:19 -07008PyObject *
9_PyPegen_new_type_comment(Parser *p, char *s)
10{
11 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
12 if (res == NULL) {
13 return NULL;
14 }
15 if (PyArena_AddPyObject(p->arena, res) < 0) {
16 Py_DECREF(res);
17 return NULL;
18 }
19 return res;
20}
21
22arg_ty
23_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
24{
25 if (tc == NULL) {
26 return a;
27 }
28 char *bytes = PyBytes_AsString(tc->bytes);
29 if (bytes == NULL) {
30 return NULL;
31 }
32 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
33 if (tco == NULL) {
34 return NULL;
35 }
36 return arg(a->arg, a->annotation, tco,
37 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
38 p->arena);
39}
40
Pablo Galindoc5fc1562020-04-22 23:29:27 +010041static int
42init_normalization(Parser *p)
43{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030044 if (p->normalize) {
45 return 1;
46 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010047 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
48 if (!m)
49 {
50 return 0;
51 }
52 p->normalize = PyObject_GetAttrString(m, "normalize");
53 Py_DECREF(m);
54 if (!p->normalize)
55 {
56 return 0;
57 }
58 return 1;
59}
60
Pablo Galindo2b74c832020-04-27 18:02:07 +010061/* Checks if the NOTEQUAL token is valid given the current parser flags
620 indicates success and nonzero indicates failure (an exception may be set) */
63int
64_PyPegen_check_barry_as_flufl(Parser *p) {
65 Token *t = p->tokens[p->fill - 1];
66 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindo30b59fd2020-06-15 15:08:00 +010070 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010071 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
Pablo Galindo30b59fd2020-06-15 15:08:00 +010073 }
74 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010075 return strcmp(tok_str, "!=");
76 }
77 return 0;
78}
79
Pablo Galindoc5fc1562020-04-22 23:29:27 +010080PyObject *
81_PyPegen_new_identifier(Parser *p, char *n)
82{
83 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
84 if (!id) {
85 goto error;
86 }
87 /* PyUnicode_DecodeUTF8 should always return a ready string. */
88 assert(PyUnicode_IS_READY(id));
89 /* Check whether there are non-ASCII characters in the
90 identifier; if so, normalize to NFKC. */
91 if (!PyUnicode_IS_ASCII(id))
92 {
93 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030094 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010095 {
96 Py_DECREF(id);
97 goto error;
98 }
99 PyObject *form = PyUnicode_InternFromString("NFKC");
100 if (form == NULL)
101 {
102 Py_DECREF(id);
103 goto error;
104 }
105 PyObject *args[2] = {form, id};
106 id2 = _PyObject_FastCall(p->normalize, args, 2);
107 Py_DECREF(id);
108 Py_DECREF(form);
109 if (!id2) {
110 goto error;
111 }
112 if (!PyUnicode_Check(id2))
113 {
114 PyErr_Format(PyExc_TypeError,
115 "unicodedata.normalize() must return a string, not "
116 "%.200s",
117 _PyType_Name(Py_TYPE(id2)));
118 Py_DECREF(id2);
119 goto error;
120 }
121 id = id2;
122 }
123 PyUnicode_InternInPlace(&id);
124 if (PyArena_AddPyObject(p->arena, id) < 0)
125 {
126 Py_DECREF(id);
127 goto error;
128 }
129 return id;
130
131error:
132 p->error_indicator = 1;
133 return NULL;
134}
135
136static PyObject *
137_create_dummy_identifier(Parser *p)
138{
139 return _PyPegen_new_identifier(p, "");
140}
141
142static inline Py_ssize_t
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700143byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100144{
145 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300146 if (!str) {
147 return 0;
148 }
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700149 assert(col_offset >= 0 && (unsigned long)col_offset <= strlen(str));
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300150 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100151 if (!text) {
152 return 0;
153 }
154 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
155 Py_DECREF(text);
156 return size;
157}
158
159const char *
160_PyPegen_get_expr_name(expr_ty e)
161{
Miss Islington (bot)8df4f392020-06-08 02:22:06 -0700162 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100163 switch (e->kind) {
164 case Attribute_kind:
165 return "attribute";
166 case Subscript_kind:
167 return "subscript";
168 case Starred_kind:
169 return "starred";
170 case Name_kind:
171 return "name";
172 case List_kind:
173 return "list";
174 case Tuple_kind:
175 return "tuple";
176 case Lambda_kind:
177 return "lambda";
178 case Call_kind:
179 return "function call";
180 case BoolOp_kind:
181 case BinOp_kind:
182 case UnaryOp_kind:
183 return "operator";
184 case GeneratorExp_kind:
185 return "generator expression";
186 case Yield_kind:
187 case YieldFrom_kind:
188 return "yield expression";
189 case Await_kind:
190 return "await expression";
191 case ListComp_kind:
192 return "list comprehension";
193 case SetComp_kind:
194 return "set comprehension";
195 case DictComp_kind:
196 return "dict comprehension";
197 case Dict_kind:
198 return "dict display";
199 case Set_kind:
200 return "set display";
201 case JoinedStr_kind:
202 case FormattedValue_kind:
203 return "f-string expression";
204 case Constant_kind: {
205 PyObject *value = e->v.Constant.value;
206 if (value == Py_None) {
207 return "None";
208 }
209 if (value == Py_False) {
210 return "False";
211 }
212 if (value == Py_True) {
213 return "True";
214 }
215 if (value == Py_Ellipsis) {
216 return "Ellipsis";
217 }
218 return "literal";
219 }
220 case Compare_kind:
221 return "comparison";
222 case IfExp_kind:
223 return "conditional expression";
224 case NamedExpr_kind:
225 return "named expression";
226 default:
227 PyErr_Format(PyExc_SystemError,
228 "unexpected expression in assignment %d (line %d)",
229 e->kind, e->lineno);
230 return NULL;
231 }
232}
233
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300234static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100235raise_decode_error(Parser *p)
236{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300237 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100238 const char *errtype = NULL;
239 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
240 errtype = "unicode error";
241 }
242 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
243 errtype = "value error";
244 }
245 if (errtype) {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100246 PyObject *type;
247 PyObject *value;
248 PyObject *tback;
249 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100250 PyErr_Fetch(&type, &value, &tback);
251 errstr = PyObject_Str(value);
252 if (errstr) {
253 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
254 Py_DECREF(errstr);
255 }
256 else {
257 PyErr_Clear();
258 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
259 }
260 Py_XDECREF(type);
261 Py_XDECREF(value);
262 Py_XDECREF(tback);
263 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300264
265 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100266}
267
268static void
269raise_tokenizer_init_error(PyObject *filename)
270{
271 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
272 || PyErr_ExceptionMatches(PyExc_ValueError)
273 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
274 return;
275 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300276 PyObject *errstr = NULL;
277 PyObject *tuple = NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100278 PyObject *type;
279 PyObject *value;
280 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100281 PyErr_Fetch(&type, &value, &tback);
282 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300283 if (!errstr) {
284 goto error;
285 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100286
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300287 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100288 if (!tmp) {
289 goto error;
290 }
291
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300292 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100293 Py_DECREF(tmp);
294 if (!value) {
295 goto error;
296 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300297 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100298
299error:
300 Py_XDECREF(type);
301 Py_XDECREF(value);
302 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300303 Py_XDECREF(errstr);
304 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100305}
306
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100307static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308tokenizer_error(Parser *p)
309{
310 if (PyErr_Occurred()) {
311 return -1;
312 }
313
314 const char *msg = NULL;
315 PyObject* errtype = PyExc_SyntaxError;
316 switch (p->tok->done) {
317 case E_TOKEN:
318 msg = "invalid token";
319 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300321 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
322 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100323 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300324 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
325 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300326 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300327 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
328 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100329 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300330 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
331 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332 case E_INTR:
333 if (!PyErr_Occurred()) {
334 PyErr_SetNone(PyExc_KeyboardInterrupt);
335 }
336 return -1;
337 case E_NOMEM:
338 PyErr_NoMemory();
339 return -1;
340 case E_TABSPACE:
341 errtype = PyExc_TabError;
342 msg = "inconsistent use of tabs and spaces in indentation";
343 break;
344 case E_TOODEEP:
345 errtype = PyExc_IndentationError;
346 msg = "too many levels of indentation";
347 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100348 case E_LINECONT:
349 msg = "unexpected character after line continuation character";
350 break;
351 default:
352 msg = "unknown parsing error";
353 }
354
355 PyErr_Format(errtype, msg);
356 // There is no reliable column information for this error
357 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
358
359 return -1;
360}
361
362void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300363_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
364{
365 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700366 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300367 if (t->col_offset == -1) {
368 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
369 intptr_t, int);
370 } else {
371 col_offset = t->col_offset + 1;
372 }
373
374 va_list va;
375 va_start(va, errmsg);
376 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
377 col_offset, errmsg, va);
378 va_end(va);
379
380 return NULL;
381}
382
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300383void *
384_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700385 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300386 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100387{
388 PyObject *value = NULL;
389 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300390 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300392 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100393
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100394 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100395 if (!errstr) {
396 goto error;
397 }
398
399 if (p->start_rule == Py_file_input) {
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300400 error_line = PyErr_ProgramTextObject(p->tok->filename, lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100401 }
402
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300403 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100404 Py_ssize_t size = p->tok->inp - p->tok->buf;
Pablo Galindobcc30362020-05-14 21:11:48 +0100405 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300406 if (!error_line) {
407 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300408 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100409 }
410
Miss Islington (bot)7795ae82020-06-16 10:36:59 -0700411 Py_ssize_t col_number = col_offset;
412
413 if (p->tok->encoding != NULL) {
414 col_number = byte_offset_to_character_offset(error_line, col_offset);
415 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300416
417 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100418 if (!tmp) {
419 goto error;
420 }
421 value = PyTuple_Pack(2, errstr, tmp);
422 Py_DECREF(tmp);
423 if (!value) {
424 goto error;
425 }
426 PyErr_SetObject(errtype, value);
427
428 Py_DECREF(errstr);
429 Py_DECREF(value);
430 return NULL;
431
432error:
433 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300434 Py_XDECREF(error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100435 return NULL;
436}
437
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100438#if 0
439static const char *
440token_name(int type)
441{
442 if (0 <= type && type <= N_TOKENS) {
443 return _PyParser_TokenNames[type];
444 }
445 return "<Huh?>";
446}
447#endif
448
449// Here, mark is the start of the node, while p->mark is the end.
450// If node==NULL, they should be the same.
451int
452_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
453{
454 // Insert in front
455 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
456 if (m == NULL) {
457 return -1;
458 }
459 m->type = type;
460 m->node = node;
461 m->mark = p->mark;
462 m->next = p->tokens[mark]->memo;
463 p->tokens[mark]->memo = m;
464 return 0;
465}
466
467// Like _PyPegen_insert_memo(), but updates an existing node if found.
468int
469_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
470{
471 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
472 if (m->type == type) {
473 // Update existing node.
474 m->node = node;
475 m->mark = p->mark;
476 return 0;
477 }
478 }
479 // Insert new node.
480 return _PyPegen_insert_memo(p, mark, type, node);
481}
482
483// Return dummy NAME.
484void *
485_PyPegen_dummy_name(Parser *p, ...)
486{
487 static void *cache = NULL;
488
489 if (cache != NULL) {
490 return cache;
491 }
492
493 PyObject *id = _create_dummy_identifier(p);
494 if (!id) {
495 return NULL;
496 }
497 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
498 return cache;
499}
500
501static int
502_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
503{
504 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
505 return NAME;
506 }
507 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
508 if (strncmp(k->str, name, name_len) == 0) {
509 return k->type;
510 }
511 }
512 return NAME;
513}
514
Guido van Rossumc001c092020-04-30 12:12:19 -0700515static int
516growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
517 assert(initial_size > 0);
518 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
519 arr->size = initial_size;
520 arr->num_items = 0;
521
522 return arr->items != NULL;
523}
524
525static int
526growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
527 if (arr->num_items >= arr->size) {
528 size_t new_size = arr->size * 2;
529 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
530 if (!new_items_array) {
531 return 0;
532 }
533 arr->items = new_items_array;
534 arr->size = new_size;
535 }
536
537 arr->items[arr->num_items].lineno = lineno;
538 arr->items[arr->num_items].comment = comment; // Take ownership
539 arr->num_items++;
540 return 1;
541}
542
543static void
544growable_comment_array_deallocate(growable_comment_array *arr) {
545 for (unsigned i = 0; i < arr->num_items; i++) {
546 PyMem_Free(arr->items[i].comment);
547 }
548 PyMem_Free(arr->items);
549}
550
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100551int
552_PyPegen_fill_token(Parser *p)
553{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100554 const char *start;
555 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100556 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700557
558 // Record and skip '# type: ignore' comments
559 while (type == TYPE_IGNORE) {
560 Py_ssize_t len = end - start;
561 char *tag = PyMem_Malloc(len + 1);
562 if (tag == NULL) {
563 PyErr_NoMemory();
564 return -1;
565 }
566 strncpy(tag, start, len);
567 tag[len] = '\0';
568 // Ownership of tag passes to the growable array
569 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
570 PyErr_NoMemory();
571 return -1;
572 }
573 type = PyTokenizer_Get(p->tok, &start, &end);
574 }
575
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100576 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
577 type = NEWLINE; /* Add an extra newline */
578 p->parsing_started = 0;
579
Pablo Galindob94dbd72020-04-27 18:35:58 +0100580 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100581 p->tok->pendin = -p->tok->indent;
582 p->tok->indent = 0;
583 }
584 }
585 else {
586 p->parsing_started = 1;
587 }
588
589 if (p->fill == p->size) {
590 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300591 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
592 if (new_tokens == NULL) {
593 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100594 return -1;
595 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100596 p->tokens = new_tokens;
597
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100598 for (int i = p->size; i < newsize; i++) {
599 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300600 if (p->tokens[i] == NULL) {
601 p->size = i; // Needed, in order to cleanup correctly after parser fails
602 PyErr_NoMemory();
603 return -1;
604 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100605 memset(p->tokens[i], '\0', sizeof(Token));
606 }
607 p->size = newsize;
608 }
609
610 Token *t = p->tokens[p->fill];
611 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
612 t->bytes = PyBytes_FromStringAndSize(start, end - start);
613 if (t->bytes == NULL) {
614 return -1;
615 }
616 PyArena_AddPyObject(p->arena, t->bytes);
617
618 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
619 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100620 int end_lineno = p->tok->lineno;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100621 int col_offset = -1;
622 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100623 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100624 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100625 }
626 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100627 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100628 }
629
630 t->lineno = p->starting_lineno + lineno;
631 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
632 t->end_lineno = p->starting_lineno + end_lineno;
633 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
634
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100635 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300636
637 if (type == ERRORTOKEN) {
638 if (p->tok->done == E_DECODE) {
639 return raise_decode_error(p);
640 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100641 return tokenizer_error(p);
642
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300643 }
644
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100645 return 0;
646}
647
648// Instrumentation to count the effectiveness of memoization.
649// The array counts the number of tokens skipped by memoization,
650// indexed by type.
651
652#define NSTATISTICS 2000
653static long memo_statistics[NSTATISTICS];
654
655void
656_PyPegen_clear_memo_statistics()
657{
658 for (int i = 0; i < NSTATISTICS; i++) {
659 memo_statistics[i] = 0;
660 }
661}
662
663PyObject *
664_PyPegen_get_memo_statistics()
665{
666 PyObject *ret = PyList_New(NSTATISTICS);
667 if (ret == NULL) {
668 return NULL;
669 }
670 for (int i = 0; i < NSTATISTICS; i++) {
671 PyObject *value = PyLong_FromLong(memo_statistics[i]);
672 if (value == NULL) {
673 Py_DECREF(ret);
674 return NULL;
675 }
676 // PyList_SetItem borrows a reference to value.
677 if (PyList_SetItem(ret, i, value) < 0) {
678 Py_DECREF(ret);
679 return NULL;
680 }
681 }
682 return ret;
683}
684
685int // bool
686_PyPegen_is_memoized(Parser *p, int type, void *pres)
687{
688 if (p->mark == p->fill) {
689 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300690 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100691 return -1;
692 }
693 }
694
695 Token *t = p->tokens[p->mark];
696
697 for (Memo *m = t->memo; m != NULL; m = m->next) {
698 if (m->type == type) {
699 if (0 <= type && type < NSTATISTICS) {
700 long count = m->mark - p->mark;
701 // A memoized negative result counts for one.
702 if (count <= 0) {
703 count = 1;
704 }
705 memo_statistics[type] += count;
706 }
707 p->mark = m->mark;
708 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100709 return 1;
710 }
711 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100712 return 0;
713}
714
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100715int
716_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
717{
718 int mark = p->mark;
719 void *res = func(p);
720 p->mark = mark;
721 return (res != NULL) == positive;
722}
723
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100724int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300725_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
726{
727 int mark = p->mark;
728 void *res = func(p, arg);
729 p->mark = mark;
730 return (res != NULL) == positive;
731}
732
733int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100734_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
735{
736 int mark = p->mark;
737 void *res = func(p, arg);
738 p->mark = mark;
739 return (res != NULL) == positive;
740}
741
742int
743_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
744{
745 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100746 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100747 p->mark = mark;
748 return (res != NULL) == positive;
749}
750
751Token *
752_PyPegen_expect_token(Parser *p, int type)
753{
754 if (p->mark == p->fill) {
755 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300756 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100757 return NULL;
758 }
759 }
760 Token *t = p->tokens[p->mark];
761 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100762 return NULL;
763 }
764 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100765 return t;
766}
767
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300768expr_ty
769_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
770{
771 if (p->mark == p->fill) {
772 if (_PyPegen_fill_token(p) < 0) {
773 p->error_indicator = 1;
774 return NULL;
775 }
776 }
777 Token *t = p->tokens[p->mark];
778 if (t->type != NAME) {
779 return NULL;
780 }
781 char* s = PyBytes_AsString(t->bytes);
782 if (!s) {
783 p->error_indicator = 1;
784 return NULL;
785 }
786 if (strcmp(s, keyword) != 0) {
787 return NULL;
788 }
789 return _PyPegen_name_token(p);
790}
791
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100792Token *
793_PyPegen_get_last_nonnwhitespace_token(Parser *p)
794{
795 assert(p->mark >= 0);
796 Token *token = NULL;
797 for (int m = p->mark - 1; m >= 0; m--) {
798 token = p->tokens[m];
799 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
800 break;
801 }
802 }
803 return token;
804}
805
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100806expr_ty
807_PyPegen_name_token(Parser *p)
808{
809 Token *t = _PyPegen_expect_token(p, NAME);
810 if (t == NULL) {
811 return NULL;
812 }
813 char* s = PyBytes_AsString(t->bytes);
814 if (!s) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300815 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100816 return NULL;
817 }
818 PyObject *id = _PyPegen_new_identifier(p, s);
819 if (id == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300820 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100821 return NULL;
822 }
823 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
824 p->arena);
825}
826
827void *
828_PyPegen_string_token(Parser *p)
829{
830 return _PyPegen_expect_token(p, STRING);
831}
832
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100833static PyObject *
834parsenumber_raw(const char *s)
835{
836 const char *end;
837 long x;
838 double dx;
839 Py_complex compl;
840 int imflag;
841
842 assert(s != NULL);
843 errno = 0;
844 end = s + strlen(s) - 1;
845 imflag = *end == 'j' || *end == 'J';
846 if (s[0] == '0') {
847 x = (long)PyOS_strtoul(s, (char **)&end, 0);
848 if (x < 0 && errno == 0) {
849 return PyLong_FromString(s, (char **)0, 0);
850 }
851 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100852 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100853 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100854 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100855 if (*end == '\0') {
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100856 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100857 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100858 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100859 return PyLong_FromLong(x);
860 }
861 /* XXX Huge floats may silently fail */
862 if (imflag) {
863 compl.real = 0.;
864 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100865 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100866 return NULL;
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100867 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100868 return PyComplex_FromCComplex(compl);
869 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100870 dx = PyOS_string_to_double(s, NULL, NULL);
871 if (dx == -1.0 && PyErr_Occurred()) {
872 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100873 }
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100874 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100875}
876
877static PyObject *
878parsenumber(const char *s)
879{
Pablo Galindo30b59fd2020-06-15 15:08:00 +0100880 char *dup;
881 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100882 PyObject *res = NULL;
883
884 assert(s != NULL);
885
886 if (strchr(s, '_') == NULL) {
887 return parsenumber_raw(s);
888 }
889 /* Create a duplicate without underscores. */
890 dup = PyMem_Malloc(strlen(s) + 1);
891 if (dup == NULL) {
892 return PyErr_NoMemory();
893 }
894 end = dup;
895 for (; *s; s++) {
896 if (*s != '_') {
897 *end++ = *s;
898 }
899 }
900 *end = '\0';
901 res = parsenumber_raw(dup);
902 PyMem_Free(dup);
903 return res;
904}
905
906expr_ty
907_PyPegen_number_token(Parser *p)
908{
909 Token *t = _PyPegen_expect_token(p, NUMBER);
910 if (t == NULL) {
911 return NULL;
912 }
913
914 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100915 if (num_raw == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300916 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100917 return NULL;
918 }
919
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300920 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
921 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700922 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300923 "in Python 3.6 and greater");
924 }
925
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100926 PyObject *c = parsenumber(num_raw);
927
928 if (c == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300929 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100930 return NULL;
931 }
932
933 if (PyArena_AddPyObject(p->arena, c) < 0) {
934 Py_DECREF(c);
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300935 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100936 return NULL;
937 }
938
939 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
940 p->arena);
941}
942
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300943static int // bool
944newline_in_string(Parser *p, const char *cur)
945{
Miss Islington (bot)15fec562020-06-05 17:13:14 -0700946 for (const char *c = cur; c >= p->tok->buf; c--) {
947 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300948 return 1;
949 }
950 }
951 return 0;
952}
953
954/* Check that the source for a single input statement really is a single
955 statement by looking at what is left in the buffer after parsing.
956 Trailing whitespace and comments are OK. */
957static int // bool
958bad_single_statement(Parser *p)
959{
960 const char *cur = strchr(p->tok->buf, '\n');
961
962 /* Newlines are allowed if preceded by a line continuation character
963 or if they appear inside a string. */
964 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
965 return 0;
966 }
967 char c = *cur;
968
969 for (;;) {
970 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
971 c = *++cur;
972 }
973
974 if (!c) {
975 return 0;
976 }
977
978 if (c != '#') {
979 return 1;
980 }
981
982 /* Suck up comment. */
983 while (c && c != '\n') {
984 c = *++cur;
985 }
986 }
987}
988
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100989void
990_PyPegen_Parser_Free(Parser *p)
991{
992 Py_XDECREF(p->normalize);
993 for (int i = 0; i < p->size; i++) {
994 PyMem_Free(p->tokens[i]);
995 }
996 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700997 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100998 PyMem_Free(p);
999}
1000
Pablo Galindo2b74c832020-04-27 18:02:07 +01001001static int
1002compute_parser_flags(PyCompilerFlags *flags)
1003{
1004 int parser_flags = 0;
1005 if (!flags) {
1006 return 0;
1007 }
1008 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1009 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1010 }
1011 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1012 parser_flags |= PyPARSE_IGNORE_COOKIE;
1013 }
1014 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1015 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1016 }
1017 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1018 parser_flags |= PyPARSE_TYPE_COMMENTS;
1019 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001020 if (flags->cf_feature_version < 7) {
1021 parser_flags |= PyPARSE_ASYNC_HACKS;
1022 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001023 return parser_flags;
1024}
1025
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001026Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001027_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001028 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001029{
1030 Parser *p = PyMem_Malloc(sizeof(Parser));
1031 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001032 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001033 }
1034 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001035 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1036 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001037 p->tok = tok;
1038 p->keywords = NULL;
1039 p->n_keyword_lists = -1;
1040 p->tokens = PyMem_Malloc(sizeof(Token *));
1041 if (!p->tokens) {
1042 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001043 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001044 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001045 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001046 if (!p->tokens) {
1047 PyMem_Free(p->tokens);
1048 PyMem_Free(p);
1049 return (Parser *) PyErr_NoMemory();
1050 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001051 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1052 PyMem_Free(p->tokens[0]);
1053 PyMem_Free(p->tokens);
1054 PyMem_Free(p);
1055 return (Parser *) PyErr_NoMemory();
1056 }
1057
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001058 p->mark = 0;
1059 p->fill = 0;
1060 p->size = 1;
1061
1062 p->errcode = errcode;
1063 p->arena = arena;
1064 p->start_rule = start_rule;
1065 p->parsing_started = 0;
1066 p->normalize = NULL;
1067 p->error_indicator = 0;
1068
1069 p->starting_lineno = 0;
1070 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001071 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001072 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001073 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001074 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001075
1076 return p;
1077}
1078
1079void *
1080_PyPegen_run_parser(Parser *p)
1081{
1082 void *res = _PyPegen_parse(p);
1083 if (res == NULL) {
1084 if (PyErr_Occurred()) {
1085 return NULL;
1086 }
1087 if (p->fill == 0) {
1088 RAISE_SYNTAX_ERROR("error at start before reading any input");
1089 }
1090 else if (p->tok->done == E_EOF) {
1091 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1092 }
1093 else {
1094 if (p->tokens[p->fill-1]->type == INDENT) {
1095 RAISE_INDENTATION_ERROR("unexpected indent");
1096 }
1097 else if (p->tokens[p->fill-1]->type == DEDENT) {
1098 RAISE_INDENTATION_ERROR("unexpected unindent");
1099 }
1100 else {
1101 RAISE_SYNTAX_ERROR("invalid syntax");
1102 }
1103 }
1104 return NULL;
1105 }
1106
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001107 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1108 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1109 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1110 }
1111
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001112 return res;
1113}
1114
1115mod_ty
1116_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1117 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001118 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001119{
1120 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1121 if (tok == NULL) {
1122 if (PyErr_Occurred()) {
1123 raise_tokenizer_init_error(filename_ob);
1124 return NULL;
1125 }
1126 return NULL;
1127 }
1128 // This transfers the ownership to the tokenizer
1129 tok->filename = filename_ob;
1130 Py_INCREF(filename_ob);
1131
1132 // From here on we need to clean up even if there's an error
1133 mod_ty result = NULL;
1134
Pablo Galindo2b74c832020-04-27 18:02:07 +01001135 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001136 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1137 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001138 if (p == NULL) {
1139 goto error;
1140 }
1141
1142 result = _PyPegen_run_parser(p);
1143 _PyPegen_Parser_Free(p);
1144
1145error:
1146 PyTokenizer_Free(tok);
1147 return result;
1148}
1149
1150mod_ty
1151_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001152 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001153{
1154 FILE *fp = fopen(filename, "rb");
1155 if (fp == NULL) {
1156 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1157 return NULL;
1158 }
1159
1160 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001161 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001162
1163 fclose(fp);
1164 return result;
1165}
1166
1167mod_ty
1168_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001169 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001170{
1171 int exec_input = start_rule == Py_file_input;
1172
1173 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001174 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001175 tok = PyTokenizer_FromUTF8(str, exec_input);
1176 } else {
1177 tok = PyTokenizer_FromString(str, exec_input);
1178 }
1179 if (tok == NULL) {
1180 if (PyErr_Occurred()) {
1181 raise_tokenizer_init_error(filename_ob);
1182 }
1183 return NULL;
1184 }
1185 // This transfers the ownership to the tokenizer
1186 tok->filename = filename_ob;
1187 Py_INCREF(filename_ob);
1188
1189 // We need to clear up from here on
1190 mod_ty result = NULL;
1191
Pablo Galindo2b74c832020-04-27 18:02:07 +01001192 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001193 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001194 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1195 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001196 if (p == NULL) {
1197 goto error;
1198 }
1199
1200 result = _PyPegen_run_parser(p);
1201 _PyPegen_Parser_Free(p);
1202
1203error:
1204 PyTokenizer_Free(tok);
1205 return result;
1206}
1207
1208void *
1209_PyPegen_interactive_exit(Parser *p)
1210{
1211 if (p->errcode) {
1212 *(p->errcode) = E_EOF;
1213 }
1214 return NULL;
1215}
1216
1217/* Creates a single-element asdl_seq* that contains a */
1218asdl_seq *
1219_PyPegen_singleton_seq(Parser *p, void *a)
1220{
1221 assert(a != NULL);
1222 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1223 if (!seq) {
1224 return NULL;
1225 }
1226 asdl_seq_SET(seq, 0, a);
1227 return seq;
1228}
1229
1230/* Creates a copy of seq and prepends a to it */
1231asdl_seq *
1232_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1233{
1234 assert(a != NULL);
1235 if (!seq) {
1236 return _PyPegen_singleton_seq(p, a);
1237 }
1238
1239 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1240 if (!new_seq) {
1241 return NULL;
1242 }
1243
1244 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001245 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001246 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1247 }
1248 return new_seq;
1249}
1250
Guido van Rossumc001c092020-04-30 12:12:19 -07001251/* Creates a copy of seq and appends a to it */
1252asdl_seq *
1253_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1254{
1255 assert(a != NULL);
1256 if (!seq) {
1257 return _PyPegen_singleton_seq(p, a);
1258 }
1259
1260 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1261 if (!new_seq) {
1262 return NULL;
1263 }
1264
1265 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1266 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1267 }
1268 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1269 return new_seq;
1270}
1271
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001272static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001273_get_flattened_seq_size(asdl_seq *seqs)
1274{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001275 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001276 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1277 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1278 size += asdl_seq_LEN(inner_seq);
1279 }
1280 return size;
1281}
1282
1283/* Flattens an asdl_seq* of asdl_seq*s */
1284asdl_seq *
1285_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1286{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001287 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001288 assert(flattened_seq_size > 0);
1289
1290 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1291 if (!flattened_seq) {
1292 return NULL;
1293 }
1294
1295 int flattened_seq_idx = 0;
1296 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1297 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001298 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001299 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1300 }
1301 }
1302 assert(flattened_seq_idx == flattened_seq_size);
1303
1304 return flattened_seq;
1305}
1306
1307/* Creates a new name of the form <first_name>.<second_name> */
1308expr_ty
1309_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1310{
1311 assert(first_name != NULL && second_name != NULL);
1312 PyObject *first_identifier = first_name->v.Name.id;
1313 PyObject *second_identifier = second_name->v.Name.id;
1314
1315 if (PyUnicode_READY(first_identifier) == -1) {
1316 return NULL;
1317 }
1318 if (PyUnicode_READY(second_identifier) == -1) {
1319 return NULL;
1320 }
1321 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1322 if (!first_str) {
1323 return NULL;
1324 }
1325 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1326 if (!second_str) {
1327 return NULL;
1328 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001329 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001330
1331 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1332 if (!str) {
1333 return NULL;
1334 }
1335
1336 char *s = PyBytes_AS_STRING(str);
1337 if (!s) {
1338 return NULL;
1339 }
1340
1341 strcpy(s, first_str);
1342 s += strlen(first_str);
1343 *s++ = '.';
1344 strcpy(s, second_str);
1345 s += strlen(second_str);
1346 *s = '\0';
1347
1348 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1349 Py_DECREF(str);
1350 if (!uni) {
1351 return NULL;
1352 }
1353 PyUnicode_InternInPlace(&uni);
1354 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1355 Py_DECREF(uni);
1356 return NULL;
1357 }
1358
1359 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1360}
1361
1362/* Counts the total number of dots in seq's tokens */
1363int
1364_PyPegen_seq_count_dots(asdl_seq *seq)
1365{
1366 int number_of_dots = 0;
1367 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1368 Token *current_expr = asdl_seq_GET(seq, i);
1369 switch (current_expr->type) {
1370 case ELLIPSIS:
1371 number_of_dots += 3;
1372 break;
1373 case DOT:
1374 number_of_dots += 1;
1375 break;
1376 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001377 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001378 }
1379 }
1380
1381 return number_of_dots;
1382}
1383
1384/* Creates an alias with '*' as the identifier name */
1385alias_ty
1386_PyPegen_alias_for_star(Parser *p)
1387{
1388 PyObject *str = PyUnicode_InternFromString("*");
1389 if (!str) {
1390 return NULL;
1391 }
1392 if (PyArena_AddPyObject(p->arena, str) < 0) {
1393 Py_DECREF(str);
1394 return NULL;
1395 }
1396 return alias(str, NULL, p->arena);
1397}
1398
1399/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1400asdl_seq *
1401_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1402{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001403 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001404 assert(len > 0);
1405
1406 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1407 if (!new_seq) {
1408 return NULL;
1409 }
1410 for (Py_ssize_t i = 0; i < len; i++) {
1411 expr_ty e = asdl_seq_GET(seq, i);
1412 asdl_seq_SET(new_seq, i, e->v.Name.id);
1413 }
1414 return new_seq;
1415}
1416
1417/* Constructs a CmpopExprPair */
1418CmpopExprPair *
1419_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1420{
1421 assert(expr != NULL);
1422 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1423 if (!a) {
1424 return NULL;
1425 }
1426 a->cmpop = cmpop;
1427 a->expr = expr;
1428 return a;
1429}
1430
1431asdl_int_seq *
1432_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1433{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001434 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001435 assert(len > 0);
1436
1437 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1438 if (!new_seq) {
1439 return NULL;
1440 }
1441 for (Py_ssize_t i = 0; i < len; i++) {
1442 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1443 asdl_seq_SET(new_seq, i, pair->cmpop);
1444 }
1445 return new_seq;
1446}
1447
1448asdl_seq *
1449_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1450{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001451 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001452 assert(len > 0);
1453
1454 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1455 if (!new_seq) {
1456 return NULL;
1457 }
1458 for (Py_ssize_t i = 0; i < len; i++) {
1459 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1460 asdl_seq_SET(new_seq, i, pair->expr);
1461 }
1462 return new_seq;
1463}
1464
1465/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1466static asdl_seq *
1467_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1468{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001469 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001470 if (len == 0) {
1471 return NULL;
1472 }
1473
1474 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1475 if (!new_seq) {
1476 return NULL;
1477 }
1478 for (Py_ssize_t i = 0; i < len; i++) {
1479 expr_ty e = asdl_seq_GET(seq, i);
1480 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1481 }
1482 return new_seq;
1483}
1484
1485static expr_ty
1486_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1487{
1488 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1489}
1490
1491static expr_ty
1492_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1493{
1494 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1495}
1496
1497static expr_ty
1498_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1499{
1500 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1501}
1502
1503static expr_ty
1504_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1505{
1506 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1507}
1508
1509static expr_ty
1510_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1511{
1512 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1513}
1514
1515static expr_ty
1516_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1517{
1518 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1519}
1520
1521/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1522expr_ty
1523_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1524{
1525 assert(expr != NULL);
1526
1527 expr_ty new = NULL;
1528 switch (expr->kind) {
1529 case Name_kind:
1530 new = _set_name_context(p, expr, ctx);
1531 break;
1532 case Tuple_kind:
1533 new = _set_tuple_context(p, expr, ctx);
1534 break;
1535 case List_kind:
1536 new = _set_list_context(p, expr, ctx);
1537 break;
1538 case Subscript_kind:
1539 new = _set_subscript_context(p, expr, ctx);
1540 break;
1541 case Attribute_kind:
1542 new = _set_attribute_context(p, expr, ctx);
1543 break;
1544 case Starred_kind:
1545 new = _set_starred_context(p, expr, ctx);
1546 break;
1547 default:
1548 new = expr;
1549 }
1550 return new;
1551}
1552
1553/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1554KeyValuePair *
1555_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1556{
1557 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1558 if (!a) {
1559 return NULL;
1560 }
1561 a->key = key;
1562 a->value = value;
1563 return a;
1564}
1565
1566/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1567asdl_seq *
1568_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1569{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001570 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001571 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1572 if (!new_seq) {
1573 return NULL;
1574 }
1575 for (Py_ssize_t i = 0; i < len; i++) {
1576 KeyValuePair *pair = asdl_seq_GET(seq, i);
1577 asdl_seq_SET(new_seq, i, pair->key);
1578 }
1579 return new_seq;
1580}
1581
1582/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1583asdl_seq *
1584_PyPegen_get_values(Parser *p, asdl_seq *seq)
1585{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001586 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001587 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1588 if (!new_seq) {
1589 return NULL;
1590 }
1591 for (Py_ssize_t i = 0; i < len; i++) {
1592 KeyValuePair *pair = asdl_seq_GET(seq, i);
1593 asdl_seq_SET(new_seq, i, pair->value);
1594 }
1595 return new_seq;
1596}
1597
1598/* Constructs a NameDefaultPair */
1599NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001600_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001601{
1602 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1603 if (!a) {
1604 return NULL;
1605 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001606 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001607 a->value = value;
1608 return a;
1609}
1610
1611/* Constructs a SlashWithDefault */
1612SlashWithDefault *
1613_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1614{
1615 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1616 if (!a) {
1617 return NULL;
1618 }
1619 a->plain_names = plain_names;
1620 a->names_with_defaults = names_with_defaults;
1621 return a;
1622}
1623
1624/* Constructs a StarEtc */
1625StarEtc *
1626_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1627{
1628 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1629 if (!a) {
1630 return NULL;
1631 }
1632 a->vararg = vararg;
1633 a->kwonlyargs = kwonlyargs;
1634 a->kwarg = kwarg;
1635 return a;
1636}
1637
1638asdl_seq *
1639_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1640{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001641 Py_ssize_t first_len = asdl_seq_LEN(a);
1642 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001643 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1644 if (!new_seq) {
1645 return NULL;
1646 }
1647
1648 int k = 0;
1649 for (Py_ssize_t i = 0; i < first_len; i++) {
1650 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1651 }
1652 for (Py_ssize_t i = 0; i < second_len; i++) {
1653 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1654 }
1655
1656 return new_seq;
1657}
1658
1659static asdl_seq *
1660_get_names(Parser *p, asdl_seq *names_with_defaults)
1661{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001662 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001663 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1664 if (!seq) {
1665 return NULL;
1666 }
1667 for (Py_ssize_t i = 0; i < len; i++) {
1668 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1669 asdl_seq_SET(seq, i, pair->arg);
1670 }
1671 return seq;
1672}
1673
1674static asdl_seq *
1675_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1676{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001677 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001678 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1679 if (!seq) {
1680 return NULL;
1681 }
1682 for (Py_ssize_t i = 0; i < len; i++) {
1683 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1684 asdl_seq_SET(seq, i, pair->value);
1685 }
1686 return seq;
1687}
1688
1689/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1690arguments_ty
1691_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1692 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1693 asdl_seq *names_with_default, StarEtc *star_etc)
1694{
1695 asdl_seq *posonlyargs;
1696 if (slash_without_default != NULL) {
1697 posonlyargs = slash_without_default;
1698 }
1699 else if (slash_with_default != NULL) {
1700 asdl_seq *slash_with_default_names =
1701 _get_names(p, slash_with_default->names_with_defaults);
1702 if (!slash_with_default_names) {
1703 return NULL;
1704 }
1705 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1706 if (!posonlyargs) {
1707 return NULL;
1708 }
1709 }
1710 else {
1711 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1712 if (!posonlyargs) {
1713 return NULL;
1714 }
1715 }
1716
1717 asdl_seq *posargs;
1718 if (plain_names != NULL && names_with_default != NULL) {
1719 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1720 if (!names_with_default_names) {
1721 return NULL;
1722 }
1723 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1724 if (!posargs) {
1725 return NULL;
1726 }
1727 }
1728 else if (plain_names == NULL && names_with_default != NULL) {
1729 posargs = _get_names(p, names_with_default);
1730 if (!posargs) {
1731 return NULL;
1732 }
1733 }
1734 else if (plain_names != NULL && names_with_default == NULL) {
1735 posargs = plain_names;
1736 }
1737 else {
1738 posargs = _Py_asdl_seq_new(0, p->arena);
1739 if (!posargs) {
1740 return NULL;
1741 }
1742 }
1743
1744 asdl_seq *posdefaults;
1745 if (slash_with_default != NULL && names_with_default != NULL) {
1746 asdl_seq *slash_with_default_values =
1747 _get_defaults(p, slash_with_default->names_with_defaults);
1748 if (!slash_with_default_values) {
1749 return NULL;
1750 }
1751 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1752 if (!names_with_default_values) {
1753 return NULL;
1754 }
1755 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1756 if (!posdefaults) {
1757 return NULL;
1758 }
1759 }
1760 else if (slash_with_default == NULL && names_with_default != NULL) {
1761 posdefaults = _get_defaults(p, names_with_default);
1762 if (!posdefaults) {
1763 return NULL;
1764 }
1765 }
1766 else if (slash_with_default != NULL && names_with_default == NULL) {
1767 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1768 if (!posdefaults) {
1769 return NULL;
1770 }
1771 }
1772 else {
1773 posdefaults = _Py_asdl_seq_new(0, p->arena);
1774 if (!posdefaults) {
1775 return NULL;
1776 }
1777 }
1778
1779 arg_ty vararg = NULL;
1780 if (star_etc != NULL && star_etc->vararg != NULL) {
1781 vararg = star_etc->vararg;
1782 }
1783
1784 asdl_seq *kwonlyargs;
1785 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1786 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1787 if (!kwonlyargs) {
1788 return NULL;
1789 }
1790 }
1791 else {
1792 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1793 if (!kwonlyargs) {
1794 return NULL;
1795 }
1796 }
1797
1798 asdl_seq *kwdefaults;
1799 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1800 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1801 if (!kwdefaults) {
1802 return NULL;
1803 }
1804 }
1805 else {
1806 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1807 if (!kwdefaults) {
1808 return NULL;
1809 }
1810 }
1811
1812 arg_ty kwarg = NULL;
1813 if (star_etc != NULL && star_etc->kwarg != NULL) {
1814 kwarg = star_etc->kwarg;
1815 }
1816
1817 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1818 posdefaults, p->arena);
1819}
1820
1821/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1822 * arguments. */
1823arguments_ty
1824_PyPegen_empty_arguments(Parser *p)
1825{
1826 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1827 if (!posonlyargs) {
1828 return NULL;
1829 }
1830 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1831 if (!posargs) {
1832 return NULL;
1833 }
1834 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1835 if (!posdefaults) {
1836 return NULL;
1837 }
1838 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1839 if (!kwonlyargs) {
1840 return NULL;
1841 }
1842 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1843 if (!kwdefaults) {
1844 return NULL;
1845 }
1846
1847 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1848 p->arena);
1849}
1850
1851/* Encapsulates the value of an operator_ty into an AugOperator struct */
1852AugOperator *
1853_PyPegen_augoperator(Parser *p, operator_ty kind)
1854{
1855 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1856 if (!a) {
1857 return NULL;
1858 }
1859 a->kind = kind;
1860 return a;
1861}
1862
1863/* Construct a FunctionDef equivalent to function_def, but with decorators */
1864stmt_ty
1865_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1866{
1867 assert(function_def != NULL);
1868 if (function_def->kind == AsyncFunctionDef_kind) {
1869 return _Py_AsyncFunctionDef(
1870 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1871 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1872 function_def->v.FunctionDef.type_comment, function_def->lineno,
1873 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1874 p->arena);
1875 }
1876
1877 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1878 function_def->v.FunctionDef.body, decorators,
1879 function_def->v.FunctionDef.returns,
1880 function_def->v.FunctionDef.type_comment, function_def->lineno,
1881 function_def->col_offset, function_def->end_lineno,
1882 function_def->end_col_offset, p->arena);
1883}
1884
1885/* Construct a ClassDef equivalent to class_def, but with decorators */
1886stmt_ty
1887_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1888{
1889 assert(class_def != NULL);
1890 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1891 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1892 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1893 class_def->end_col_offset, p->arena);
1894}
1895
1896/* Construct a KeywordOrStarred */
1897KeywordOrStarred *
1898_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1899{
1900 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1901 if (!a) {
1902 return NULL;
1903 }
1904 a->element = element;
1905 a->is_keyword = is_keyword;
1906 return a;
1907}
1908
1909/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1910static int
1911_seq_number_of_starred_exprs(asdl_seq *seq)
1912{
1913 int n = 0;
1914 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1915 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1916 if (!k->is_keyword) {
1917 n++;
1918 }
1919 }
1920 return n;
1921}
1922
1923/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1924asdl_seq *
1925_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1926{
1927 int new_len = _seq_number_of_starred_exprs(kwargs);
1928 if (new_len == 0) {
1929 return NULL;
1930 }
1931 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1932 if (!new_seq) {
1933 return NULL;
1934 }
1935
1936 int idx = 0;
1937 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1938 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1939 if (!k->is_keyword) {
1940 asdl_seq_SET(new_seq, idx++, k->element);
1941 }
1942 }
1943 return new_seq;
1944}
1945
1946/* Return a new asdl_seq* with only the keywords in kwargs */
1947asdl_seq *
1948_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1949{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001950 Py_ssize_t len = asdl_seq_LEN(kwargs);
1951 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001952 if (new_len == 0) {
1953 return NULL;
1954 }
1955 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1956 if (!new_seq) {
1957 return NULL;
1958 }
1959
1960 int idx = 0;
1961 for (Py_ssize_t i = 0; i < len; i++) {
1962 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1963 if (k->is_keyword) {
1964 asdl_seq_SET(new_seq, idx++, k->element);
1965 }
1966 }
1967 return new_seq;
1968}
1969
1970expr_ty
1971_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1972{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001973 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001974 assert(len > 0);
1975
1976 Token *first = asdl_seq_GET(strings, 0);
1977 Token *last = asdl_seq_GET(strings, len - 1);
1978
1979 int bytesmode = 0;
1980 PyObject *bytes_str = NULL;
1981
1982 FstringParser state;
1983 _PyPegen_FstringParser_Init(&state);
1984
1985 for (Py_ssize_t i = 0; i < len; i++) {
1986 Token *t = asdl_seq_GET(strings, i);
1987
1988 int this_bytesmode;
1989 int this_rawmode;
1990 PyObject *s;
1991 const char *fstr;
1992 Py_ssize_t fstrlen = -1;
1993
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001994 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001995 goto error;
1996 }
1997
1998 /* Check that we are not mixing bytes with unicode. */
1999 if (i != 0 && bytesmode != this_bytesmode) {
2000 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2001 Py_XDECREF(s);
2002 goto error;
2003 }
2004 bytesmode = this_bytesmode;
2005
2006 if (fstr != NULL) {
2007 assert(s == NULL && !bytesmode);
2008
2009 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2010 this_rawmode, 0, first, t, last);
2011 if (result < 0) {
2012 goto error;
2013 }
2014 }
2015 else {
2016 /* String or byte string. */
2017 assert(s != NULL && fstr == NULL);
2018 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2019
2020 if (bytesmode) {
2021 if (i == 0) {
2022 bytes_str = s;
2023 }
2024 else {
2025 PyBytes_ConcatAndDel(&bytes_str, s);
2026 if (!bytes_str) {
2027 goto error;
2028 }
2029 }
2030 }
2031 else {
2032 /* This is a regular string. Concatenate it. */
2033 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2034 goto error;
2035 }
2036 }
2037 }
2038 }
2039
2040 if (bytesmode) {
2041 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2042 goto error;
2043 }
2044 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2045 last->end_col_offset, p->arena);
2046 }
2047
2048 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2049
2050error:
2051 Py_XDECREF(bytes_str);
2052 _PyPegen_FstringParser_Dealloc(&state);
2053 if (PyErr_Occurred()) {
2054 raise_decode_error(p);
2055 }
2056 return NULL;
2057}
Guido van Rossumc001c092020-04-30 12:12:19 -07002058
2059mod_ty
2060_PyPegen_make_module(Parser *p, asdl_seq *a) {
2061 asdl_seq *type_ignores = NULL;
2062 Py_ssize_t num = p->type_ignore_comments.num_items;
2063 if (num > 0) {
2064 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2065 type_ignores = _Py_asdl_seq_new(num, p->arena);
2066 if (type_ignores == NULL) {
2067 return NULL;
2068 }
2069 for (int i = 0; i < num; i++) {
2070 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2071 if (tag == NULL) {
2072 return NULL;
2073 }
2074 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2075 if (ti == NULL) {
2076 return NULL;
2077 }
2078 asdl_seq_SET(type_ignores, i, ti);
2079 }
2080 }
2081 return Module(a, type_ignores, p->arena);
2082}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002083
2084// Error reporting helpers
2085
2086expr_ty
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002087_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002088{
2089 if (e == NULL) {
2090 return NULL;
2091 }
2092
2093#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2094 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2095 for (Py_ssize_t i = 0; i < len; i++) {\
2096 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002097 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002098 if (child != NULL) {\
2099 return child;\
2100 }\
2101 }\
2102 } while (0)
2103
2104 // We only need to visit List and Tuple nodes recursively as those
2105 // are the only ones that can contain valid names in targets when
2106 // they are parsed as expressions. Any other kind of expression
2107 // that is a container (like Sets or Dicts) is directly invalid and
2108 // we don't need to visit it recursively.
2109
2110 switch (e->kind) {
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002111 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002112 VISIT_CONTAINER(e, List);
2113 return NULL;
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002114 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002115 VISIT_CONTAINER(e, Tuple);
2116 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002117 case Starred_kind:
Lysandros Nikolaoua5442b22020-06-19 03:03:58 +03002118 if (targets_type == DEL_TARGETS) {
2119 return e;
2120 }
2121 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2122 case Compare_kind:
2123 // This is needed, because the `a in b` in `for a in b` gets parsed
2124 // as a comparison, and so we need to search the left side of the comparison
2125 // for invalid targets.
2126 if (targets_type == FOR_TARGETS) {
2127 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2128 if (cmpop == In) {
2129 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2130 }
2131 return NULL;
2132 }
2133 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002134 case Name_kind:
2135 case Subscript_kind:
2136 case Attribute_kind:
2137 return NULL;
2138 default:
2139 return e;
2140 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002141}
2142
2143void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2144 int kwarg_unpacking = 0;
2145 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2146 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2147 if (!keyword->arg) {
2148 kwarg_unpacking = 1;
2149 }
2150 }
2151
2152 const char *msg = NULL;
2153 if (kwarg_unpacking) {
2154 msg = "positional argument follows keyword argument unpacking";
2155 } else {
2156 msg = "positional argument follows keyword argument";
2157 }
2158
2159 return RAISE_SYNTAX_ERROR(msg);
2160}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002161
2162void *
2163_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2164{
2165 /* The rule that calls this function is 'args for_if_clauses'.
2166 For the input f(L, x for x in y), L and x are in args and
2167 the for is parsed as a for_if_clause. We have to check if
2168 len <= 1, so that input like dict((a, b) for a, b in x)
2169 gets successfully parsed and then we pass the last
2170 argument (x in the above example) as the location of the
2171 error */
2172 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2173 if (len <= 1) {
2174 return NULL;
2175 }
2176
2177 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2178 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2179 "Generator expression must be parenthesized"
2180 );
2181}