blob: e2cbf8ba2461ce161ad6b82290e31fc4562beea5 [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01003#include "tokenizer.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004
5#include "pegen.h"
Pablo Galindo1ed83ad2020-06-11 17:30:46 +01006#include "string_parser.h"
Pablo Galindoc5fc1562020-04-22 23:29:27 +01007
Guido van Rossumc001c092020-04-30 12:12:19 -07008PyObject *
9_PyPegen_new_type_comment(Parser *p, char *s)
10{
11 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
12 if (res == NULL) {
13 return NULL;
14 }
15 if (PyArena_AddPyObject(p->arena, res) < 0) {
16 Py_DECREF(res);
17 return NULL;
18 }
19 return res;
20}
21
22arg_ty
23_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
24{
25 if (tc == NULL) {
26 return a;
27 }
28 char *bytes = PyBytes_AsString(tc->bytes);
29 if (bytes == NULL) {
30 return NULL;
31 }
32 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
33 if (tco == NULL) {
34 return NULL;
35 }
36 return arg(a->arg, a->annotation, tco,
37 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
38 p->arena);
39}
40
Pablo Galindoc5fc1562020-04-22 23:29:27 +010041static int
42init_normalization(Parser *p)
43{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030044 if (p->normalize) {
45 return 1;
46 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010047 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
48 if (!m)
49 {
50 return 0;
51 }
52 p->normalize = PyObject_GetAttrString(m, "normalize");
53 Py_DECREF(m);
54 if (!p->normalize)
55 {
56 return 0;
57 }
58 return 1;
59}
60
Pablo Galindo2b74c832020-04-27 18:02:07 +010061/* Checks if the NOTEQUAL token is valid given the current parser flags
620 indicates success and nonzero indicates failure (an exception may be set) */
63int
64_PyPegen_check_barry_as_flufl(Parser *p) {
65 Token *t = p->tokens[p->fill - 1];
66 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
Pablo Galindofb61c422020-06-15 14:23:43 +010070 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010071 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
Pablo Galindofb61c422020-06-15 14:23:43 +010073 }
74 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
Pablo Galindo2b74c832020-04-27 18:02:07 +010075 return strcmp(tok_str, "!=");
76 }
77 return 0;
78}
79
Pablo Galindoc5fc1562020-04-22 23:29:27 +010080PyObject *
81_PyPegen_new_identifier(Parser *p, char *n)
82{
83 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
84 if (!id) {
85 goto error;
86 }
87 /* PyUnicode_DecodeUTF8 should always return a ready string. */
88 assert(PyUnicode_IS_READY(id));
89 /* Check whether there are non-ASCII characters in the
90 identifier; if so, normalize to NFKC. */
91 if (!PyUnicode_IS_ASCII(id))
92 {
93 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030094 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010095 {
96 Py_DECREF(id);
97 goto error;
98 }
99 PyObject *form = PyUnicode_InternFromString("NFKC");
100 if (form == NULL)
101 {
102 Py_DECREF(id);
103 goto error;
104 }
105 PyObject *args[2] = {form, id};
106 id2 = _PyObject_FastCall(p->normalize, args, 2);
107 Py_DECREF(id);
108 Py_DECREF(form);
109 if (!id2) {
110 goto error;
111 }
112 if (!PyUnicode_Check(id2))
113 {
114 PyErr_Format(PyExc_TypeError,
115 "unicodedata.normalize() must return a string, not "
116 "%.200s",
117 _PyType_Name(Py_TYPE(id2)));
118 Py_DECREF(id2);
119 goto error;
120 }
121 id = id2;
122 }
123 PyUnicode_InternInPlace(&id);
124 if (PyArena_AddPyObject(p->arena, id) < 0)
125 {
126 Py_DECREF(id);
127 goto error;
128 }
129 return id;
130
131error:
132 p->error_indicator = 1;
133 return NULL;
134}
135
136static PyObject *
137_create_dummy_identifier(Parser *p)
138{
139 return _PyPegen_new_identifier(p, "");
140}
141
142static inline Py_ssize_t
Pablo Galindo51c58962020-06-16 16:49:43 +0100143byte_offset_to_character_offset(PyObject *line, Py_ssize_t col_offset)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100144{
145 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300146 if (!str) {
147 return 0;
148 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100149 assert(col_offset >= 0 && (unsigned long)col_offset <= strlen(str));
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300150 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100151 if (!text) {
152 return 0;
153 }
154 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
155 Py_DECREF(text);
156 return size;
157}
158
159const char *
160_PyPegen_get_expr_name(expr_ty e)
161{
Pablo Galindo9f495902020-06-08 02:57:00 +0100162 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100163 switch (e->kind) {
164 case Attribute_kind:
165 return "attribute";
166 case Subscript_kind:
167 return "subscript";
168 case Starred_kind:
169 return "starred";
170 case Name_kind:
171 return "name";
172 case List_kind:
173 return "list";
174 case Tuple_kind:
175 return "tuple";
176 case Lambda_kind:
177 return "lambda";
178 case Call_kind:
179 return "function call";
180 case BoolOp_kind:
181 case BinOp_kind:
182 case UnaryOp_kind:
183 return "operator";
184 case GeneratorExp_kind:
185 return "generator expression";
186 case Yield_kind:
187 case YieldFrom_kind:
188 return "yield expression";
189 case Await_kind:
190 return "await expression";
191 case ListComp_kind:
192 return "list comprehension";
193 case SetComp_kind:
194 return "set comprehension";
195 case DictComp_kind:
196 return "dict comprehension";
197 case Dict_kind:
198 return "dict display";
199 case Set_kind:
200 return "set display";
201 case JoinedStr_kind:
202 case FormattedValue_kind:
203 return "f-string expression";
204 case Constant_kind: {
205 PyObject *value = e->v.Constant.value;
206 if (value == Py_None) {
207 return "None";
208 }
209 if (value == Py_False) {
210 return "False";
211 }
212 if (value == Py_True) {
213 return "True";
214 }
215 if (value == Py_Ellipsis) {
216 return "Ellipsis";
217 }
218 return "literal";
219 }
220 case Compare_kind:
221 return "comparison";
222 case IfExp_kind:
223 return "conditional expression";
224 case NamedExpr_kind:
225 return "named expression";
226 default:
227 PyErr_Format(PyExc_SystemError,
228 "unexpected expression in assignment %d (line %d)",
229 e->kind, e->lineno);
230 return NULL;
231 }
232}
233
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300234static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100235raise_decode_error(Parser *p)
236{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300237 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100238 const char *errtype = NULL;
239 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
240 errtype = "unicode error";
241 }
242 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
243 errtype = "value error";
244 }
245 if (errtype) {
Pablo Galindofb61c422020-06-15 14:23:43 +0100246 PyObject *type;
247 PyObject *value;
248 PyObject *tback;
249 PyObject *errstr;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100250 PyErr_Fetch(&type, &value, &tback);
251 errstr = PyObject_Str(value);
252 if (errstr) {
253 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
254 Py_DECREF(errstr);
255 }
256 else {
257 PyErr_Clear();
258 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
259 }
260 Py_XDECREF(type);
261 Py_XDECREF(value);
262 Py_XDECREF(tback);
263 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300264
265 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100266}
267
268static void
269raise_tokenizer_init_error(PyObject *filename)
270{
271 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
272 || PyErr_ExceptionMatches(PyExc_ValueError)
273 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
274 return;
275 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300276 PyObject *errstr = NULL;
277 PyObject *tuple = NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100278 PyObject *type;
279 PyObject *value;
280 PyObject *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100281 PyErr_Fetch(&type, &value, &tback);
282 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300283 if (!errstr) {
284 goto error;
285 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100286
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300287 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100288 if (!tmp) {
289 goto error;
290 }
291
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300292 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100293 Py_DECREF(tmp);
294 if (!value) {
295 goto error;
296 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300297 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100298
299error:
300 Py_XDECREF(type);
301 Py_XDECREF(value);
302 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300303 Py_XDECREF(errstr);
304 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100305}
306
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100307static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100308tokenizer_error(Parser *p)
309{
310 if (PyErr_Occurred()) {
311 return -1;
312 }
313
314 const char *msg = NULL;
315 PyObject* errtype = PyExc_SyntaxError;
316 switch (p->tok->done) {
317 case E_TOKEN:
318 msg = "invalid token";
319 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300321 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
322 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100323 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300324 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
325 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300326 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300327 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
328 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100329 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300330 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
331 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100332 case E_INTR:
333 if (!PyErr_Occurred()) {
334 PyErr_SetNone(PyExc_KeyboardInterrupt);
335 }
336 return -1;
337 case E_NOMEM:
338 PyErr_NoMemory();
339 return -1;
340 case E_TABSPACE:
341 errtype = PyExc_TabError;
342 msg = "inconsistent use of tabs and spaces in indentation";
343 break;
344 case E_TOODEEP:
345 errtype = PyExc_IndentationError;
346 msg = "too many levels of indentation";
347 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100348 case E_LINECONT:
349 msg = "unexpected character after line continuation character";
350 break;
351 default:
352 msg = "unknown parsing error";
353 }
354
355 PyErr_Format(errtype, msg);
356 // There is no reliable column information for this error
357 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
358
359 return -1;
360}
361
362void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300363_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
364{
365 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
Pablo Galindo51c58962020-06-16 16:49:43 +0100366 Py_ssize_t col_offset;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300367 if (t->col_offset == -1) {
368 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
369 intptr_t, int);
370 } else {
371 col_offset = t->col_offset + 1;
372 }
373
374 va_list va;
375 va_start(va, errmsg);
376 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
377 col_offset, errmsg, va);
378 va_end(va);
379
380 return NULL;
381}
382
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300383void *
384_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Pablo Galindo51c58962020-06-16 16:49:43 +0100385 Py_ssize_t lineno, Py_ssize_t col_offset,
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300386 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100387{
388 PyObject *value = NULL;
389 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300390 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300392 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100393
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300394 if (p->start_rule == Py_fstring_input) {
395 const char *fstring_msg = "f-string: ";
396 Py_ssize_t len = strlen(fstring_msg) + strlen(errmsg);
397
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300398 char *new_errmsg = PyMem_Malloc(len + 1); // Lengths of both strings plus NULL character
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300399 if (!new_errmsg) {
400 return (void *) PyErr_NoMemory();
401 }
402
403 // Copy both strings into new buffer
404 memcpy(new_errmsg, fstring_msg, strlen(fstring_msg));
405 memcpy(new_errmsg + strlen(fstring_msg), errmsg, strlen(errmsg));
406 new_errmsg[len] = 0;
407 errmsg = new_errmsg;
408 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100409 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100410 if (!errstr) {
411 goto error;
412 }
413
414 if (p->start_rule == Py_file_input) {
Lysandros Nikolaou861efc62020-06-20 15:57:27 +0300415 error_line = PyErr_ProgramTextObject(p->tok->filename, (int) lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100416 }
417
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300418 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100419 Py_ssize_t size = p->tok->inp - p->tok->buf;
Pablo Galindobcc30362020-05-14 21:11:48 +0100420 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300421 if (!error_line) {
422 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300423 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100424 }
425
Lysandros Nikolaou1f0f4ab2020-06-28 02:41:48 +0300426 if (p->start_rule == Py_fstring_input) {
427 col_offset -= p->starting_col_offset;
428 }
Pablo Galindo51c58962020-06-16 16:49:43 +0100429 Py_ssize_t col_number = col_offset;
430
431 if (p->tok->encoding != NULL) {
432 col_number = byte_offset_to_character_offset(error_line, col_offset);
433 }
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300434
435 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100436 if (!tmp) {
437 goto error;
438 }
439 value = PyTuple_Pack(2, errstr, tmp);
440 Py_DECREF(tmp);
441 if (!value) {
442 goto error;
443 }
444 PyErr_SetObject(errtype, value);
445
446 Py_DECREF(errstr);
447 Py_DECREF(value);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300448 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300449 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300450 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100451 return NULL;
452
453error:
454 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300455 Py_XDECREF(error_line);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300456 if (p->start_rule == Py_fstring_input) {
Lysandros Nikolaou6dcbc242020-06-27 20:47:00 +0300457 PyMem_Free((void *)errmsg);
Lysandros Nikolaou2e0a9202020-06-26 14:24:05 +0300458 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100459 return NULL;
460}
461
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100462#if 0
463static const char *
464token_name(int type)
465{
466 if (0 <= type && type <= N_TOKENS) {
467 return _PyParser_TokenNames[type];
468 }
469 return "<Huh?>";
470}
471#endif
472
473// Here, mark is the start of the node, while p->mark is the end.
474// If node==NULL, they should be the same.
475int
476_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
477{
478 // Insert in front
479 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
480 if (m == NULL) {
481 return -1;
482 }
483 m->type = type;
484 m->node = node;
485 m->mark = p->mark;
486 m->next = p->tokens[mark]->memo;
487 p->tokens[mark]->memo = m;
488 return 0;
489}
490
491// Like _PyPegen_insert_memo(), but updates an existing node if found.
492int
493_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
494{
495 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
496 if (m->type == type) {
497 // Update existing node.
498 m->node = node;
499 m->mark = p->mark;
500 return 0;
501 }
502 }
503 // Insert new node.
504 return _PyPegen_insert_memo(p, mark, type, node);
505}
506
507// Return dummy NAME.
508void *
509_PyPegen_dummy_name(Parser *p, ...)
510{
511 static void *cache = NULL;
512
513 if (cache != NULL) {
514 return cache;
515 }
516
517 PyObject *id = _create_dummy_identifier(p);
518 if (!id) {
519 return NULL;
520 }
521 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
522 return cache;
523}
524
525static int
526_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
527{
Lysandros Nikolaou782f44b2020-07-07 01:42:21 +0300528 assert(name_len > 0);
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100529 if (name_len >= p->n_keyword_lists ||
530 p->keywords[name_len] == NULL ||
531 p->keywords[name_len]->type == -1) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100532 return NAME;
533 }
Pablo Galindo1ac0cbc2020-07-06 20:31:16 +0100534 for (KeywordToken *k = p->keywords[name_len]; k != NULL && k->type != -1; k++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100535 if (strncmp(k->str, name, name_len) == 0) {
536 return k->type;
537 }
538 }
539 return NAME;
540}
541
Guido van Rossumc001c092020-04-30 12:12:19 -0700542static int
543growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
544 assert(initial_size > 0);
545 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
546 arr->size = initial_size;
547 arr->num_items = 0;
548
549 return arr->items != NULL;
550}
551
552static int
553growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
554 if (arr->num_items >= arr->size) {
555 size_t new_size = arr->size * 2;
556 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
557 if (!new_items_array) {
558 return 0;
559 }
560 arr->items = new_items_array;
561 arr->size = new_size;
562 }
563
564 arr->items[arr->num_items].lineno = lineno;
565 arr->items[arr->num_items].comment = comment; // Take ownership
566 arr->num_items++;
567 return 1;
568}
569
570static void
571growable_comment_array_deallocate(growable_comment_array *arr) {
572 for (unsigned i = 0; i < arr->num_items; i++) {
573 PyMem_Free(arr->items[i].comment);
574 }
575 PyMem_Free(arr->items);
576}
577
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100578int
579_PyPegen_fill_token(Parser *p)
580{
Pablo Galindofb61c422020-06-15 14:23:43 +0100581 const char *start;
582 const char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100583 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700584
585 // Record and skip '# type: ignore' comments
586 while (type == TYPE_IGNORE) {
587 Py_ssize_t len = end - start;
588 char *tag = PyMem_Malloc(len + 1);
589 if (tag == NULL) {
590 PyErr_NoMemory();
591 return -1;
592 }
593 strncpy(tag, start, len);
594 tag[len] = '\0';
595 // Ownership of tag passes to the growable array
596 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
597 PyErr_NoMemory();
598 return -1;
599 }
600 type = PyTokenizer_Get(p->tok, &start, &end);
601 }
602
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100603 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
604 type = NEWLINE; /* Add an extra newline */
605 p->parsing_started = 0;
606
Pablo Galindob94dbd72020-04-27 18:35:58 +0100607 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100608 p->tok->pendin = -p->tok->indent;
609 p->tok->indent = 0;
610 }
611 }
612 else {
613 p->parsing_started = 1;
614 }
615
616 if (p->fill == p->size) {
617 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300618 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
619 if (new_tokens == NULL) {
620 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100621 return -1;
622 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100623 p->tokens = new_tokens;
624
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100625 for (int i = p->size; i < newsize; i++) {
626 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300627 if (p->tokens[i] == NULL) {
628 p->size = i; // Needed, in order to cleanup correctly after parser fails
629 PyErr_NoMemory();
630 return -1;
631 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100632 memset(p->tokens[i], '\0', sizeof(Token));
633 }
634 p->size = newsize;
635 }
636
637 Token *t = p->tokens[p->fill];
638 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
639 t->bytes = PyBytes_FromStringAndSize(start, end - start);
640 if (t->bytes == NULL) {
641 return -1;
642 }
643 PyArena_AddPyObject(p->arena, t->bytes);
644
645 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
646 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100647 int end_lineno = p->tok->lineno;
Pablo Galindofb61c422020-06-15 14:23:43 +0100648 int col_offset = -1;
649 int end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100650 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100651 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100652 }
653 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100654 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100655 }
656
657 t->lineno = p->starting_lineno + lineno;
658 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
659 t->end_lineno = p->starting_lineno + end_lineno;
660 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
661
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100662 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300663
664 if (type == ERRORTOKEN) {
665 if (p->tok->done == E_DECODE) {
666 return raise_decode_error(p);
667 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100668 return tokenizer_error(p);
669
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300670 }
671
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100672 return 0;
673}
674
675// Instrumentation to count the effectiveness of memoization.
676// The array counts the number of tokens skipped by memoization,
677// indexed by type.
678
679#define NSTATISTICS 2000
680static long memo_statistics[NSTATISTICS];
681
682void
683_PyPegen_clear_memo_statistics()
684{
685 for (int i = 0; i < NSTATISTICS; i++) {
686 memo_statistics[i] = 0;
687 }
688}
689
690PyObject *
691_PyPegen_get_memo_statistics()
692{
693 PyObject *ret = PyList_New(NSTATISTICS);
694 if (ret == NULL) {
695 return NULL;
696 }
697 for (int i = 0; i < NSTATISTICS; i++) {
698 PyObject *value = PyLong_FromLong(memo_statistics[i]);
699 if (value == NULL) {
700 Py_DECREF(ret);
701 return NULL;
702 }
703 // PyList_SetItem borrows a reference to value.
704 if (PyList_SetItem(ret, i, value) < 0) {
705 Py_DECREF(ret);
706 return NULL;
707 }
708 }
709 return ret;
710}
711
712int // bool
713_PyPegen_is_memoized(Parser *p, int type, void *pres)
714{
715 if (p->mark == p->fill) {
716 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300717 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100718 return -1;
719 }
720 }
721
722 Token *t = p->tokens[p->mark];
723
724 for (Memo *m = t->memo; m != NULL; m = m->next) {
725 if (m->type == type) {
726 if (0 <= type && type < NSTATISTICS) {
727 long count = m->mark - p->mark;
728 // A memoized negative result counts for one.
729 if (count <= 0) {
730 count = 1;
731 }
732 memo_statistics[type] += count;
733 }
734 p->mark = m->mark;
735 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100736 return 1;
737 }
738 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100739 return 0;
740}
741
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100742
743int
744_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
745{
746 int mark = p->mark;
747 void *res = func(p);
748 p->mark = mark;
749 return (res != NULL) == positive;
750}
751
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100752int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100753_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
754{
755 int mark = p->mark;
756 void *res = func(p, arg);
757 p->mark = mark;
758 return (res != NULL) == positive;
759}
760
761int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100762_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
763{
764 int mark = p->mark;
765 void *res = func(p, arg);
766 p->mark = mark;
767 return (res != NULL) == positive;
768}
769
770int
771_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
772{
773 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100774 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100775 p->mark = mark;
776 return (res != NULL) == positive;
777}
778
779Token *
780_PyPegen_expect_token(Parser *p, int type)
781{
782 if (p->mark == p->fill) {
783 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300784 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100785 return NULL;
786 }
787 }
788 Token *t = p->tokens[p->mark];
789 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100790 return NULL;
791 }
792 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100793 return t;
794}
795
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700796expr_ty
797_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
798{
799 if (p->mark == p->fill) {
800 if (_PyPegen_fill_token(p) < 0) {
801 p->error_indicator = 1;
802 return NULL;
803 }
804 }
805 Token *t = p->tokens[p->mark];
806 if (t->type != NAME) {
807 return NULL;
808 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300809 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700810 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300811 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700812 return NULL;
813 }
814 if (strcmp(s, keyword) != 0) {
815 return NULL;
816 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300817 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700818}
819
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100820Token *
821_PyPegen_get_last_nonnwhitespace_token(Parser *p)
822{
823 assert(p->mark >= 0);
824 Token *token = NULL;
825 for (int m = p->mark - 1; m >= 0; m--) {
826 token = p->tokens[m];
827 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
828 break;
829 }
830 }
831 return token;
832}
833
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100834expr_ty
835_PyPegen_name_token(Parser *p)
836{
837 Token *t = _PyPegen_expect_token(p, NAME);
838 if (t == NULL) {
839 return NULL;
840 }
841 char* s = PyBytes_AsString(t->bytes);
842 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300843 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100844 return NULL;
845 }
846 PyObject *id = _PyPegen_new_identifier(p, s);
847 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300848 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100849 return NULL;
850 }
851 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
852 p->arena);
853}
854
855void *
856_PyPegen_string_token(Parser *p)
857{
858 return _PyPegen_expect_token(p, STRING);
859}
860
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100861static PyObject *
862parsenumber_raw(const char *s)
863{
864 const char *end;
865 long x;
866 double dx;
867 Py_complex compl;
868 int imflag;
869
870 assert(s != NULL);
871 errno = 0;
872 end = s + strlen(s) - 1;
873 imflag = *end == 'j' || *end == 'J';
874 if (s[0] == '0') {
875 x = (long)PyOS_strtoul(s, (char **)&end, 0);
876 if (x < 0 && errno == 0) {
877 return PyLong_FromString(s, (char **)0, 0);
878 }
879 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100880 else {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100881 x = PyOS_strtol(s, (char **)&end, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100882 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100883 if (*end == '\0') {
Pablo Galindofb61c422020-06-15 14:23:43 +0100884 if (errno != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100885 return PyLong_FromString(s, (char **)0, 0);
Pablo Galindofb61c422020-06-15 14:23:43 +0100886 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100887 return PyLong_FromLong(x);
888 }
889 /* XXX Huge floats may silently fail */
890 if (imflag) {
891 compl.real = 0.;
892 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
Pablo Galindofb61c422020-06-15 14:23:43 +0100893 if (compl.imag == -1.0 && PyErr_Occurred()) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100894 return NULL;
Pablo Galindofb61c422020-06-15 14:23:43 +0100895 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100896 return PyComplex_FromCComplex(compl);
897 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100898 dx = PyOS_string_to_double(s, NULL, NULL);
899 if (dx == -1.0 && PyErr_Occurred()) {
900 return NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100901 }
Pablo Galindofb61c422020-06-15 14:23:43 +0100902 return PyFloat_FromDouble(dx);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100903}
904
905static PyObject *
906parsenumber(const char *s)
907{
Pablo Galindofb61c422020-06-15 14:23:43 +0100908 char *dup;
909 char *end;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100910 PyObject *res = NULL;
911
912 assert(s != NULL);
913
914 if (strchr(s, '_') == NULL) {
915 return parsenumber_raw(s);
916 }
917 /* Create a duplicate without underscores. */
918 dup = PyMem_Malloc(strlen(s) + 1);
919 if (dup == NULL) {
920 return PyErr_NoMemory();
921 }
922 end = dup;
923 for (; *s; s++) {
924 if (*s != '_') {
925 *end++ = *s;
926 }
927 }
928 *end = '\0';
929 res = parsenumber_raw(dup);
930 PyMem_Free(dup);
931 return res;
932}
933
934expr_ty
935_PyPegen_number_token(Parser *p)
936{
937 Token *t = _PyPegen_expect_token(p, NUMBER);
938 if (t == NULL) {
939 return NULL;
940 }
941
942 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100943 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300944 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100945 return NULL;
946 }
947
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300948 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
949 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700950 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300951 "in Python 3.6 and greater");
952 }
953
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100954 PyObject *c = parsenumber(num_raw);
955
956 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300957 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100958 return NULL;
959 }
960
961 if (PyArena_AddPyObject(p->arena, c) < 0) {
962 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300963 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100964 return NULL;
965 }
966
967 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
968 p->arena);
969}
970
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300971static int // bool
972newline_in_string(Parser *p, const char *cur)
973{
Pablo Galindo2e6593d2020-06-06 00:52:27 +0100974 for (const char *c = cur; c >= p->tok->buf; c--) {
975 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300976 return 1;
977 }
978 }
979 return 0;
980}
981
982/* Check that the source for a single input statement really is a single
983 statement by looking at what is left in the buffer after parsing.
984 Trailing whitespace and comments are OK. */
985static int // bool
986bad_single_statement(Parser *p)
987{
988 const char *cur = strchr(p->tok->buf, '\n');
989
990 /* Newlines are allowed if preceded by a line continuation character
991 or if they appear inside a string. */
992 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
993 return 0;
994 }
995 char c = *cur;
996
997 for (;;) {
998 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
999 c = *++cur;
1000 }
1001
1002 if (!c) {
1003 return 0;
1004 }
1005
1006 if (c != '#') {
1007 return 1;
1008 }
1009
1010 /* Suck up comment. */
1011 while (c && c != '\n') {
1012 c = *++cur;
1013 }
1014 }
1015}
1016
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001017void
1018_PyPegen_Parser_Free(Parser *p)
1019{
1020 Py_XDECREF(p->normalize);
1021 for (int i = 0; i < p->size; i++) {
1022 PyMem_Free(p->tokens[i]);
1023 }
1024 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -07001025 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001026 PyMem_Free(p);
1027}
1028
Pablo Galindo2b74c832020-04-27 18:02:07 +01001029static int
1030compute_parser_flags(PyCompilerFlags *flags)
1031{
1032 int parser_flags = 0;
1033 if (!flags) {
1034 return 0;
1035 }
1036 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1037 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1038 }
1039 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1040 parser_flags |= PyPARSE_IGNORE_COOKIE;
1041 }
1042 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1043 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1044 }
1045 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1046 parser_flags |= PyPARSE_TYPE_COMMENTS;
1047 }
Guido van Rossum9d197c72020-06-27 17:33:49 -07001048 if ((flags->cf_flags & PyCF_ONLY_AST) && flags->cf_feature_version < 7) {
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001049 parser_flags |= PyPARSE_ASYNC_HACKS;
1050 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001051 return parser_flags;
1052}
1053
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001054Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001055_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001056 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001057{
1058 Parser *p = PyMem_Malloc(sizeof(Parser));
1059 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001060 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001061 }
1062 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001063 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1064 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001065 p->tok = tok;
1066 p->keywords = NULL;
1067 p->n_keyword_lists = -1;
1068 p->tokens = PyMem_Malloc(sizeof(Token *));
1069 if (!p->tokens) {
1070 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001071 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001072 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001073 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001074 if (!p->tokens) {
1075 PyMem_Free(p->tokens);
1076 PyMem_Free(p);
1077 return (Parser *) PyErr_NoMemory();
1078 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001079 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1080 PyMem_Free(p->tokens[0]);
1081 PyMem_Free(p->tokens);
1082 PyMem_Free(p);
1083 return (Parser *) PyErr_NoMemory();
1084 }
1085
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001086 p->mark = 0;
1087 p->fill = 0;
1088 p->size = 1;
1089
1090 p->errcode = errcode;
1091 p->arena = arena;
1092 p->start_rule = start_rule;
1093 p->parsing_started = 0;
1094 p->normalize = NULL;
1095 p->error_indicator = 0;
1096
1097 p->starting_lineno = 0;
1098 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001099 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001100 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001101 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001102 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001103
1104 return p;
1105}
1106
1107void *
1108_PyPegen_run_parser(Parser *p)
1109{
1110 void *res = _PyPegen_parse(p);
1111 if (res == NULL) {
1112 if (PyErr_Occurred()) {
1113 return NULL;
1114 }
1115 if (p->fill == 0) {
1116 RAISE_SYNTAX_ERROR("error at start before reading any input");
1117 }
1118 else if (p->tok->done == E_EOF) {
1119 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1120 }
1121 else {
1122 if (p->tokens[p->fill-1]->type == INDENT) {
1123 RAISE_INDENTATION_ERROR("unexpected indent");
1124 }
1125 else if (p->tokens[p->fill-1]->type == DEDENT) {
1126 RAISE_INDENTATION_ERROR("unexpected unindent");
1127 }
1128 else {
1129 RAISE_SYNTAX_ERROR("invalid syntax");
1130 }
1131 }
1132 return NULL;
1133 }
1134
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001135 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1136 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1137 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1138 }
1139
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001140 return res;
1141}
1142
1143mod_ty
1144_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1145 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001146 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001147{
1148 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1149 if (tok == NULL) {
1150 if (PyErr_Occurred()) {
1151 raise_tokenizer_init_error(filename_ob);
1152 return NULL;
1153 }
1154 return NULL;
1155 }
1156 // This transfers the ownership to the tokenizer
1157 tok->filename = filename_ob;
1158 Py_INCREF(filename_ob);
1159
1160 // From here on we need to clean up even if there's an error
1161 mod_ty result = NULL;
1162
Pablo Galindo2b74c832020-04-27 18:02:07 +01001163 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001164 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1165 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001166 if (p == NULL) {
1167 goto error;
1168 }
1169
1170 result = _PyPegen_run_parser(p);
1171 _PyPegen_Parser_Free(p);
1172
1173error:
1174 PyTokenizer_Free(tok);
1175 return result;
1176}
1177
1178mod_ty
1179_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001180 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001181{
1182 FILE *fp = fopen(filename, "rb");
1183 if (fp == NULL) {
1184 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1185 return NULL;
1186 }
1187
1188 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001189 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001190
1191 fclose(fp);
1192 return result;
1193}
1194
1195mod_ty
1196_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001197 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001198{
1199 int exec_input = start_rule == Py_file_input;
1200
1201 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001202 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001203 tok = PyTokenizer_FromUTF8(str, exec_input);
1204 } else {
1205 tok = PyTokenizer_FromString(str, exec_input);
1206 }
1207 if (tok == NULL) {
1208 if (PyErr_Occurred()) {
1209 raise_tokenizer_init_error(filename_ob);
1210 }
1211 return NULL;
1212 }
1213 // This transfers the ownership to the tokenizer
1214 tok->filename = filename_ob;
1215 Py_INCREF(filename_ob);
1216
1217 // We need to clear up from here on
1218 mod_ty result = NULL;
1219
Pablo Galindo2b74c832020-04-27 18:02:07 +01001220 int parser_flags = compute_parser_flags(flags);
Guido van Rossum9d197c72020-06-27 17:33:49 -07001221 int feature_version = flags && (flags->cf_flags & PyCF_ONLY_AST) ?
1222 flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001223 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1224 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001225 if (p == NULL) {
1226 goto error;
1227 }
1228
1229 result = _PyPegen_run_parser(p);
1230 _PyPegen_Parser_Free(p);
1231
1232error:
1233 PyTokenizer_Free(tok);
1234 return result;
1235}
1236
1237void *
1238_PyPegen_interactive_exit(Parser *p)
1239{
1240 if (p->errcode) {
1241 *(p->errcode) = E_EOF;
1242 }
1243 return NULL;
1244}
1245
1246/* Creates a single-element asdl_seq* that contains a */
1247asdl_seq *
1248_PyPegen_singleton_seq(Parser *p, void *a)
1249{
1250 assert(a != NULL);
1251 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1252 if (!seq) {
1253 return NULL;
1254 }
1255 asdl_seq_SET(seq, 0, a);
1256 return seq;
1257}
1258
1259/* Creates a copy of seq and prepends a to it */
1260asdl_seq *
1261_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1262{
1263 assert(a != NULL);
1264 if (!seq) {
1265 return _PyPegen_singleton_seq(p, a);
1266 }
1267
1268 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1269 if (!new_seq) {
1270 return NULL;
1271 }
1272
1273 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001274 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001275 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1276 }
1277 return new_seq;
1278}
1279
Guido van Rossumc001c092020-04-30 12:12:19 -07001280/* Creates a copy of seq and appends a to it */
1281asdl_seq *
1282_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1283{
1284 assert(a != NULL);
1285 if (!seq) {
1286 return _PyPegen_singleton_seq(p, a);
1287 }
1288
1289 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1290 if (!new_seq) {
1291 return NULL;
1292 }
1293
1294 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1295 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1296 }
1297 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1298 return new_seq;
1299}
1300
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001301static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001302_get_flattened_seq_size(asdl_seq *seqs)
1303{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001304 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001305 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1306 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1307 size += asdl_seq_LEN(inner_seq);
1308 }
1309 return size;
1310}
1311
1312/* Flattens an asdl_seq* of asdl_seq*s */
1313asdl_seq *
1314_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1315{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001316 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001317 assert(flattened_seq_size > 0);
1318
1319 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1320 if (!flattened_seq) {
1321 return NULL;
1322 }
1323
1324 int flattened_seq_idx = 0;
1325 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1326 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001327 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001328 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1329 }
1330 }
1331 assert(flattened_seq_idx == flattened_seq_size);
1332
1333 return flattened_seq;
1334}
1335
1336/* Creates a new name of the form <first_name>.<second_name> */
1337expr_ty
1338_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1339{
1340 assert(first_name != NULL && second_name != NULL);
1341 PyObject *first_identifier = first_name->v.Name.id;
1342 PyObject *second_identifier = second_name->v.Name.id;
1343
1344 if (PyUnicode_READY(first_identifier) == -1) {
1345 return NULL;
1346 }
1347 if (PyUnicode_READY(second_identifier) == -1) {
1348 return NULL;
1349 }
1350 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1351 if (!first_str) {
1352 return NULL;
1353 }
1354 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1355 if (!second_str) {
1356 return NULL;
1357 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001358 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001359
1360 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1361 if (!str) {
1362 return NULL;
1363 }
1364
1365 char *s = PyBytes_AS_STRING(str);
1366 if (!s) {
1367 return NULL;
1368 }
1369
1370 strcpy(s, first_str);
1371 s += strlen(first_str);
1372 *s++ = '.';
1373 strcpy(s, second_str);
1374 s += strlen(second_str);
1375 *s = '\0';
1376
1377 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1378 Py_DECREF(str);
1379 if (!uni) {
1380 return NULL;
1381 }
1382 PyUnicode_InternInPlace(&uni);
1383 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1384 Py_DECREF(uni);
1385 return NULL;
1386 }
1387
1388 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1389}
1390
1391/* Counts the total number of dots in seq's tokens */
1392int
1393_PyPegen_seq_count_dots(asdl_seq *seq)
1394{
1395 int number_of_dots = 0;
1396 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1397 Token *current_expr = asdl_seq_GET(seq, i);
1398 switch (current_expr->type) {
1399 case ELLIPSIS:
1400 number_of_dots += 3;
1401 break;
1402 case DOT:
1403 number_of_dots += 1;
1404 break;
1405 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001406 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001407 }
1408 }
1409
1410 return number_of_dots;
1411}
1412
1413/* Creates an alias with '*' as the identifier name */
1414alias_ty
1415_PyPegen_alias_for_star(Parser *p)
1416{
1417 PyObject *str = PyUnicode_InternFromString("*");
1418 if (!str) {
1419 return NULL;
1420 }
1421 if (PyArena_AddPyObject(p->arena, str) < 0) {
1422 Py_DECREF(str);
1423 return NULL;
1424 }
1425 return alias(str, NULL, p->arena);
1426}
1427
1428/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1429asdl_seq *
1430_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1431{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001432 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001433 assert(len > 0);
1434
1435 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1436 if (!new_seq) {
1437 return NULL;
1438 }
1439 for (Py_ssize_t i = 0; i < len; i++) {
1440 expr_ty e = asdl_seq_GET(seq, i);
1441 asdl_seq_SET(new_seq, i, e->v.Name.id);
1442 }
1443 return new_seq;
1444}
1445
1446/* Constructs a CmpopExprPair */
1447CmpopExprPair *
1448_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1449{
1450 assert(expr != NULL);
1451 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1452 if (!a) {
1453 return NULL;
1454 }
1455 a->cmpop = cmpop;
1456 a->expr = expr;
1457 return a;
1458}
1459
1460asdl_int_seq *
1461_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1462{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001463 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001464 assert(len > 0);
1465
1466 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1467 if (!new_seq) {
1468 return NULL;
1469 }
1470 for (Py_ssize_t i = 0; i < len; i++) {
1471 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1472 asdl_seq_SET(new_seq, i, pair->cmpop);
1473 }
1474 return new_seq;
1475}
1476
1477asdl_seq *
1478_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1479{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001480 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001481 assert(len > 0);
1482
1483 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1484 if (!new_seq) {
1485 return NULL;
1486 }
1487 for (Py_ssize_t i = 0; i < len; i++) {
1488 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1489 asdl_seq_SET(new_seq, i, pair->expr);
1490 }
1491 return new_seq;
1492}
1493
1494/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1495static asdl_seq *
1496_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1497{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001498 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001499 if (len == 0) {
1500 return NULL;
1501 }
1502
1503 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1504 if (!new_seq) {
1505 return NULL;
1506 }
1507 for (Py_ssize_t i = 0; i < len; i++) {
1508 expr_ty e = asdl_seq_GET(seq, i);
1509 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1510 }
1511 return new_seq;
1512}
1513
1514static expr_ty
1515_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1516{
1517 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1518}
1519
1520static expr_ty
1521_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1522{
1523 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1524}
1525
1526static expr_ty
1527_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1528{
1529 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1530}
1531
1532static expr_ty
1533_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1534{
1535 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1536}
1537
1538static expr_ty
1539_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1540{
1541 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1542}
1543
1544static expr_ty
1545_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1546{
1547 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1548}
1549
1550/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1551expr_ty
1552_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1553{
1554 assert(expr != NULL);
1555
1556 expr_ty new = NULL;
1557 switch (expr->kind) {
1558 case Name_kind:
1559 new = _set_name_context(p, expr, ctx);
1560 break;
1561 case Tuple_kind:
1562 new = _set_tuple_context(p, expr, ctx);
1563 break;
1564 case List_kind:
1565 new = _set_list_context(p, expr, ctx);
1566 break;
1567 case Subscript_kind:
1568 new = _set_subscript_context(p, expr, ctx);
1569 break;
1570 case Attribute_kind:
1571 new = _set_attribute_context(p, expr, ctx);
1572 break;
1573 case Starred_kind:
1574 new = _set_starred_context(p, expr, ctx);
1575 break;
1576 default:
1577 new = expr;
1578 }
1579 return new;
1580}
1581
1582/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1583KeyValuePair *
1584_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1585{
1586 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1587 if (!a) {
1588 return NULL;
1589 }
1590 a->key = key;
1591 a->value = value;
1592 return a;
1593}
1594
1595/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1596asdl_seq *
1597_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1598{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001599 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001600 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1601 if (!new_seq) {
1602 return NULL;
1603 }
1604 for (Py_ssize_t i = 0; i < len; i++) {
1605 KeyValuePair *pair = asdl_seq_GET(seq, i);
1606 asdl_seq_SET(new_seq, i, pair->key);
1607 }
1608 return new_seq;
1609}
1610
1611/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1612asdl_seq *
1613_PyPegen_get_values(Parser *p, asdl_seq *seq)
1614{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001615 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001616 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1617 if (!new_seq) {
1618 return NULL;
1619 }
1620 for (Py_ssize_t i = 0; i < len; i++) {
1621 KeyValuePair *pair = asdl_seq_GET(seq, i);
1622 asdl_seq_SET(new_seq, i, pair->value);
1623 }
1624 return new_seq;
1625}
1626
1627/* Constructs a NameDefaultPair */
1628NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001629_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001630{
1631 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1632 if (!a) {
1633 return NULL;
1634 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001635 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001636 a->value = value;
1637 return a;
1638}
1639
1640/* Constructs a SlashWithDefault */
1641SlashWithDefault *
1642_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1643{
1644 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1645 if (!a) {
1646 return NULL;
1647 }
1648 a->plain_names = plain_names;
1649 a->names_with_defaults = names_with_defaults;
1650 return a;
1651}
1652
1653/* Constructs a StarEtc */
1654StarEtc *
1655_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1656{
1657 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1658 if (!a) {
1659 return NULL;
1660 }
1661 a->vararg = vararg;
1662 a->kwonlyargs = kwonlyargs;
1663 a->kwarg = kwarg;
1664 return a;
1665}
1666
1667asdl_seq *
1668_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1669{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001670 Py_ssize_t first_len = asdl_seq_LEN(a);
1671 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001672 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1673 if (!new_seq) {
1674 return NULL;
1675 }
1676
1677 int k = 0;
1678 for (Py_ssize_t i = 0; i < first_len; i++) {
1679 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1680 }
1681 for (Py_ssize_t i = 0; i < second_len; i++) {
1682 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1683 }
1684
1685 return new_seq;
1686}
1687
1688static asdl_seq *
1689_get_names(Parser *p, asdl_seq *names_with_defaults)
1690{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001691 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001692 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1693 if (!seq) {
1694 return NULL;
1695 }
1696 for (Py_ssize_t i = 0; i < len; i++) {
1697 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1698 asdl_seq_SET(seq, i, pair->arg);
1699 }
1700 return seq;
1701}
1702
1703static asdl_seq *
1704_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1705{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001706 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001707 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1708 if (!seq) {
1709 return NULL;
1710 }
1711 for (Py_ssize_t i = 0; i < len; i++) {
1712 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1713 asdl_seq_SET(seq, i, pair->value);
1714 }
1715 return seq;
1716}
1717
1718/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1719arguments_ty
1720_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1721 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1722 asdl_seq *names_with_default, StarEtc *star_etc)
1723{
1724 asdl_seq *posonlyargs;
1725 if (slash_without_default != NULL) {
1726 posonlyargs = slash_without_default;
1727 }
1728 else if (slash_with_default != NULL) {
1729 asdl_seq *slash_with_default_names =
1730 _get_names(p, slash_with_default->names_with_defaults);
1731 if (!slash_with_default_names) {
1732 return NULL;
1733 }
1734 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1735 if (!posonlyargs) {
1736 return NULL;
1737 }
1738 }
1739 else {
1740 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1741 if (!posonlyargs) {
1742 return NULL;
1743 }
1744 }
1745
1746 asdl_seq *posargs;
1747 if (plain_names != NULL && names_with_default != NULL) {
1748 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1749 if (!names_with_default_names) {
1750 return NULL;
1751 }
1752 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1753 if (!posargs) {
1754 return NULL;
1755 }
1756 }
1757 else if (plain_names == NULL && names_with_default != NULL) {
1758 posargs = _get_names(p, names_with_default);
1759 if (!posargs) {
1760 return NULL;
1761 }
1762 }
1763 else if (plain_names != NULL && names_with_default == NULL) {
1764 posargs = plain_names;
1765 }
1766 else {
1767 posargs = _Py_asdl_seq_new(0, p->arena);
1768 if (!posargs) {
1769 return NULL;
1770 }
1771 }
1772
1773 asdl_seq *posdefaults;
1774 if (slash_with_default != NULL && names_with_default != NULL) {
1775 asdl_seq *slash_with_default_values =
1776 _get_defaults(p, slash_with_default->names_with_defaults);
1777 if (!slash_with_default_values) {
1778 return NULL;
1779 }
1780 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1781 if (!names_with_default_values) {
1782 return NULL;
1783 }
1784 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1785 if (!posdefaults) {
1786 return NULL;
1787 }
1788 }
1789 else if (slash_with_default == NULL && names_with_default != NULL) {
1790 posdefaults = _get_defaults(p, names_with_default);
1791 if (!posdefaults) {
1792 return NULL;
1793 }
1794 }
1795 else if (slash_with_default != NULL && names_with_default == NULL) {
1796 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1797 if (!posdefaults) {
1798 return NULL;
1799 }
1800 }
1801 else {
1802 posdefaults = _Py_asdl_seq_new(0, p->arena);
1803 if (!posdefaults) {
1804 return NULL;
1805 }
1806 }
1807
1808 arg_ty vararg = NULL;
1809 if (star_etc != NULL && star_etc->vararg != NULL) {
1810 vararg = star_etc->vararg;
1811 }
1812
1813 asdl_seq *kwonlyargs;
1814 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1815 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1816 if (!kwonlyargs) {
1817 return NULL;
1818 }
1819 }
1820 else {
1821 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1822 if (!kwonlyargs) {
1823 return NULL;
1824 }
1825 }
1826
1827 asdl_seq *kwdefaults;
1828 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1829 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1830 if (!kwdefaults) {
1831 return NULL;
1832 }
1833 }
1834 else {
1835 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1836 if (!kwdefaults) {
1837 return NULL;
1838 }
1839 }
1840
1841 arg_ty kwarg = NULL;
1842 if (star_etc != NULL && star_etc->kwarg != NULL) {
1843 kwarg = star_etc->kwarg;
1844 }
1845
1846 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1847 posdefaults, p->arena);
1848}
1849
1850/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1851 * arguments. */
1852arguments_ty
1853_PyPegen_empty_arguments(Parser *p)
1854{
1855 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1856 if (!posonlyargs) {
1857 return NULL;
1858 }
1859 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1860 if (!posargs) {
1861 return NULL;
1862 }
1863 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1864 if (!posdefaults) {
1865 return NULL;
1866 }
1867 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1868 if (!kwonlyargs) {
1869 return NULL;
1870 }
1871 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1872 if (!kwdefaults) {
1873 return NULL;
1874 }
1875
1876 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1877 p->arena);
1878}
1879
1880/* Encapsulates the value of an operator_ty into an AugOperator struct */
1881AugOperator *
1882_PyPegen_augoperator(Parser *p, operator_ty kind)
1883{
1884 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1885 if (!a) {
1886 return NULL;
1887 }
1888 a->kind = kind;
1889 return a;
1890}
1891
1892/* Construct a FunctionDef equivalent to function_def, but with decorators */
1893stmt_ty
1894_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1895{
1896 assert(function_def != NULL);
1897 if (function_def->kind == AsyncFunctionDef_kind) {
1898 return _Py_AsyncFunctionDef(
1899 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1900 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1901 function_def->v.FunctionDef.type_comment, function_def->lineno,
1902 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1903 p->arena);
1904 }
1905
1906 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1907 function_def->v.FunctionDef.body, decorators,
1908 function_def->v.FunctionDef.returns,
1909 function_def->v.FunctionDef.type_comment, function_def->lineno,
1910 function_def->col_offset, function_def->end_lineno,
1911 function_def->end_col_offset, p->arena);
1912}
1913
1914/* Construct a ClassDef equivalent to class_def, but with decorators */
1915stmt_ty
1916_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1917{
1918 assert(class_def != NULL);
1919 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1920 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1921 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1922 class_def->end_col_offset, p->arena);
1923}
1924
1925/* Construct a KeywordOrStarred */
1926KeywordOrStarred *
1927_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1928{
1929 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1930 if (!a) {
1931 return NULL;
1932 }
1933 a->element = element;
1934 a->is_keyword = is_keyword;
1935 return a;
1936}
1937
1938/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1939static int
1940_seq_number_of_starred_exprs(asdl_seq *seq)
1941{
1942 int n = 0;
1943 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1944 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1945 if (!k->is_keyword) {
1946 n++;
1947 }
1948 }
1949 return n;
1950}
1951
1952/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1953asdl_seq *
1954_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1955{
1956 int new_len = _seq_number_of_starred_exprs(kwargs);
1957 if (new_len == 0) {
1958 return NULL;
1959 }
1960 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1961 if (!new_seq) {
1962 return NULL;
1963 }
1964
1965 int idx = 0;
1966 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1967 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1968 if (!k->is_keyword) {
1969 asdl_seq_SET(new_seq, idx++, k->element);
1970 }
1971 }
1972 return new_seq;
1973}
1974
1975/* Return a new asdl_seq* with only the keywords in kwargs */
1976asdl_seq *
1977_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1978{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001979 Py_ssize_t len = asdl_seq_LEN(kwargs);
1980 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001981 if (new_len == 0) {
1982 return NULL;
1983 }
1984 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1985 if (!new_seq) {
1986 return NULL;
1987 }
1988
1989 int idx = 0;
1990 for (Py_ssize_t i = 0; i < len; i++) {
1991 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1992 if (k->is_keyword) {
1993 asdl_seq_SET(new_seq, idx++, k->element);
1994 }
1995 }
1996 return new_seq;
1997}
1998
1999expr_ty
2000_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
2001{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002002 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002003 assert(len > 0);
2004
2005 Token *first = asdl_seq_GET(strings, 0);
2006 Token *last = asdl_seq_GET(strings, len - 1);
2007
2008 int bytesmode = 0;
2009 PyObject *bytes_str = NULL;
2010
2011 FstringParser state;
2012 _PyPegen_FstringParser_Init(&state);
2013
2014 for (Py_ssize_t i = 0; i < len; i++) {
2015 Token *t = asdl_seq_GET(strings, i);
2016
2017 int this_bytesmode;
2018 int this_rawmode;
2019 PyObject *s;
2020 const char *fstr;
2021 Py_ssize_t fstrlen = -1;
2022
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03002023 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002024 goto error;
2025 }
2026
2027 /* Check that we are not mixing bytes with unicode. */
2028 if (i != 0 && bytesmode != this_bytesmode) {
2029 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2030 Py_XDECREF(s);
2031 goto error;
2032 }
2033 bytesmode = this_bytesmode;
2034
2035 if (fstr != NULL) {
2036 assert(s == NULL && !bytesmode);
2037
2038 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2039 this_rawmode, 0, first, t, last);
2040 if (result < 0) {
2041 goto error;
2042 }
2043 }
2044 else {
2045 /* String or byte string. */
2046 assert(s != NULL && fstr == NULL);
2047 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2048
2049 if (bytesmode) {
2050 if (i == 0) {
2051 bytes_str = s;
2052 }
2053 else {
2054 PyBytes_ConcatAndDel(&bytes_str, s);
2055 if (!bytes_str) {
2056 goto error;
2057 }
2058 }
2059 }
2060 else {
2061 /* This is a regular string. Concatenate it. */
2062 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2063 goto error;
2064 }
2065 }
2066 }
2067 }
2068
2069 if (bytesmode) {
2070 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2071 goto error;
2072 }
2073 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2074 last->end_col_offset, p->arena);
2075 }
2076
2077 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2078
2079error:
2080 Py_XDECREF(bytes_str);
2081 _PyPegen_FstringParser_Dealloc(&state);
2082 if (PyErr_Occurred()) {
2083 raise_decode_error(p);
2084 }
2085 return NULL;
2086}
Guido van Rossumc001c092020-04-30 12:12:19 -07002087
2088mod_ty
2089_PyPegen_make_module(Parser *p, asdl_seq *a) {
2090 asdl_seq *type_ignores = NULL;
2091 Py_ssize_t num = p->type_ignore_comments.num_items;
2092 if (num > 0) {
2093 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2094 type_ignores = _Py_asdl_seq_new(num, p->arena);
2095 if (type_ignores == NULL) {
2096 return NULL;
2097 }
2098 for (int i = 0; i < num; i++) {
2099 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2100 if (tag == NULL) {
2101 return NULL;
2102 }
2103 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2104 if (ti == NULL) {
2105 return NULL;
2106 }
2107 asdl_seq_SET(type_ignores, i, ti);
2108 }
2109 }
2110 return Module(a, type_ignores, p->arena);
2111}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002112
2113// Error reporting helpers
2114
2115expr_ty
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002116_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
Pablo Galindo16ab0702020-05-15 02:04:52 +01002117{
2118 if (e == NULL) {
2119 return NULL;
2120 }
2121
2122#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2123 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2124 for (Py_ssize_t i = 0; i < len; i++) {\
2125 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002126 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
Pablo Galindo16ab0702020-05-15 02:04:52 +01002127 if (child != NULL) {\
2128 return child;\
2129 }\
2130 }\
2131 } while (0)
2132
2133 // We only need to visit List and Tuple nodes recursively as those
2134 // are the only ones that can contain valid names in targets when
2135 // they are parsed as expressions. Any other kind of expression
2136 // that is a container (like Sets or Dicts) is directly invalid and
2137 // we don't need to visit it recursively.
2138
2139 switch (e->kind) {
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002140 case List_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002141 VISIT_CONTAINER(e, List);
2142 return NULL;
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002143 case Tuple_kind:
Pablo Galindo16ab0702020-05-15 02:04:52 +01002144 VISIT_CONTAINER(e, Tuple);
2145 return NULL;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002146 case Starred_kind:
Lysandros Nikolaou01ece632020-06-19 02:10:43 +03002147 if (targets_type == DEL_TARGETS) {
2148 return e;
2149 }
2150 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
2151 case Compare_kind:
2152 // This is needed, because the `a in b` in `for a in b` gets parsed
2153 // as a comparison, and so we need to search the left side of the comparison
2154 // for invalid targets.
2155 if (targets_type == FOR_TARGETS) {
2156 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
2157 if (cmpop == In) {
2158 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
2159 }
2160 return NULL;
2161 }
2162 return e;
Pablo Galindo16ab0702020-05-15 02:04:52 +01002163 case Name_kind:
2164 case Subscript_kind:
2165 case Attribute_kind:
2166 return NULL;
2167 default:
2168 return e;
2169 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002170}
2171
2172void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2173 int kwarg_unpacking = 0;
2174 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2175 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2176 if (!keyword->arg) {
2177 kwarg_unpacking = 1;
2178 }
2179 }
2180
2181 const char *msg = NULL;
2182 if (kwarg_unpacking) {
2183 msg = "positional argument follows keyword argument unpacking";
2184 } else {
2185 msg = "positional argument follows keyword argument";
2186 }
2187
2188 return RAISE_SYNTAX_ERROR(msg);
2189}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002190
2191void *
2192_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2193{
2194 /* The rule that calls this function is 'args for_if_clauses'.
2195 For the input f(L, x for x in y), L and x are in args and
2196 the for is parsed as a for_if_clause. We have to check if
2197 len <= 1, so that input like dict((a, b) for a, b in x)
2198 gets successfully parsed and then we pass the last
2199 argument (x in the above example) as the location of the
2200 error */
2201 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2202 if (len <= 1) {
2203 return NULL;
2204 }
2205
2206 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2207 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2208 "Generator expression must be parenthesized"
2209 );
2210}