blob: 594754cee5d5380d38e3ae0a59f7b0fdd21bb206 [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01003#include "tokenizer.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004
5#include "pegen.h"
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01006#include "string_parser.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01007
Guido van Rossumc001c092020-04-30 12:12:19 -07008PyObject *
9_PyPegen_new_type_comment(Parser *p, char *s)
10{
11 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
12 if (res == NULL) {
13 return NULL;
14 }
15 if (PyArena_AddPyObject(p->arena, res) < 0) {
16 Py_DECREF(res);
17 return NULL;
18 }
19 return res;
20}
21
22arg_ty
23_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
24{
25 if (tc == NULL) {
26 return a;
27 }
28 char *bytes = PyBytes_AsString(tc->bytes);
29 if (bytes == NULL) {
30 return NULL;
31 }
32 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
33 if (tco == NULL) {
34 return NULL;
35 }
36 return arg(a->arg, a->annotation, tco,
37 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
38 p->arena);
39}
40
Pablo Galindoc5fc1562020-04-22 23:29:27 +010041static int
42init_normalization(Parser *p)
43{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030044 if (p->normalize) {
45 return 1;
46 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010047 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
48 if (!m)
49 {
50 return 0;
51 }
52 p->normalize = PyObject_GetAttrString(m, "normalize");
53 Py_DECREF(m);
54 if (!p->normalize)
55 {
56 return 0;
57 }
58 return 1;
59}
60
Pablo Galindo2b74c832020-04-27 18:02:07 +010061/* Checks if the NOTEQUAL token is valid given the current parser flags
620 indicates success and nonzero indicates failure (an exception may be set) */
63int
64_PyPegen_check_barry_as_flufl(Parser *p) {
65 Token *t = p->tokens[p->fill - 1];
66 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindofb61c422020-06-15 14:23:43 +010070 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010071 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
Pablo Galindofb61c422020-06-15 14:23:43 +010073 }
74 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010075 return strcmp(tok_str, "!=");
76 }
77 return 0;
78}
79
Pablo Galindoc5fc1562020-04-22 23:29:27 +010080PyObject *
81_PyPegen_new_identifier(Parser *p, char *n)
82{
83 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
84 if (!id) {
85 goto error;
86 }
87 /* PyUnicode_DecodeUTF8 should always return a ready string. */
88 assert(PyUnicode_IS_READY(id));
89 /* Check whether there are non-ASCII characters in the
90 identifier; if so, normalize to NFKC. */
91 if (!PyUnicode_IS_ASCII(id))
92 {
93 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030094 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010095 {
96 Py_DECREF(id);
97 goto error;
98 }
99 PyObject *form = PyUnicode_InternFromString("NFKC");
100 if (form == NULL)
101 {
102 Py_DECREF(id);
103 goto error;
104 }
105 PyObject *args[2] = {form, id};
106 id2 = _PyObject_FastCall(p->normalize, args, 2);
107 Py_DECREF(id);
108 Py_DECREF(form);
109 if (!id2) {
110 goto error;
111 }
112 if (!PyUnicode_Check(id2))
113 {
114 PyErr_Format(PyExc_TypeError,
115 "unicodedata.normalize() must return a string, not "
116 "%.200s",
117 _PyType_Name(Py_TYPE(id2)));
118 Py_DECREF(id2);
119 goto error;
120 }
121 id = id2;
122 }
123 PyUnicode_InternInPlace(&id);
124 if (PyArena_AddPyObject(p->arena, id) < 0)
125 {
126 Py_DECREF(id);
127 goto error;
128 }
129 return id;
130
131error:
132 p->error_indicator = 1;
133 return NULL;
134}
135
136static PyObject *
137_create_dummy_identifier(Parser *p)
138{
139 return _PyPegen_new_identifier(p, "");
140}
141
142static inline Py_ssize_t
Pablo Galindo51c58962020-06-16 16:49:43 +0100143byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100144{
145 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300146 if (!str) {
147 return 0;
148 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100149 assert(col_offset >= 0 && (unsigned long)col_offset <= strlen(str));
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300150 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100151 if (!text) {
152 return 0;
153 }
154 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
155 Py_DECREF(text);
156 return size;
157}
158
159const char *
160_PyPegen_get_expr_name(expr_ty e)
161{
Pablo Galindo9f495902020-06-08 02:57:00 +0100162 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100163 switch (e->kind) {
164 case Attribute_kind:
165 return "attribute";
166 case Subscript_kind:
167 return "subscript";
168 case Starred_kind:
169 return "starred";
170 case Name_kind:
171 return "name";
172 case List_kind:
173 return "list";
174 case Tuple_kind:
175 return "tuple";
176 case Lambda_kind:
177 return "lambda";
178 case Call_kind:
179 return "function call";
180 case BoolOp_kind:
181 case BinOp_kind:
182 case UnaryOp_kind:
183 return "operator";
184 case GeneratorExp_kind:
185 return "generator expression";
186 case Yield_kind:
187 case YieldFrom_kind:
188 return "yield expression";
189 case Await_kind:
190 return "await expression";
191 case ListComp_kind:
192 return "list comprehension";
193 case SetComp_kind:
194 return "set comprehension";
195 case DictComp_kind:
196 return "dict comprehension";
197 case Dict_kind:
198 return "dict display";
199 case Set_kind:
200 return "set display";
201 case JoinedStr_kind:
202 case FormattedValue_kind:
203 return "f-string expression";
204 case Constant_kind: {
205 PyObject *value = e->v.Constant.value;
206 if (value == Py_None) {
207 return "None";
208 }
209 if (value == Py_False) {
210 return "False";
211 }
212 if (value == Py_True) {
213 return "True";
214 }
215 if (value == Py_Ellipsis) {
216 return "Ellipsis";
217 }
218 return "literal";
219 }
220 case Compare_kind:
221 return "comparison";
222 case IfExp_kind:
223 return "conditional expression";
224 case NamedExpr_kind:
225 return "named expression";
226 default:
227 PyErr_Format(PyExc_SystemError,
228 "unexpected expression in assignment %d (line %d)",
229 e->kind, e->lineno);
230 return NULL;
231 }
232}
233
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300234static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100235raise_decode_error(Parser *p)
236{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300237 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100238 const char *errtype = NULL;
239 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
240 errtype = "unicode error";
241 }
242 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
243 errtype = "value error";
244 }
245 if (errtype) {
Pablo Galindofb61c422020-06-15 14:23:43 +0100246 PyObject *type;
247 PyObject *value;
248 PyObject *tback;
249 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100250 PyErr_Fetch(&type, &value, &tback);
251 errstr = PyObject_Str(value);
252 if (errstr) {
253 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
254 Py_DECREF(errstr);
255 }
256 else {
257 PyErr_Clear();
258 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
259 }
260 Py_XDECREF(type);
261 Py_XDECREF(value);
262 Py_XDECREF(tback);
263 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300264
265 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100266}
267
268static void
269raise_tokenizer_init_error(PyObject *filename)
270{
271 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
272 || PyErr_ExceptionMatches(PyExc_ValueError)
273 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
274 return;
275 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300276 PyObject *errstr = NULL;
277 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100278 PyObject *type;
279 PyObject *value;
280 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100281 PyErr_Fetch(&type, &value, &tback);
282 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300283 if (!errstr) {
284 goto error;
285 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100286
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300287 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100288 if (!tmp) {
289 goto error;
290 }
291
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300292 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100293 Py_DECREF(tmp);
294 if (!value) {
295 goto error;
296 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300297 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100298
299error:
300 Py_XDECREF(type);
301 Py_XDECREF(value);
302 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300303 Py_XDECREF(errstr);
304 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100305}
306
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100307static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308tokenizer_error(Parser *p)
309{
310 if (PyErr_Occurred()) {
311 return -1;
312 }
313
314 const char *msg = NULL;
315 PyObject* errtype = PyExc_SyntaxError;
316 switch (p->tok->done) {
317 case E_TOKEN:
318 msg = "invalid token";
319 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300321 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
322 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100323 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300324 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
325 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300326 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300327 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
328 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100329 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300330 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
331 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332 case E_INTR:
333 if (!PyErr_Occurred()) {
334 PyErr_SetNone(PyExc_KeyboardInterrupt);
335 }
336 return -1;
337 case E_NOMEM:
338 PyErr_NoMemory();
339 return -1;
340 case E_TABSPACE:
341 errtype = PyExc_TabError;
342 msg = "inconsistent use of tabs and spaces in indentation";
343 break;
344 case E_TOODEEP:
345 errtype = PyExc_IndentationError;
346 msg = "too many levels of indentation";
347 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100348 case E_LINECONT:
349 msg = "unexpected character after line continuation character";
350 break;
351 default:
352 msg = "unknown parsing error";
353 }
354
355 PyErr_Format(errtype, msg);
356 // There is no reliable column information for this error
357 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
358
359 return -1;
360}
361
362void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300363_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
364{
365 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100366 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300367 if (t->col_offset == -1) {
368 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
369 intptr_t, int);
370 } else {
371 col_offset = t->col_offset + 1;
372 }
373
374 va_list va;
375 va_start(va, errmsg);
376 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
377 col_offset, errmsg, va);
378 va_end(va);
379
380 return NULL;
381}
382
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300383void *
384_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100385 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300386 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100387{
388 PyObject *value = NULL;
389 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300390 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300392 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100393
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 Nikolaou861efc62020-06-20 15:57:27 +0300400 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) 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
Pablo Galindo51c58962020-06-16 16:49:43 +0100411 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 Galindofb61c422020-06-15 14:23:43 +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 Galindofb61c422020-06-15 14:23:43 +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 Galindofb61c422020-06-15 14:23:43 +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 Galindofb61c422020-06-15 14:23:43 +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 +0100715
716int
717_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
718{
719 int mark = p->mark;
720 void *res = func(p);
721 p->mark = mark;
722 return (res != NULL) == positive;
723}
724
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100725int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100726_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
727{
728 int mark = p->mark;
729 void *res = func(p, arg);
730 p->mark = mark;
731 return (res != NULL) == positive;
732}
733
734int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100735_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
736{
737 int mark = p->mark;
738 void *res = func(p, arg);
739 p->mark = mark;
740 return (res != NULL) == positive;
741}
742
743int
744_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
745{
746 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100747 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100748 p->mark = mark;
749 return (res != NULL) == positive;
750}
751
752Token *
753_PyPegen_expect_token(Parser *p, int type)
754{
755 if (p->mark == p->fill) {
756 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300757 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100758 return NULL;
759 }
760 }
761 Token *t = p->tokens[p->mark];
762 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100763 return NULL;
764 }
765 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100766 return t;
767}
768
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700769expr_ty
770_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
771{
772 if (p->mark == p->fill) {
773 if (_PyPegen_fill_token(p) < 0) {
774 p->error_indicator = 1;
775 return NULL;
776 }
777 }
778 Token *t = p->tokens[p->mark];
779 if (t->type != NAME) {
780 return NULL;
781 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300782 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700783 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300784 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700785 return NULL;
786 }
787 if (strcmp(s, keyword) != 0) {
788 return NULL;
789 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300790 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700791}
792
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100793Token *
794_PyPegen_get_last_nonnwhitespace_token(Parser *p)
795{
796 assert(p->mark >= 0);
797 Token *token = NULL;
798 for (int m = p->mark - 1; m >= 0; m--) {
799 token = p->tokens[m];
800 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
801 break;
802 }
803 }
804 return token;
805}
806
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100807expr_ty
808_PyPegen_name_token(Parser *p)
809{
810 Token *t = _PyPegen_expect_token(p, NAME);
811 if (t == NULL) {
812 return NULL;
813 }
814 char* s = PyBytes_AsString(t->bytes);
815 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300816 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100817 return NULL;
818 }
819 PyObject *id = _PyPegen_new_identifier(p, s);
820 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300821 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100822 return NULL;
823 }
824 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
825 p->arena);
826}
827
828void *
829_PyPegen_string_token(Parser *p)
830{
831 return _PyPegen_expect_token(p, STRING);
832}
833
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100834static PyObject *
835parsenumber_raw(const char *s)
836{
837 const char *end;
838 long x;
839 double dx;
840 Py_complex compl;
841 int imflag;
842
843 assert(s != NULL);
844 errno = 0;
845 end = s + strlen(s) - 1;
846 imflag = *end == 'j' || *end == 'J';
847 if (s[0] == '0') {
848 x = (long)PyOS_strtoul(s, (char **)&end, 0);
849 if (x < 0 && errno == 0) {
850 return PyLong_FromString(s, (char **)0, 0);
851 }
852 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100853 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100854 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100855 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100856 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100857 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100858 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100859 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100860 return PyLong_FromLong(x);
861 }
862 /* XXX Huge floats may silently fail */
863 if (imflag) {
864 compl.real = 0.;
865 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100866 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100867 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100868 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100869 return PyComplex_FromCComplex(compl);
870 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100871 dx = PyOS_string_to_double(s, NULL, NULL);
872 if (dx == -1.0 && PyErr_Occurred()) {
873 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100874 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100875 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100876}
877
878static PyObject *
879parsenumber(const char *s)
880{
Pablo Galindofb61c422020-06-15 14:23:43 +0100881 char *dup;
882 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100883 PyObject *res = NULL;
884
885 assert(s != NULL);
886
887 if (strchr(s, '_') == NULL) {
888 return parsenumber_raw(s);
889 }
890 /* Create a duplicate without underscores. */
891 dup = PyMem_Malloc(strlen(s) + 1);
892 if (dup == NULL) {
893 return PyErr_NoMemory();
894 }
895 end = dup;
896 for (; *s; s++) {
897 if (*s != '_') {
898 *end++ = *s;
899 }
900 }
901 *end = '\0';
902 res = parsenumber_raw(dup);
903 PyMem_Free(dup);
904 return res;
905}
906
907expr_ty
908_PyPegen_number_token(Parser *p)
909{
910 Token *t = _PyPegen_expect_token(p, NUMBER);
911 if (t == NULL) {
912 return NULL;
913 }
914
915 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100916 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300917 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100918 return NULL;
919 }
920
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300921 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
922 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700923 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300924 "in Python 3.6 and greater");
925 }
926
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100927 PyObject *c = parsenumber(num_raw);
928
929 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300930 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100931 return NULL;
932 }
933
934 if (PyArena_AddPyObject(p->arena, c) < 0) {
935 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300936 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100937 return NULL;
938 }
939
940 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
941 p->arena);
942}
943
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300944static int // bool
945newline_in_string(Parser *p, const char *cur)
946{
Pablo Galindo2e6593d2020-06-06 00:52:27 +0100947 for (const char *c = cur; c >= p->tok->buf; c--) {
948 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300949 return 1;
950 }
951 }
952 return 0;
953}
954
955/* Check that the source for a single input statement really is a single
956 statement by looking at what is left in the buffer after parsing.
957 Trailing whitespace and comments are OK. */
958static int // bool
959bad_single_statement(Parser *p)
960{
961 const char *cur = strchr(p->tok->buf, '\n');
962
963 /* Newlines are allowed if preceded by a line continuation character
964 or if they appear inside a string. */
965 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
966 return 0;
967 }
968 char c = *cur;
969
970 for (;;) {
971 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
972 c = *++cur;
973 }
974
975 if (!c) {
976 return 0;
977 }
978
979 if (c != '#') {
980 return 1;
981 }
982
983 /* Suck up comment. */
984 while (c && c != '\n') {
985 c = *++cur;
986 }
987 }
988}
989
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100990void
991_PyPegen_Parser_Free(Parser *p)
992{
993 Py_XDECREF(p->normalize);
994 for (int i = 0; i < p->size; i++) {
995 PyMem_Free(p->tokens[i]);
996 }
997 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700998 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100999 PyMem_Free(p);
1000}
1001
Pablo Galindo2b74c832020-04-27 18:02:07 +01001002static int
1003compute_parser_flags(PyCompilerFlags *flags)
1004{
1005 int parser_flags = 0;
1006 if (!flags) {
1007 return 0;
1008 }
1009 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1010 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1011 }
1012 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1013 parser_flags |= PyPARSE_IGNORE_COOKIE;
1014 }
1015 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1016 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1017 }
1018 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1019 parser_flags |= PyPARSE_TYPE_COMMENTS;
1020 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001021 if (flags->cf_feature_version < 7) {
1022 parser_flags |= PyPARSE_ASYNC_HACKS;
1023 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001024 return parser_flags;
1025}
1026
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001027Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001028_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001029 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001030{
1031 Parser *p = PyMem_Malloc(sizeof(Parser));
1032 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001033 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001034 }
1035 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001036 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1037 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001038 p->tok = tok;
1039 p->keywords = NULL;
1040 p->n_keyword_lists = -1;
1041 p->tokens = PyMem_Malloc(sizeof(Token *));
1042 if (!p->tokens) {
1043 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001044 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001045 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001046 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001047 if (!p->tokens) {
1048 PyMem_Free(p->tokens);
1049 PyMem_Free(p);
1050 return (Parser *) PyErr_NoMemory();
1051 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001052 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1053 PyMem_Free(p->tokens[0]);
1054 PyMem_Free(p->tokens);
1055 PyMem_Free(p);
1056 return (Parser *) PyErr_NoMemory();
1057 }
1058
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001059 p->mark = 0;
1060 p->fill = 0;
1061 p->size = 1;
1062
1063 p->errcode = errcode;
1064 p->arena = arena;
1065 p->start_rule = start_rule;
1066 p->parsing_started = 0;
1067 p->normalize = NULL;
1068 p->error_indicator = 0;
1069
1070 p->starting_lineno = 0;
1071 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001072 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001073 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001074 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001075 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001076
1077 return p;
1078}
1079
1080void *
1081_PyPegen_run_parser(Parser *p)
1082{
1083 void *res = _PyPegen_parse(p);
1084 if (res == NULL) {
1085 if (PyErr_Occurred()) {
1086 return NULL;
1087 }
1088 if (p->fill == 0) {
1089 RAISE_SYNTAX_ERROR("error at start before reading any input");
1090 }
1091 else if (p->tok->done == E_EOF) {
1092 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1093 }
1094 else {
1095 if (p->tokens[p->fill-1]->type == INDENT) {
1096 RAISE_INDENTATION_ERROR("unexpected indent");
1097 }
1098 else if (p->tokens[p->fill-1]->type == DEDENT) {
1099 RAISE_INDENTATION_ERROR("unexpected unindent");
1100 }
1101 else {
1102 RAISE_SYNTAX_ERROR("invalid syntax");
1103 }
1104 }
1105 return NULL;
1106 }
1107
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001108 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1109 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1110 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1111 }
1112
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001113 return res;
1114}
1115
1116mod_ty
1117_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1118 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001119 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001120{
1121 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1122 if (tok == NULL) {
1123 if (PyErr_Occurred()) {
1124 raise_tokenizer_init_error(filename_ob);
1125 return NULL;
1126 }
1127 return NULL;
1128 }
1129 // This transfers the ownership to the tokenizer
1130 tok->filename = filename_ob;
1131 Py_INCREF(filename_ob);
1132
1133 // From here on we need to clean up even if there's an error
1134 mod_ty result = NULL;
1135
Pablo Galindo2b74c832020-04-27 18:02:07 +01001136 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001137 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1138 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001139 if (p == NULL) {
1140 goto error;
1141 }
1142
1143 result = _PyPegen_run_parser(p);
1144 _PyPegen_Parser_Free(p);
1145
1146error:
1147 PyTokenizer_Free(tok);
1148 return result;
1149}
1150
1151mod_ty
1152_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001153 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001154{
1155 FILE *fp = fopen(filename, "rb");
1156 if (fp == NULL) {
1157 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1158 return NULL;
1159 }
1160
1161 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001162 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001163
1164 fclose(fp);
1165 return result;
1166}
1167
1168mod_ty
1169_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001170 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001171{
1172 int exec_input = start_rule == Py_file_input;
1173
1174 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001175 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001176 tok = PyTokenizer_FromUTF8(str, exec_input);
1177 } else {
1178 tok = PyTokenizer_FromString(str, exec_input);
1179 }
1180 if (tok == NULL) {
1181 if (PyErr_Occurred()) {
1182 raise_tokenizer_init_error(filename_ob);
1183 }
1184 return NULL;
1185 }
1186 // This transfers the ownership to the tokenizer
1187 tok->filename = filename_ob;
1188 Py_INCREF(filename_ob);
1189
1190 // We need to clear up from here on
1191 mod_ty result = NULL;
1192
Pablo Galindo2b74c832020-04-27 18:02:07 +01001193 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001194 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001195 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1196 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001197 if (p == NULL) {
1198 goto error;
1199 }
1200
1201 result = _PyPegen_run_parser(p);
1202 _PyPegen_Parser_Free(p);
1203
1204error:
1205 PyTokenizer_Free(tok);
1206 return result;
1207}
1208
1209void *
1210_PyPegen_interactive_exit(Parser *p)
1211{
1212 if (p->errcode) {
1213 *(p->errcode) = E_EOF;
1214 }
1215 return NULL;
1216}
1217
1218/* Creates a single-element asdl_seq* that contains a */
1219asdl_seq *
1220_PyPegen_singleton_seq(Parser *p, void *a)
1221{
1222 assert(a != NULL);
1223 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1224 if (!seq) {
1225 return NULL;
1226 }
1227 asdl_seq_SET(seq, 0, a);
1228 return seq;
1229}
1230
1231/* Creates a copy of seq and prepends a to it */
1232asdl_seq *
1233_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1234{
1235 assert(a != NULL);
1236 if (!seq) {
1237 return _PyPegen_singleton_seq(p, a);
1238 }
1239
1240 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1241 if (!new_seq) {
1242 return NULL;
1243 }
1244
1245 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001246 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001247 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1248 }
1249 return new_seq;
1250}
1251
Guido van Rossumc001c092020-04-30 12:12:19 -07001252/* Creates a copy of seq and appends a to it */
1253asdl_seq *
1254_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1255{
1256 assert(a != NULL);
1257 if (!seq) {
1258 return _PyPegen_singleton_seq(p, a);
1259 }
1260
1261 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1262 if (!new_seq) {
1263 return NULL;
1264 }
1265
1266 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1267 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1268 }
1269 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1270 return new_seq;
1271}
1272
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001273static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001274_get_flattened_seq_size(asdl_seq *seqs)
1275{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001276 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001277 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1278 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1279 size += asdl_seq_LEN(inner_seq);
1280 }
1281 return size;
1282}
1283
1284/* Flattens an asdl_seq* of asdl_seq*s */
1285asdl_seq *
1286_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1287{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001288 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001289 assert(flattened_seq_size > 0);
1290
1291 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1292 if (!flattened_seq) {
1293 return NULL;
1294 }
1295
1296 int flattened_seq_idx = 0;
1297 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1298 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001299 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001300 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1301 }
1302 }
1303 assert(flattened_seq_idx == flattened_seq_size);
1304
1305 return flattened_seq;
1306}
1307
1308/* Creates a new name of the form <first_name>.<second_name> */
1309expr_ty
1310_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1311{
1312 assert(first_name != NULL && second_name != NULL);
1313 PyObject *first_identifier = first_name->v.Name.id;
1314 PyObject *second_identifier = second_name->v.Name.id;
1315
1316 if (PyUnicode_READY(first_identifier) == -1) {
1317 return NULL;
1318 }
1319 if (PyUnicode_READY(second_identifier) == -1) {
1320 return NULL;
1321 }
1322 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1323 if (!first_str) {
1324 return NULL;
1325 }
1326 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1327 if (!second_str) {
1328 return NULL;
1329 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001330 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001331
1332 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1333 if (!str) {
1334 return NULL;
1335 }
1336
1337 char *s = PyBytes_AS_STRING(str);
1338 if (!s) {
1339 return NULL;
1340 }
1341
1342 strcpy(s, first_str);
1343 s += strlen(first_str);
1344 *s++ = '.';
1345 strcpy(s, second_str);
1346 s += strlen(second_str);
1347 *s = '\0';
1348
1349 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1350 Py_DECREF(str);
1351 if (!uni) {
1352 return NULL;
1353 }
1354 PyUnicode_InternInPlace(&uni);
1355 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1356 Py_DECREF(uni);
1357 return NULL;
1358 }
1359
1360 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1361}
1362
1363/* Counts the total number of dots in seq's tokens */
1364int
1365_PyPegen_seq_count_dots(asdl_seq *seq)
1366{
1367 int number_of_dots = 0;
1368 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1369 Token *current_expr = asdl_seq_GET(seq, i);
1370 switch (current_expr->type) {
1371 case ELLIPSIS:
1372 number_of_dots += 3;
1373 break;
1374 case DOT:
1375 number_of_dots += 1;
1376 break;
1377 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001378 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001379 }
1380 }
1381
1382 return number_of_dots;
1383}
1384
1385/* Creates an alias with '*' as the identifier name */
1386alias_ty
1387_PyPegen_alias_for_star(Parser *p)
1388{
1389 PyObject *str = PyUnicode_InternFromString("*");
1390 if (!str) {
1391 return NULL;
1392 }
1393 if (PyArena_AddPyObject(p->arena, str) < 0) {
1394 Py_DECREF(str);
1395 return NULL;
1396 }
1397 return alias(str, NULL, p->arena);
1398}
1399
1400/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1401asdl_seq *
1402_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1403{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001404 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001405 assert(len > 0);
1406
1407 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1408 if (!new_seq) {
1409 return NULL;
1410 }
1411 for (Py_ssize_t i = 0; i < len; i++) {
1412 expr_ty e = asdl_seq_GET(seq, i);
1413 asdl_seq_SET(new_seq, i, e->v.Name.id);
1414 }
1415 return new_seq;
1416}
1417
1418/* Constructs a CmpopExprPair */
1419CmpopExprPair *
1420_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1421{
1422 assert(expr != NULL);
1423 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1424 if (!a) {
1425 return NULL;
1426 }
1427 a->cmpop = cmpop;
1428 a->expr = expr;
1429 return a;
1430}
1431
1432asdl_int_seq *
1433_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1434{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001435 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001436 assert(len > 0);
1437
1438 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1439 if (!new_seq) {
1440 return NULL;
1441 }
1442 for (Py_ssize_t i = 0; i < len; i++) {
1443 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1444 asdl_seq_SET(new_seq, i, pair->cmpop);
1445 }
1446 return new_seq;
1447}
1448
1449asdl_seq *
1450_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1451{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001452 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001453 assert(len > 0);
1454
1455 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1456 if (!new_seq) {
1457 return NULL;
1458 }
1459 for (Py_ssize_t i = 0; i < len; i++) {
1460 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1461 asdl_seq_SET(new_seq, i, pair->expr);
1462 }
1463 return new_seq;
1464}
1465
1466/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1467static asdl_seq *
1468_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1469{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001470 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001471 if (len == 0) {
1472 return NULL;
1473 }
1474
1475 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1476 if (!new_seq) {
1477 return NULL;
1478 }
1479 for (Py_ssize_t i = 0; i < len; i++) {
1480 expr_ty e = asdl_seq_GET(seq, i);
1481 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1482 }
1483 return new_seq;
1484}
1485
1486static expr_ty
1487_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1488{
1489 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1490}
1491
1492static expr_ty
1493_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1494{
1495 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1496}
1497
1498static expr_ty
1499_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1500{
1501 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1502}
1503
1504static expr_ty
1505_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1506{
1507 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1508}
1509
1510static expr_ty
1511_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1512{
1513 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1514}
1515
1516static expr_ty
1517_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1518{
1519 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1520}
1521
1522/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1523expr_ty
1524_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1525{
1526 assert(expr != NULL);
1527
1528 expr_ty new = NULL;
1529 switch (expr->kind) {
1530 case Name_kind:
1531 new = _set_name_context(p, expr, ctx);
1532 break;
1533 case Tuple_kind:
1534 new = _set_tuple_context(p, expr, ctx);
1535 break;
1536 case List_kind:
1537 new = _set_list_context(p, expr, ctx);
1538 break;
1539 case Subscript_kind:
1540 new = _set_subscript_context(p, expr, ctx);
1541 break;
1542 case Attribute_kind:
1543 new = _set_attribute_context(p, expr, ctx);
1544 break;
1545 case Starred_kind:
1546 new = _set_starred_context(p, expr, ctx);
1547 break;
1548 default:
1549 new = expr;
1550 }
1551 return new;
1552}
1553
1554/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1555KeyValuePair *
1556_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1557{
1558 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1559 if (!a) {
1560 return NULL;
1561 }
1562 a->key = key;
1563 a->value = value;
1564 return a;
1565}
1566
1567/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1568asdl_seq *
1569_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1570{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001571 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001572 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1573 if (!new_seq) {
1574 return NULL;
1575 }
1576 for (Py_ssize_t i = 0; i < len; i++) {
1577 KeyValuePair *pair = asdl_seq_GET(seq, i);
1578 asdl_seq_SET(new_seq, i, pair->key);
1579 }
1580 return new_seq;
1581}
1582
1583/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1584asdl_seq *
1585_PyPegen_get_values(Parser *p, asdl_seq *seq)
1586{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001587 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001588 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1589 if (!new_seq) {
1590 return NULL;
1591 }
1592 for (Py_ssize_t i = 0; i < len; i++) {
1593 KeyValuePair *pair = asdl_seq_GET(seq, i);
1594 asdl_seq_SET(new_seq, i, pair->value);
1595 }
1596 return new_seq;
1597}
1598
1599/* Constructs a NameDefaultPair */
1600NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001601_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001602{
1603 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1604 if (!a) {
1605 return NULL;
1606 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001607 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001608 a->value = value;
1609 return a;
1610}
1611
1612/* Constructs a SlashWithDefault */
1613SlashWithDefault *
1614_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1615{
1616 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1617 if (!a) {
1618 return NULL;
1619 }
1620 a->plain_names = plain_names;
1621 a->names_with_defaults = names_with_defaults;
1622 return a;
1623}
1624
1625/* Constructs a StarEtc */
1626StarEtc *
1627_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1628{
1629 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1630 if (!a) {
1631 return NULL;
1632 }
1633 a->vararg = vararg;
1634 a->kwonlyargs = kwonlyargs;
1635 a->kwarg = kwarg;
1636 return a;
1637}
1638
1639asdl_seq *
1640_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1641{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001642 Py_ssize_t first_len = asdl_seq_LEN(a);
1643 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001644 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1645 if (!new_seq) {
1646 return NULL;
1647 }
1648
1649 int k = 0;
1650 for (Py_ssize_t i = 0; i < first_len; i++) {
1651 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1652 }
1653 for (Py_ssize_t i = 0; i < second_len; i++) {
1654 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1655 }
1656
1657 return new_seq;
1658}
1659
1660static asdl_seq *
1661_get_names(Parser *p, asdl_seq *names_with_defaults)
1662{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001663 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001664 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1665 if (!seq) {
1666 return NULL;
1667 }
1668 for (Py_ssize_t i = 0; i < len; i++) {
1669 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1670 asdl_seq_SET(seq, i, pair->arg);
1671 }
1672 return seq;
1673}
1674
1675static asdl_seq *
1676_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1677{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001678 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001679 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1680 if (!seq) {
1681 return NULL;
1682 }
1683 for (Py_ssize_t i = 0; i < len; i++) {
1684 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1685 asdl_seq_SET(seq, i, pair->value);
1686 }
1687 return seq;
1688}
1689
1690/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1691arguments_ty
1692_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1693 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1694 asdl_seq *names_with_default, StarEtc *star_etc)
1695{
1696 asdl_seq *posonlyargs;
1697 if (slash_without_default != NULL) {
1698 posonlyargs = slash_without_default;
1699 }
1700 else if (slash_with_default != NULL) {
1701 asdl_seq *slash_with_default_names =
1702 _get_names(p, slash_with_default->names_with_defaults);
1703 if (!slash_with_default_names) {
1704 return NULL;
1705 }
1706 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1707 if (!posonlyargs) {
1708 return NULL;
1709 }
1710 }
1711 else {
1712 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1713 if (!posonlyargs) {
1714 return NULL;
1715 }
1716 }
1717
1718 asdl_seq *posargs;
1719 if (plain_names != NULL && names_with_default != NULL) {
1720 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1721 if (!names_with_default_names) {
1722 return NULL;
1723 }
1724 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1725 if (!posargs) {
1726 return NULL;
1727 }
1728 }
1729 else if (plain_names == NULL && names_with_default != NULL) {
1730 posargs = _get_names(p, names_with_default);
1731 if (!posargs) {
1732 return NULL;
1733 }
1734 }
1735 else if (plain_names != NULL && names_with_default == NULL) {
1736 posargs = plain_names;
1737 }
1738 else {
1739 posargs = _Py_asdl_seq_new(0, p->arena);
1740 if (!posargs) {
1741 return NULL;
1742 }
1743 }
1744
1745 asdl_seq *posdefaults;
1746 if (slash_with_default != NULL && names_with_default != NULL) {
1747 asdl_seq *slash_with_default_values =
1748 _get_defaults(p, slash_with_default->names_with_defaults);
1749 if (!slash_with_default_values) {
1750 return NULL;
1751 }
1752 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1753 if (!names_with_default_values) {
1754 return NULL;
1755 }
1756 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1757 if (!posdefaults) {
1758 return NULL;
1759 }
1760 }
1761 else if (slash_with_default == NULL && names_with_default != NULL) {
1762 posdefaults = _get_defaults(p, names_with_default);
1763 if (!posdefaults) {
1764 return NULL;
1765 }
1766 }
1767 else if (slash_with_default != NULL && names_with_default == NULL) {
1768 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1769 if (!posdefaults) {
1770 return NULL;
1771 }
1772 }
1773 else {
1774 posdefaults = _Py_asdl_seq_new(0, p->arena);
1775 if (!posdefaults) {
1776 return NULL;
1777 }
1778 }
1779
1780 arg_ty vararg = NULL;
1781 if (star_etc != NULL && star_etc->vararg != NULL) {
1782 vararg = star_etc->vararg;
1783 }
1784
1785 asdl_seq *kwonlyargs;
1786 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1787 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1788 if (!kwonlyargs) {
1789 return NULL;
1790 }
1791 }
1792 else {
1793 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1794 if (!kwonlyargs) {
1795 return NULL;
1796 }
1797 }
1798
1799 asdl_seq *kwdefaults;
1800 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1801 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1802 if (!kwdefaults) {
1803 return NULL;
1804 }
1805 }
1806 else {
1807 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1808 if (!kwdefaults) {
1809 return NULL;
1810 }
1811 }
1812
1813 arg_ty kwarg = NULL;
1814 if (star_etc != NULL && star_etc->kwarg != NULL) {
1815 kwarg = star_etc->kwarg;
1816 }
1817
1818 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1819 posdefaults, p->arena);
1820}
1821
1822/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1823 * arguments. */
1824arguments_ty
1825_PyPegen_empty_arguments(Parser *p)
1826{
1827 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1828 if (!posonlyargs) {
1829 return NULL;
1830 }
1831 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1832 if (!posargs) {
1833 return NULL;
1834 }
1835 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1836 if (!posdefaults) {
1837 return NULL;
1838 }
1839 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1840 if (!kwonlyargs) {
1841 return NULL;
1842 }
1843 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1844 if (!kwdefaults) {
1845 return NULL;
1846 }
1847
1848 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1849 p->arena);
1850}
1851
1852/* Encapsulates the value of an operator_ty into an AugOperator struct */
1853AugOperator *
1854_PyPegen_augoperator(Parser *p, operator_ty kind)
1855{
1856 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1857 if (!a) {
1858 return NULL;
1859 }
1860 a->kind = kind;
1861 return a;
1862}
1863
1864/* Construct a FunctionDef equivalent to function_def, but with decorators */
1865stmt_ty
1866_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1867{
1868 assert(function_def != NULL);
1869 if (function_def->kind == AsyncFunctionDef_kind) {
1870 return _Py_AsyncFunctionDef(
1871 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1872 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1873 function_def->v.FunctionDef.type_comment, function_def->lineno,
1874 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1875 p->arena);
1876 }
1877
1878 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1879 function_def->v.FunctionDef.body, decorators,
1880 function_def->v.FunctionDef.returns,
1881 function_def->v.FunctionDef.type_comment, function_def->lineno,
1882 function_def->col_offset, function_def->end_lineno,
1883 function_def->end_col_offset, p->arena);
1884}
1885
1886/* Construct a ClassDef equivalent to class_def, but with decorators */
1887stmt_ty
1888_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1889{
1890 assert(class_def != NULL);
1891 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1892 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1893 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1894 class_def->end_col_offset, p->arena);
1895}
1896
1897/* Construct a KeywordOrStarred */
1898KeywordOrStarred *
1899_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1900{
1901 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1902 if (!a) {
1903 return NULL;
1904 }
1905 a->element = element;
1906 a->is_keyword = is_keyword;
1907 return a;
1908}
1909
1910/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1911static int
1912_seq_number_of_starred_exprs(asdl_seq *seq)
1913{
1914 int n = 0;
1915 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1916 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1917 if (!k->is_keyword) {
1918 n++;
1919 }
1920 }
1921 return n;
1922}
1923
1924/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1925asdl_seq *
1926_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1927{
1928 int new_len = _seq_number_of_starred_exprs(kwargs);
1929 if (new_len == 0) {
1930 return NULL;
1931 }
1932 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1933 if (!new_seq) {
1934 return NULL;
1935 }
1936
1937 int idx = 0;
1938 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1939 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1940 if (!k->is_keyword) {
1941 asdl_seq_SET(new_seq, idx++, k->element);
1942 }
1943 }
1944 return new_seq;
1945}
1946
1947/* Return a new asdl_seq* with only the keywords in kwargs */
1948asdl_seq *
1949_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1950{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001951 Py_ssize_t len = asdl_seq_LEN(kwargs);
1952 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001953 if (new_len == 0) {
1954 return NULL;
1955 }
1956 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1957 if (!new_seq) {
1958 return NULL;
1959 }
1960
1961 int idx = 0;
1962 for (Py_ssize_t i = 0; i < len; i++) {
1963 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1964 if (k->is_keyword) {
1965 asdl_seq_SET(new_seq, idx++, k->element);
1966 }
1967 }
1968 return new_seq;
1969}
1970
1971expr_ty
1972_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1973{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001974 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001975 assert(len > 0);
1976
1977 Token *first = asdl_seq_GET(strings, 0);
1978 Token *last = asdl_seq_GET(strings, len - 1);
1979
1980 int bytesmode = 0;
1981 PyObject *bytes_str = NULL;
1982
1983 FstringParser state;
1984 _PyPegen_FstringParser_Init(&state);
1985
1986 for (Py_ssize_t i = 0; i < len; i++) {
1987 Token *t = asdl_seq_GET(strings, i);
1988
1989 int this_bytesmode;
1990 int this_rawmode;
1991 PyObject *s;
1992 const char *fstr;
1993 Py_ssize_t fstrlen = -1;
1994
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001995 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001996 goto error;
1997 }
1998
1999 /* Check that we are not mixing bytes with unicode. */
2000 if (i != 0 && bytesmode != this_bytesmode) {
2001 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2002 Py_XDECREF(s);
2003 goto error;
2004 }
2005 bytesmode = this_bytesmode;
2006
2007 if (fstr != NULL) {
2008 assert(s == NULL && !bytesmode);
2009
2010 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2011 this_rawmode, 0, first, t, last);
2012 if (result < 0) {
2013 goto error;
2014 }
2015 }
2016 else {
2017 /* String or byte string. */
2018 assert(s != NULL && fstr == NULL);
2019 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2020
2021 if (bytesmode) {
2022 if (i == 0) {
2023 bytes_str = s;
2024 }
2025 else {
2026 PyBytes_ConcatAndDel(&bytes_str, s);
2027 if (!bytes_str) {
2028 goto error;
2029 }
2030 }
2031 }
2032 else {
2033 /* This is a regular string. Concatenate it. */
2034 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2035 goto error;
2036 }
2037 }
2038 }
2039 }
2040
2041 if (bytesmode) {
2042 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2043 goto error;
2044 }
2045 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2046 last->end_col_offset, p->arena);
2047 }
2048
2049 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2050
2051error:
2052 Py_XDECREF(bytes_str);
2053 _PyPegen_FstringParser_Dealloc(&state);
2054 if (PyErr_Occurred()) {
2055 raise_decode_error(p);
2056 }
2057 return NULL;
2058}
Guido van Rossumc001c092020-04-30 12:12:19 -07002059
2060mod_ty
2061_PyPegen_make_module(Parser *p, asdl_seq *a) {
2062 asdl_seq *type_ignores = NULL;
2063 Py_ssize_t num = p->type_ignore_comments.num_items;
2064 if (num > 0) {
2065 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2066 type_ignores = _Py_asdl_seq_new(num, p->arena);
2067 if (type_ignores == NULL) {
2068 return NULL;
2069 }
2070 for (int i = 0; i < num; i++) {
2071 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2072 if (tag == NULL) {
2073 return NULL;
2074 }
2075 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2076 if (ti == NULL) {
2077 return NULL;
2078 }
2079 asdl_seq_SET(type_ignores, i, ti);
2080 }
2081 }
2082 return Module(a, type_ignores, p->arena);
2083}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002084
2085// Error reporting helpers
2086
2087expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002088_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002089{
2090 if (e == NULL) {
2091 return NULL;
2092 }
2093
2094#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2095 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2096 for (Py_ssize_t i = 0; i < len; i++) {\
2097 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002098 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002099 if (child != NULL) {\
2100 return child;\
2101 }\
2102 }\
2103 } while (0)
2104
2105 // We only need to visit List and Tuple nodes recursively as those
2106 // are the only ones that can contain valid names in targets when
2107 // they are parsed as expressions. Any other kind of expression
2108 // that is a container (like Sets or Dicts) is directly invalid and
2109 // we don't need to visit it recursively.
2110
2111 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002112 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002113 VISIT_CONTAINER(e, List);
2114 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002115 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002116 VISIT_CONTAINER(e, Tuple);
2117 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002118 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002119 if (targets_type == DEL_TARGETS) {
2120 return e;
2121 }
2122 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2123 case Compare_kind:
2124 // This is needed, because the `a in b` in `for a in b` gets parsed
2125 // as a comparison, and so we need to search the left side of the comparison
2126 // for invalid targets.
2127 if (targets_type == FOR_TARGETS) {
2128 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2129 if (cmpop == In) {
2130 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2131 }
2132 return NULL;
2133 }
2134 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002135 case Name_kind:
2136 case Subscript_kind:
2137 case Attribute_kind:
2138 return NULL;
2139 default:
2140 return e;
2141 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002142}
2143
2144void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2145 int kwarg_unpacking = 0;
2146 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2147 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2148 if (!keyword->arg) {
2149 kwarg_unpacking = 1;
2150 }
2151 }
2152
2153 const char *msg = NULL;
2154 if (kwarg_unpacking) {
2155 msg = "positional argument follows keyword argument unpacking";
2156 } else {
2157 msg = "positional argument follows keyword argument";
2158 }
2159
2160 return RAISE_SYNTAX_ERROR(msg);
2161}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002162
2163void *
2164_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2165{
2166 /* The rule that calls this function is 'args for_if_clauses'.
2167 For the input f(L, x for x in y), L and x are in args and
2168 the for is parsed as a for_if_clause. We have to check if
2169 len <= 1, so that input like dict((a, b) for a, b in x)
2170 gets successfully parsed and then we pass the last
2171 argument (x in the above example) as the location of the
2172 error */
2173 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2174 if (len <= 1) {
2175 return NULL;
2176 }
2177
2178 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2179 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2180 "Generator expression must be parenthesized"
2181 );
2182}