blob: b858b6b9d3854545b363a43db58abbe71a614283 [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
3#include "../tokenizer.h"
4
5#include "pegen.h"
6#include "parse_string.h"
7
Guido van Rossumc001c092020-04-30 12:12:19 -07008PyObject *
9_PyPegen_new_type_comment(Parser *p, char *s)
10{
11 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
12 if (res == NULL) {
13 return NULL;
14 }
15 if (PyArena_AddPyObject(p->arena, res) < 0) {
16 Py_DECREF(res);
17 return NULL;
18 }
19 return res;
20}
21
22arg_ty
23_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
24{
25 if (tc == NULL) {
26 return a;
27 }
28 char *bytes = PyBytes_AsString(tc->bytes);
29 if (bytes == NULL) {
30 return NULL;
31 }
32 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
33 if (tco == NULL) {
34 return NULL;
35 }
36 return arg(a->arg, a->annotation, tco,
37 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
38 p->arena);
39}
40
Pablo Galindoc5fc1562020-04-22 23:29:27 +010041static int
42init_normalization(Parser *p)
43{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030044 if (p->normalize) {
45 return 1;
46 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010047 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
48 if (!m)
49 {
50 return 0;
51 }
52 p->normalize = PyObject_GetAttrString(m, "normalize");
53 Py_DECREF(m);
54 if (!p->normalize)
55 {
56 return 0;
57 }
58 return 1;
59}
60
Pablo Galindo2b74c832020-04-27 18:02:07 +010061/* Checks if the NOTEQUAL token is valid given the current parser flags
620 indicates success and nonzero indicates failure (an exception may be set) */
63int
64_PyPegen_check_barry_as_flufl(Parser *p) {
65 Token *t = p->tokens[p->fill - 1];
66 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
70 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>")){
71 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
73 } else if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
74 return strcmp(tok_str, "!=");
75 }
76 return 0;
77}
78
Pablo Galindoc5fc1562020-04-22 23:29:27 +010079PyObject *
80_PyPegen_new_identifier(Parser *p, char *n)
81{
82 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
83 if (!id) {
84 goto error;
85 }
86 /* PyUnicode_DecodeUTF8 should always return a ready string. */
87 assert(PyUnicode_IS_READY(id));
88 /* Check whether there are non-ASCII characters in the
89 identifier; if so, normalize to NFKC. */
90 if (!PyUnicode_IS_ASCII(id))
91 {
92 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030093 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010094 {
95 Py_DECREF(id);
96 goto error;
97 }
98 PyObject *form = PyUnicode_InternFromString("NFKC");
99 if (form == NULL)
100 {
101 Py_DECREF(id);
102 goto error;
103 }
104 PyObject *args[2] = {form, id};
105 id2 = _PyObject_FastCall(p->normalize, args, 2);
106 Py_DECREF(id);
107 Py_DECREF(form);
108 if (!id2) {
109 goto error;
110 }
111 if (!PyUnicode_Check(id2))
112 {
113 PyErr_Format(PyExc_TypeError,
114 "unicodedata.normalize() must return a string, not "
115 "%.200s",
116 _PyType_Name(Py_TYPE(id2)));
117 Py_DECREF(id2);
118 goto error;
119 }
120 id = id2;
121 }
122 PyUnicode_InternInPlace(&id);
123 if (PyArena_AddPyObject(p->arena, id) < 0)
124 {
125 Py_DECREF(id);
126 goto error;
127 }
128 return id;
129
130error:
131 p->error_indicator = 1;
132 return NULL;
133}
134
135static PyObject *
136_create_dummy_identifier(Parser *p)
137{
138 return _PyPegen_new_identifier(p, "");
139}
140
141static inline Py_ssize_t
142byte_offset_to_character_offset(PyObject *line, int col_offset)
143{
144 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300145 if (!str) {
146 return 0;
147 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300148 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100149 if (!text) {
150 return 0;
151 }
152 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300153 str = PyUnicode_AsUTF8(text);
154 if (str != NULL && (int)strlen(str) == col_offset) {
155 size = strlen(str);
156 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100157 Py_DECREF(text);
158 return size;
159}
160
161const char *
162_PyPegen_get_expr_name(expr_ty e)
163{
164 switch (e->kind) {
165 case Attribute_kind:
166 return "attribute";
167 case Subscript_kind:
168 return "subscript";
169 case Starred_kind:
170 return "starred";
171 case Name_kind:
172 return "name";
173 case List_kind:
174 return "list";
175 case Tuple_kind:
176 return "tuple";
177 case Lambda_kind:
178 return "lambda";
179 case Call_kind:
180 return "function call";
181 case BoolOp_kind:
182 case BinOp_kind:
183 case UnaryOp_kind:
184 return "operator";
185 case GeneratorExp_kind:
186 return "generator expression";
187 case Yield_kind:
188 case YieldFrom_kind:
189 return "yield expression";
190 case Await_kind:
191 return "await expression";
192 case ListComp_kind:
193 return "list comprehension";
194 case SetComp_kind:
195 return "set comprehension";
196 case DictComp_kind:
197 return "dict comprehension";
198 case Dict_kind:
199 return "dict display";
200 case Set_kind:
201 return "set display";
202 case JoinedStr_kind:
203 case FormattedValue_kind:
204 return "f-string expression";
205 case Constant_kind: {
206 PyObject *value = e->v.Constant.value;
207 if (value == Py_None) {
208 return "None";
209 }
210 if (value == Py_False) {
211 return "False";
212 }
213 if (value == Py_True) {
214 return "True";
215 }
216 if (value == Py_Ellipsis) {
217 return "Ellipsis";
218 }
219 return "literal";
220 }
221 case Compare_kind:
222 return "comparison";
223 case IfExp_kind:
224 return "conditional expression";
225 case NamedExpr_kind:
226 return "named expression";
227 default:
228 PyErr_Format(PyExc_SystemError,
229 "unexpected expression in assignment %d (line %d)",
230 e->kind, e->lineno);
231 return NULL;
232 }
233}
234
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300235static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100236raise_decode_error(Parser *p)
237{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300238 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100239 const char *errtype = NULL;
240 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
241 errtype = "unicode error";
242 }
243 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
244 errtype = "value error";
245 }
246 if (errtype) {
247 PyObject *type, *value, *tback, *errstr;
248 PyErr_Fetch(&type, &value, &tback);
249 errstr = PyObject_Str(value);
250 if (errstr) {
251 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
252 Py_DECREF(errstr);
253 }
254 else {
255 PyErr_Clear();
256 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
257 }
258 Py_XDECREF(type);
259 Py_XDECREF(value);
260 Py_XDECREF(tback);
261 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300262
263 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100264}
265
266static void
267raise_tokenizer_init_error(PyObject *filename)
268{
269 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
270 || PyErr_ExceptionMatches(PyExc_ValueError)
271 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
272 return;
273 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300274 PyObject *errstr = NULL;
275 PyObject *tuple = NULL;
276 PyObject *type, *value, *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100277 PyErr_Fetch(&type, &value, &tback);
278 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300279 if (!errstr) {
280 goto error;
281 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100282
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300283 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100284 if (!tmp) {
285 goto error;
286 }
287
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300288 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100289 Py_DECREF(tmp);
290 if (!value) {
291 goto error;
292 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300293 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100294
295error:
296 Py_XDECREF(type);
297 Py_XDECREF(value);
298 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300299 Py_XDECREF(errstr);
300 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100301}
302
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100303static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100304tokenizer_error(Parser *p)
305{
306 if (PyErr_Occurred()) {
307 return -1;
308 }
309
310 const char *msg = NULL;
311 PyObject* errtype = PyExc_SyntaxError;
312 switch (p->tok->done) {
313 case E_TOKEN:
314 msg = "invalid token";
315 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100316 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300317 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
318 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100319 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300320 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
321 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300322 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300323 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
324 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100325 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300326 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
327 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100328 case E_INTR:
329 if (!PyErr_Occurred()) {
330 PyErr_SetNone(PyExc_KeyboardInterrupt);
331 }
332 return -1;
333 case E_NOMEM:
334 PyErr_NoMemory();
335 return -1;
336 case E_TABSPACE:
337 errtype = PyExc_TabError;
338 msg = "inconsistent use of tabs and spaces in indentation";
339 break;
340 case E_TOODEEP:
341 errtype = PyExc_IndentationError;
342 msg = "too many levels of indentation";
343 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100344 case E_LINECONT:
345 msg = "unexpected character after line continuation character";
346 break;
347 default:
348 msg = "unknown parsing error";
349 }
350
351 PyErr_Format(errtype, msg);
352 // There is no reliable column information for this error
353 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
354
355 return -1;
356}
357
358void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300359_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
360{
361 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
362 int col_offset;
363 if (t->col_offset == -1) {
364 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
365 intptr_t, int);
366 } else {
367 col_offset = t->col_offset + 1;
368 }
369
370 va_list va;
371 va_start(va, errmsg);
372 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
373 col_offset, errmsg, va);
374 va_end(va);
375
376 return NULL;
377}
378
379
380void *
381_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
382 int lineno, int col_offset,
383 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100384{
385 PyObject *value = NULL;
386 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300387 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100388 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300389 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100390
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100392 if (!errstr) {
393 goto error;
394 }
395
396 if (p->start_rule == Py_file_input) {
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300397 error_line = PyErr_ProgramTextObject(p->tok->filename, lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100398 }
399
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300400 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100401 Py_ssize_t size = p->tok->inp - p->tok->buf;
402 if (size && p->tok->buf[size-1] == '\n') {
403 size--;
404 }
405 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300406 if (!error_line) {
407 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300408 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100409 }
410
Miss Islington (bot)11fb6052020-05-23 22:20:44 -0700411 Py_ssize_t col_number = byte_offset_to_character_offset(error_line, col_offset);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300412
413 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100414 if (!tmp) {
415 goto error;
416 }
417 value = PyTuple_Pack(2, errstr, tmp);
418 Py_DECREF(tmp);
419 if (!value) {
420 goto error;
421 }
422 PyErr_SetObject(errtype, value);
423
424 Py_DECREF(errstr);
425 Py_DECREF(value);
426 return NULL;
427
428error:
429 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300430 Py_XDECREF(error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100431 return NULL;
432}
433
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100434#if 0
435static const char *
436token_name(int type)
437{
438 if (0 <= type && type <= N_TOKENS) {
439 return _PyParser_TokenNames[type];
440 }
441 return "<Huh?>";
442}
443#endif
444
445// Here, mark is the start of the node, while p->mark is the end.
446// If node==NULL, they should be the same.
447int
448_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
449{
450 // Insert in front
451 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
452 if (m == NULL) {
453 return -1;
454 }
455 m->type = type;
456 m->node = node;
457 m->mark = p->mark;
458 m->next = p->tokens[mark]->memo;
459 p->tokens[mark]->memo = m;
460 return 0;
461}
462
463// Like _PyPegen_insert_memo(), but updates an existing node if found.
464int
465_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
466{
467 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
468 if (m->type == type) {
469 // Update existing node.
470 m->node = node;
471 m->mark = p->mark;
472 return 0;
473 }
474 }
475 // Insert new node.
476 return _PyPegen_insert_memo(p, mark, type, node);
477}
478
479// Return dummy NAME.
480void *
481_PyPegen_dummy_name(Parser *p, ...)
482{
483 static void *cache = NULL;
484
485 if (cache != NULL) {
486 return cache;
487 }
488
489 PyObject *id = _create_dummy_identifier(p);
490 if (!id) {
491 return NULL;
492 }
493 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
494 return cache;
495}
496
497static int
498_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
499{
500 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
501 return NAME;
502 }
503 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
504 if (strncmp(k->str, name, name_len) == 0) {
505 return k->type;
506 }
507 }
508 return NAME;
509}
510
Guido van Rossumc001c092020-04-30 12:12:19 -0700511static int
512growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
513 assert(initial_size > 0);
514 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
515 arr->size = initial_size;
516 arr->num_items = 0;
517
518 return arr->items != NULL;
519}
520
521static int
522growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
523 if (arr->num_items >= arr->size) {
524 size_t new_size = arr->size * 2;
525 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
526 if (!new_items_array) {
527 return 0;
528 }
529 arr->items = new_items_array;
530 arr->size = new_size;
531 }
532
533 arr->items[arr->num_items].lineno = lineno;
534 arr->items[arr->num_items].comment = comment; // Take ownership
535 arr->num_items++;
536 return 1;
537}
538
539static void
540growable_comment_array_deallocate(growable_comment_array *arr) {
541 for (unsigned i = 0; i < arr->num_items; i++) {
542 PyMem_Free(arr->items[i].comment);
543 }
544 PyMem_Free(arr->items);
545}
546
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100547int
548_PyPegen_fill_token(Parser *p)
549{
550 const char *start, *end;
551 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700552
553 // Record and skip '# type: ignore' comments
554 while (type == TYPE_IGNORE) {
555 Py_ssize_t len = end - start;
556 char *tag = PyMem_Malloc(len + 1);
557 if (tag == NULL) {
558 PyErr_NoMemory();
559 return -1;
560 }
561 strncpy(tag, start, len);
562 tag[len] = '\0';
563 // Ownership of tag passes to the growable array
564 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
565 PyErr_NoMemory();
566 return -1;
567 }
568 type = PyTokenizer_Get(p->tok, &start, &end);
569 }
570
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100571 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
572 type = NEWLINE; /* Add an extra newline */
573 p->parsing_started = 0;
574
Pablo Galindob94dbd72020-04-27 18:35:58 +0100575 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100576 p->tok->pendin = -p->tok->indent;
577 p->tok->indent = 0;
578 }
579 }
580 else {
581 p->parsing_started = 1;
582 }
583
584 if (p->fill == p->size) {
585 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300586 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
587 if (new_tokens == NULL) {
588 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100589 return -1;
590 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300591 else {
592 p->tokens = new_tokens;
593 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100594 for (int i = p->size; i < newsize; i++) {
595 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300596 if (p->tokens[i] == NULL) {
597 p->size = i; // Needed, in order to cleanup correctly after parser fails
598 PyErr_NoMemory();
599 return -1;
600 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100601 memset(p->tokens[i], '\0', sizeof(Token));
602 }
603 p->size = newsize;
604 }
605
606 Token *t = p->tokens[p->fill];
607 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
608 t->bytes = PyBytes_FromStringAndSize(start, end - start);
609 if (t->bytes == NULL) {
610 return -1;
611 }
612 PyArena_AddPyObject(p->arena, t->bytes);
613
614 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
615 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100616 int end_lineno = p->tok->lineno;
617 int col_offset = -1, end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100618 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100619 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100620 }
621 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100622 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100623 }
624
625 t->lineno = p->starting_lineno + lineno;
626 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
627 t->end_lineno = p->starting_lineno + end_lineno;
628 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
629
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100630 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300631
632 if (type == ERRORTOKEN) {
633 if (p->tok->done == E_DECODE) {
634 return raise_decode_error(p);
635 }
636 else {
637 return tokenizer_error(p);
638 }
639 }
640
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100641 return 0;
642}
643
644// Instrumentation to count the effectiveness of memoization.
645// The array counts the number of tokens skipped by memoization,
646// indexed by type.
647
648#define NSTATISTICS 2000
649static long memo_statistics[NSTATISTICS];
650
651void
652_PyPegen_clear_memo_statistics()
653{
654 for (int i = 0; i < NSTATISTICS; i++) {
655 memo_statistics[i] = 0;
656 }
657}
658
659PyObject *
660_PyPegen_get_memo_statistics()
661{
662 PyObject *ret = PyList_New(NSTATISTICS);
663 if (ret == NULL) {
664 return NULL;
665 }
666 for (int i = 0; i < NSTATISTICS; i++) {
667 PyObject *value = PyLong_FromLong(memo_statistics[i]);
668 if (value == NULL) {
669 Py_DECREF(ret);
670 return NULL;
671 }
672 // PyList_SetItem borrows a reference to value.
673 if (PyList_SetItem(ret, i, value) < 0) {
674 Py_DECREF(ret);
675 return NULL;
676 }
677 }
678 return ret;
679}
680
681int // bool
682_PyPegen_is_memoized(Parser *p, int type, void *pres)
683{
684 if (p->mark == p->fill) {
685 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300686 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100687 return -1;
688 }
689 }
690
691 Token *t = p->tokens[p->mark];
692
693 for (Memo *m = t->memo; m != NULL; m = m->next) {
694 if (m->type == type) {
695 if (0 <= type && type < NSTATISTICS) {
696 long count = m->mark - p->mark;
697 // A memoized negative result counts for one.
698 if (count <= 0) {
699 count = 1;
700 }
701 memo_statistics[type] += count;
702 }
703 p->mark = m->mark;
704 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100705 return 1;
706 }
707 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100708 return 0;
709}
710
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100711int
712_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
713{
714 int mark = p->mark;
715 void *res = func(p);
716 p->mark = mark;
717 return (res != NULL) == positive;
718}
719
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100720int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300721_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
722{
723 int mark = p->mark;
724 void *res = func(p, arg);
725 p->mark = mark;
726 return (res != NULL) == positive;
727}
728
729int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100730_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
731{
732 int mark = p->mark;
733 void *res = func(p, arg);
734 p->mark = mark;
735 return (res != NULL) == positive;
736}
737
738int
739_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
740{
741 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100742 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100743 p->mark = mark;
744 return (res != NULL) == positive;
745}
746
747Token *
748_PyPegen_expect_token(Parser *p, int type)
749{
750 if (p->mark == p->fill) {
751 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300752 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100753 return NULL;
754 }
755 }
756 Token *t = p->tokens[p->mark];
757 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100758 return NULL;
759 }
760 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100761 return t;
762}
763
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300764expr_ty
765_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
766{
767 if (p->mark == p->fill) {
768 if (_PyPegen_fill_token(p) < 0) {
769 p->error_indicator = 1;
770 return NULL;
771 }
772 }
773 Token *t = p->tokens[p->mark];
774 if (t->type != NAME) {
775 return NULL;
776 }
777 char* s = PyBytes_AsString(t->bytes);
778 if (!s) {
779 p->error_indicator = 1;
780 return NULL;
781 }
782 if (strcmp(s, keyword) != 0) {
783 return NULL;
784 }
785 return _PyPegen_name_token(p);
786}
787
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100788Token *
789_PyPegen_get_last_nonnwhitespace_token(Parser *p)
790{
791 assert(p->mark >= 0);
792 Token *token = NULL;
793 for (int m = p->mark - 1; m >= 0; m--) {
794 token = p->tokens[m];
795 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
796 break;
797 }
798 }
799 return token;
800}
801
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100802expr_ty
803_PyPegen_name_token(Parser *p)
804{
805 Token *t = _PyPegen_expect_token(p, NAME);
806 if (t == NULL) {
807 return NULL;
808 }
809 char* s = PyBytes_AsString(t->bytes);
810 if (!s) {
811 return NULL;
812 }
813 PyObject *id = _PyPegen_new_identifier(p, s);
814 if (id == NULL) {
815 return NULL;
816 }
817 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
818 p->arena);
819}
820
821void *
822_PyPegen_string_token(Parser *p)
823{
824 return _PyPegen_expect_token(p, STRING);
825}
826
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100827static PyObject *
828parsenumber_raw(const char *s)
829{
830 const char *end;
831 long x;
832 double dx;
833 Py_complex compl;
834 int imflag;
835
836 assert(s != NULL);
837 errno = 0;
838 end = s + strlen(s) - 1;
839 imflag = *end == 'j' || *end == 'J';
840 if (s[0] == '0') {
841 x = (long)PyOS_strtoul(s, (char **)&end, 0);
842 if (x < 0 && errno == 0) {
843 return PyLong_FromString(s, (char **)0, 0);
844 }
845 }
846 else
847 x = PyOS_strtol(s, (char **)&end, 0);
848 if (*end == '\0') {
849 if (errno != 0)
850 return PyLong_FromString(s, (char **)0, 0);
851 return PyLong_FromLong(x);
852 }
853 /* XXX Huge floats may silently fail */
854 if (imflag) {
855 compl.real = 0.;
856 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
857 if (compl.imag == -1.0 && PyErr_Occurred())
858 return NULL;
859 return PyComplex_FromCComplex(compl);
860 }
861 else {
862 dx = PyOS_string_to_double(s, NULL, NULL);
863 if (dx == -1.0 && PyErr_Occurred())
864 return NULL;
865 return PyFloat_FromDouble(dx);
866 }
867}
868
869static PyObject *
870parsenumber(const char *s)
871{
872 char *dup, *end;
873 PyObject *res = NULL;
874
875 assert(s != NULL);
876
877 if (strchr(s, '_') == NULL) {
878 return parsenumber_raw(s);
879 }
880 /* Create a duplicate without underscores. */
881 dup = PyMem_Malloc(strlen(s) + 1);
882 if (dup == NULL) {
883 return PyErr_NoMemory();
884 }
885 end = dup;
886 for (; *s; s++) {
887 if (*s != '_') {
888 *end++ = *s;
889 }
890 }
891 *end = '\0';
892 res = parsenumber_raw(dup);
893 PyMem_Free(dup);
894 return res;
895}
896
897expr_ty
898_PyPegen_number_token(Parser *p)
899{
900 Token *t = _PyPegen_expect_token(p, NUMBER);
901 if (t == NULL) {
902 return NULL;
903 }
904
905 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100906 if (num_raw == NULL) {
907 return NULL;
908 }
909
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300910 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
911 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700912 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300913 "in Python 3.6 and greater");
914 }
915
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100916 PyObject *c = parsenumber(num_raw);
917
918 if (c == NULL) {
919 return NULL;
920 }
921
922 if (PyArena_AddPyObject(p->arena, c) < 0) {
923 Py_DECREF(c);
924 return NULL;
925 }
926
927 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
928 p->arena);
929}
930
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300931static int // bool
932newline_in_string(Parser *p, const char *cur)
933{
934 for (char c = *cur; cur >= p->tok->buf; c = *--cur) {
935 if (c == '\'' || c == '"') {
936 return 1;
937 }
938 }
939 return 0;
940}
941
942/* Check that the source for a single input statement really is a single
943 statement by looking at what is left in the buffer after parsing.
944 Trailing whitespace and comments are OK. */
945static int // bool
946bad_single_statement(Parser *p)
947{
948 const char *cur = strchr(p->tok->buf, '\n');
949
950 /* Newlines are allowed if preceded by a line continuation character
951 or if they appear inside a string. */
952 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
953 return 0;
954 }
955 char c = *cur;
956
957 for (;;) {
958 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
959 c = *++cur;
960 }
961
962 if (!c) {
963 return 0;
964 }
965
966 if (c != '#') {
967 return 1;
968 }
969
970 /* Suck up comment. */
971 while (c && c != '\n') {
972 c = *++cur;
973 }
974 }
975}
976
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100977void
978_PyPegen_Parser_Free(Parser *p)
979{
980 Py_XDECREF(p->normalize);
981 for (int i = 0; i < p->size; i++) {
982 PyMem_Free(p->tokens[i]);
983 }
984 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700985 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100986 PyMem_Free(p);
987}
988
Pablo Galindo2b74c832020-04-27 18:02:07 +0100989static int
990compute_parser_flags(PyCompilerFlags *flags)
991{
992 int parser_flags = 0;
993 if (!flags) {
994 return 0;
995 }
996 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
997 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
998 }
999 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1000 parser_flags |= PyPARSE_IGNORE_COOKIE;
1001 }
1002 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1003 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1004 }
1005 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1006 parser_flags |= PyPARSE_TYPE_COMMENTS;
1007 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001008 if (flags->cf_feature_version < 7) {
1009 parser_flags |= PyPARSE_ASYNC_HACKS;
1010 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001011 return parser_flags;
1012}
1013
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001014Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001015_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001016 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001017{
1018 Parser *p = PyMem_Malloc(sizeof(Parser));
1019 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001020 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001021 }
1022 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001023 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1024 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001025 p->tok = tok;
1026 p->keywords = NULL;
1027 p->n_keyword_lists = -1;
1028 p->tokens = PyMem_Malloc(sizeof(Token *));
1029 if (!p->tokens) {
1030 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001031 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001032 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001033 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001034 if (!p->tokens) {
1035 PyMem_Free(p->tokens);
1036 PyMem_Free(p);
1037 return (Parser *) PyErr_NoMemory();
1038 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001039 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1040 PyMem_Free(p->tokens[0]);
1041 PyMem_Free(p->tokens);
1042 PyMem_Free(p);
1043 return (Parser *) PyErr_NoMemory();
1044 }
1045
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001046 p->mark = 0;
1047 p->fill = 0;
1048 p->size = 1;
1049
1050 p->errcode = errcode;
1051 p->arena = arena;
1052 p->start_rule = start_rule;
1053 p->parsing_started = 0;
1054 p->normalize = NULL;
1055 p->error_indicator = 0;
1056
1057 p->starting_lineno = 0;
1058 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001059 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001060 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001061 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001062 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001063
1064 return p;
1065}
1066
1067void *
1068_PyPegen_run_parser(Parser *p)
1069{
1070 void *res = _PyPegen_parse(p);
1071 if (res == NULL) {
1072 if (PyErr_Occurred()) {
1073 return NULL;
1074 }
1075 if (p->fill == 0) {
1076 RAISE_SYNTAX_ERROR("error at start before reading any input");
1077 }
1078 else if (p->tok->done == E_EOF) {
1079 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1080 }
1081 else {
1082 if (p->tokens[p->fill-1]->type == INDENT) {
1083 RAISE_INDENTATION_ERROR("unexpected indent");
1084 }
1085 else if (p->tokens[p->fill-1]->type == DEDENT) {
1086 RAISE_INDENTATION_ERROR("unexpected unindent");
1087 }
1088 else {
1089 RAISE_SYNTAX_ERROR("invalid syntax");
1090 }
1091 }
1092 return NULL;
1093 }
1094
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001095 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1096 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1097 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1098 }
1099
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001100 return res;
1101}
1102
1103mod_ty
1104_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1105 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001106 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001107{
1108 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1109 if (tok == NULL) {
1110 if (PyErr_Occurred()) {
1111 raise_tokenizer_init_error(filename_ob);
1112 return NULL;
1113 }
1114 return NULL;
1115 }
1116 // This transfers the ownership to the tokenizer
1117 tok->filename = filename_ob;
1118 Py_INCREF(filename_ob);
1119
1120 // From here on we need to clean up even if there's an error
1121 mod_ty result = NULL;
1122
Pablo Galindo2b74c832020-04-27 18:02:07 +01001123 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001124 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1125 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001126 if (p == NULL) {
1127 goto error;
1128 }
1129
1130 result = _PyPegen_run_parser(p);
1131 _PyPegen_Parser_Free(p);
1132
1133error:
1134 PyTokenizer_Free(tok);
1135 return result;
1136}
1137
1138mod_ty
1139_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001140 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001141{
1142 FILE *fp = fopen(filename, "rb");
1143 if (fp == NULL) {
1144 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1145 return NULL;
1146 }
1147
1148 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001149 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001150
1151 fclose(fp);
1152 return result;
1153}
1154
1155mod_ty
1156_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001157 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001158{
1159 int exec_input = start_rule == Py_file_input;
1160
1161 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001162 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001163 tok = PyTokenizer_FromUTF8(str, exec_input);
1164 } else {
1165 tok = PyTokenizer_FromString(str, exec_input);
1166 }
1167 if (tok == NULL) {
1168 if (PyErr_Occurred()) {
1169 raise_tokenizer_init_error(filename_ob);
1170 }
1171 return NULL;
1172 }
1173 // This transfers the ownership to the tokenizer
1174 tok->filename = filename_ob;
1175 Py_INCREF(filename_ob);
1176
1177 // We need to clear up from here on
1178 mod_ty result = NULL;
1179
Pablo Galindo2b74c832020-04-27 18:02:07 +01001180 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001181 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001182 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1183 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001184 if (p == NULL) {
1185 goto error;
1186 }
1187
1188 result = _PyPegen_run_parser(p);
1189 _PyPegen_Parser_Free(p);
1190
1191error:
1192 PyTokenizer_Free(tok);
1193 return result;
1194}
1195
1196void *
1197_PyPegen_interactive_exit(Parser *p)
1198{
1199 if (p->errcode) {
1200 *(p->errcode) = E_EOF;
1201 }
1202 return NULL;
1203}
1204
1205/* Creates a single-element asdl_seq* that contains a */
1206asdl_seq *
1207_PyPegen_singleton_seq(Parser *p, void *a)
1208{
1209 assert(a != NULL);
1210 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1211 if (!seq) {
1212 return NULL;
1213 }
1214 asdl_seq_SET(seq, 0, a);
1215 return seq;
1216}
1217
1218/* Creates a copy of seq and prepends a to it */
1219asdl_seq *
1220_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1221{
1222 assert(a != NULL);
1223 if (!seq) {
1224 return _PyPegen_singleton_seq(p, a);
1225 }
1226
1227 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1228 if (!new_seq) {
1229 return NULL;
1230 }
1231
1232 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001233 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001234 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1235 }
1236 return new_seq;
1237}
1238
Guido van Rossumc001c092020-04-30 12:12:19 -07001239/* Creates a copy of seq and appends a to it */
1240asdl_seq *
1241_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1242{
1243 assert(a != NULL);
1244 if (!seq) {
1245 return _PyPegen_singleton_seq(p, a);
1246 }
1247
1248 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1249 if (!new_seq) {
1250 return NULL;
1251 }
1252
1253 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1254 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1255 }
1256 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1257 return new_seq;
1258}
1259
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001260static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001261_get_flattened_seq_size(asdl_seq *seqs)
1262{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001263 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001264 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1265 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1266 size += asdl_seq_LEN(inner_seq);
1267 }
1268 return size;
1269}
1270
1271/* Flattens an asdl_seq* of asdl_seq*s */
1272asdl_seq *
1273_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1274{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001275 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001276 assert(flattened_seq_size > 0);
1277
1278 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1279 if (!flattened_seq) {
1280 return NULL;
1281 }
1282
1283 int flattened_seq_idx = 0;
1284 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1285 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001286 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001287 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1288 }
1289 }
1290 assert(flattened_seq_idx == flattened_seq_size);
1291
1292 return flattened_seq;
1293}
1294
1295/* Creates a new name of the form <first_name>.<second_name> */
1296expr_ty
1297_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1298{
1299 assert(first_name != NULL && second_name != NULL);
1300 PyObject *first_identifier = first_name->v.Name.id;
1301 PyObject *second_identifier = second_name->v.Name.id;
1302
1303 if (PyUnicode_READY(first_identifier) == -1) {
1304 return NULL;
1305 }
1306 if (PyUnicode_READY(second_identifier) == -1) {
1307 return NULL;
1308 }
1309 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1310 if (!first_str) {
1311 return NULL;
1312 }
1313 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1314 if (!second_str) {
1315 return NULL;
1316 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001317 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001318
1319 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1320 if (!str) {
1321 return NULL;
1322 }
1323
1324 char *s = PyBytes_AS_STRING(str);
1325 if (!s) {
1326 return NULL;
1327 }
1328
1329 strcpy(s, first_str);
1330 s += strlen(first_str);
1331 *s++ = '.';
1332 strcpy(s, second_str);
1333 s += strlen(second_str);
1334 *s = '\0';
1335
1336 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1337 Py_DECREF(str);
1338 if (!uni) {
1339 return NULL;
1340 }
1341 PyUnicode_InternInPlace(&uni);
1342 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1343 Py_DECREF(uni);
1344 return NULL;
1345 }
1346
1347 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1348}
1349
1350/* Counts the total number of dots in seq's tokens */
1351int
1352_PyPegen_seq_count_dots(asdl_seq *seq)
1353{
1354 int number_of_dots = 0;
1355 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1356 Token *current_expr = asdl_seq_GET(seq, i);
1357 switch (current_expr->type) {
1358 case ELLIPSIS:
1359 number_of_dots += 3;
1360 break;
1361 case DOT:
1362 number_of_dots += 1;
1363 break;
1364 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001365 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001366 }
1367 }
1368
1369 return number_of_dots;
1370}
1371
1372/* Creates an alias with '*' as the identifier name */
1373alias_ty
1374_PyPegen_alias_for_star(Parser *p)
1375{
1376 PyObject *str = PyUnicode_InternFromString("*");
1377 if (!str) {
1378 return NULL;
1379 }
1380 if (PyArena_AddPyObject(p->arena, str) < 0) {
1381 Py_DECREF(str);
1382 return NULL;
1383 }
1384 return alias(str, NULL, p->arena);
1385}
1386
1387/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1388asdl_seq *
1389_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1390{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001391 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001392 assert(len > 0);
1393
1394 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1395 if (!new_seq) {
1396 return NULL;
1397 }
1398 for (Py_ssize_t i = 0; i < len; i++) {
1399 expr_ty e = asdl_seq_GET(seq, i);
1400 asdl_seq_SET(new_seq, i, e->v.Name.id);
1401 }
1402 return new_seq;
1403}
1404
1405/* Constructs a CmpopExprPair */
1406CmpopExprPair *
1407_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1408{
1409 assert(expr != NULL);
1410 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1411 if (!a) {
1412 return NULL;
1413 }
1414 a->cmpop = cmpop;
1415 a->expr = expr;
1416 return a;
1417}
1418
1419asdl_int_seq *
1420_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1421{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001422 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001423 assert(len > 0);
1424
1425 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1426 if (!new_seq) {
1427 return NULL;
1428 }
1429 for (Py_ssize_t i = 0; i < len; i++) {
1430 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1431 asdl_seq_SET(new_seq, i, pair->cmpop);
1432 }
1433 return new_seq;
1434}
1435
1436asdl_seq *
1437_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1438{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001439 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001440 assert(len > 0);
1441
1442 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1443 if (!new_seq) {
1444 return NULL;
1445 }
1446 for (Py_ssize_t i = 0; i < len; i++) {
1447 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1448 asdl_seq_SET(new_seq, i, pair->expr);
1449 }
1450 return new_seq;
1451}
1452
1453/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1454static asdl_seq *
1455_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1456{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001457 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001458 if (len == 0) {
1459 return NULL;
1460 }
1461
1462 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1463 if (!new_seq) {
1464 return NULL;
1465 }
1466 for (Py_ssize_t i = 0; i < len; i++) {
1467 expr_ty e = asdl_seq_GET(seq, i);
1468 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1469 }
1470 return new_seq;
1471}
1472
1473static expr_ty
1474_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1475{
1476 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1477}
1478
1479static expr_ty
1480_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1481{
1482 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1483}
1484
1485static expr_ty
1486_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1487{
1488 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1489}
1490
1491static expr_ty
1492_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1493{
1494 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1495}
1496
1497static expr_ty
1498_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1499{
1500 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1501}
1502
1503static expr_ty
1504_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1505{
1506 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1507}
1508
1509/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1510expr_ty
1511_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1512{
1513 assert(expr != NULL);
1514
1515 expr_ty new = NULL;
1516 switch (expr->kind) {
1517 case Name_kind:
1518 new = _set_name_context(p, expr, ctx);
1519 break;
1520 case Tuple_kind:
1521 new = _set_tuple_context(p, expr, ctx);
1522 break;
1523 case List_kind:
1524 new = _set_list_context(p, expr, ctx);
1525 break;
1526 case Subscript_kind:
1527 new = _set_subscript_context(p, expr, ctx);
1528 break;
1529 case Attribute_kind:
1530 new = _set_attribute_context(p, expr, ctx);
1531 break;
1532 case Starred_kind:
1533 new = _set_starred_context(p, expr, ctx);
1534 break;
1535 default:
1536 new = expr;
1537 }
1538 return new;
1539}
1540
1541/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1542KeyValuePair *
1543_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1544{
1545 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1546 if (!a) {
1547 return NULL;
1548 }
1549 a->key = key;
1550 a->value = value;
1551 return a;
1552}
1553
1554/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1555asdl_seq *
1556_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1557{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001558 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001559 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1560 if (!new_seq) {
1561 return NULL;
1562 }
1563 for (Py_ssize_t i = 0; i < len; i++) {
1564 KeyValuePair *pair = asdl_seq_GET(seq, i);
1565 asdl_seq_SET(new_seq, i, pair->key);
1566 }
1567 return new_seq;
1568}
1569
1570/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1571asdl_seq *
1572_PyPegen_get_values(Parser *p, asdl_seq *seq)
1573{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001574 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001575 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1576 if (!new_seq) {
1577 return NULL;
1578 }
1579 for (Py_ssize_t i = 0; i < len; i++) {
1580 KeyValuePair *pair = asdl_seq_GET(seq, i);
1581 asdl_seq_SET(new_seq, i, pair->value);
1582 }
1583 return new_seq;
1584}
1585
1586/* Constructs a NameDefaultPair */
1587NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001588_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001589{
1590 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1591 if (!a) {
1592 return NULL;
1593 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001594 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001595 a->value = value;
1596 return a;
1597}
1598
1599/* Constructs a SlashWithDefault */
1600SlashWithDefault *
1601_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1602{
1603 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1604 if (!a) {
1605 return NULL;
1606 }
1607 a->plain_names = plain_names;
1608 a->names_with_defaults = names_with_defaults;
1609 return a;
1610}
1611
1612/* Constructs a StarEtc */
1613StarEtc *
1614_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1615{
1616 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1617 if (!a) {
1618 return NULL;
1619 }
1620 a->vararg = vararg;
1621 a->kwonlyargs = kwonlyargs;
1622 a->kwarg = kwarg;
1623 return a;
1624}
1625
1626asdl_seq *
1627_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1628{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001629 Py_ssize_t first_len = asdl_seq_LEN(a);
1630 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001631 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1632 if (!new_seq) {
1633 return NULL;
1634 }
1635
1636 int k = 0;
1637 for (Py_ssize_t i = 0; i < first_len; i++) {
1638 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1639 }
1640 for (Py_ssize_t i = 0; i < second_len; i++) {
1641 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1642 }
1643
1644 return new_seq;
1645}
1646
1647static asdl_seq *
1648_get_names(Parser *p, asdl_seq *names_with_defaults)
1649{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001650 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001651 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1652 if (!seq) {
1653 return NULL;
1654 }
1655 for (Py_ssize_t i = 0; i < len; i++) {
1656 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1657 asdl_seq_SET(seq, i, pair->arg);
1658 }
1659 return seq;
1660}
1661
1662static asdl_seq *
1663_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1664{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001665 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001666 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1667 if (!seq) {
1668 return NULL;
1669 }
1670 for (Py_ssize_t i = 0; i < len; i++) {
1671 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1672 asdl_seq_SET(seq, i, pair->value);
1673 }
1674 return seq;
1675}
1676
1677/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1678arguments_ty
1679_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1680 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1681 asdl_seq *names_with_default, StarEtc *star_etc)
1682{
1683 asdl_seq *posonlyargs;
1684 if (slash_without_default != NULL) {
1685 posonlyargs = slash_without_default;
1686 }
1687 else if (slash_with_default != NULL) {
1688 asdl_seq *slash_with_default_names =
1689 _get_names(p, slash_with_default->names_with_defaults);
1690 if (!slash_with_default_names) {
1691 return NULL;
1692 }
1693 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1694 if (!posonlyargs) {
1695 return NULL;
1696 }
1697 }
1698 else {
1699 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1700 if (!posonlyargs) {
1701 return NULL;
1702 }
1703 }
1704
1705 asdl_seq *posargs;
1706 if (plain_names != NULL && names_with_default != NULL) {
1707 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1708 if (!names_with_default_names) {
1709 return NULL;
1710 }
1711 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1712 if (!posargs) {
1713 return NULL;
1714 }
1715 }
1716 else if (plain_names == NULL && names_with_default != NULL) {
1717 posargs = _get_names(p, names_with_default);
1718 if (!posargs) {
1719 return NULL;
1720 }
1721 }
1722 else if (plain_names != NULL && names_with_default == NULL) {
1723 posargs = plain_names;
1724 }
1725 else {
1726 posargs = _Py_asdl_seq_new(0, p->arena);
1727 if (!posargs) {
1728 return NULL;
1729 }
1730 }
1731
1732 asdl_seq *posdefaults;
1733 if (slash_with_default != NULL && names_with_default != NULL) {
1734 asdl_seq *slash_with_default_values =
1735 _get_defaults(p, slash_with_default->names_with_defaults);
1736 if (!slash_with_default_values) {
1737 return NULL;
1738 }
1739 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1740 if (!names_with_default_values) {
1741 return NULL;
1742 }
1743 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1744 if (!posdefaults) {
1745 return NULL;
1746 }
1747 }
1748 else if (slash_with_default == NULL && names_with_default != NULL) {
1749 posdefaults = _get_defaults(p, names_with_default);
1750 if (!posdefaults) {
1751 return NULL;
1752 }
1753 }
1754 else if (slash_with_default != NULL && names_with_default == NULL) {
1755 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1756 if (!posdefaults) {
1757 return NULL;
1758 }
1759 }
1760 else {
1761 posdefaults = _Py_asdl_seq_new(0, p->arena);
1762 if (!posdefaults) {
1763 return NULL;
1764 }
1765 }
1766
1767 arg_ty vararg = NULL;
1768 if (star_etc != NULL && star_etc->vararg != NULL) {
1769 vararg = star_etc->vararg;
1770 }
1771
1772 asdl_seq *kwonlyargs;
1773 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1774 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1775 if (!kwonlyargs) {
1776 return NULL;
1777 }
1778 }
1779 else {
1780 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1781 if (!kwonlyargs) {
1782 return NULL;
1783 }
1784 }
1785
1786 asdl_seq *kwdefaults;
1787 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1788 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1789 if (!kwdefaults) {
1790 return NULL;
1791 }
1792 }
1793 else {
1794 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1795 if (!kwdefaults) {
1796 return NULL;
1797 }
1798 }
1799
1800 arg_ty kwarg = NULL;
1801 if (star_etc != NULL && star_etc->kwarg != NULL) {
1802 kwarg = star_etc->kwarg;
1803 }
1804
1805 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1806 posdefaults, p->arena);
1807}
1808
1809/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1810 * arguments. */
1811arguments_ty
1812_PyPegen_empty_arguments(Parser *p)
1813{
1814 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1815 if (!posonlyargs) {
1816 return NULL;
1817 }
1818 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1819 if (!posargs) {
1820 return NULL;
1821 }
1822 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1823 if (!posdefaults) {
1824 return NULL;
1825 }
1826 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1827 if (!kwonlyargs) {
1828 return NULL;
1829 }
1830 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1831 if (!kwdefaults) {
1832 return NULL;
1833 }
1834
1835 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1836 p->arena);
1837}
1838
1839/* Encapsulates the value of an operator_ty into an AugOperator struct */
1840AugOperator *
1841_PyPegen_augoperator(Parser *p, operator_ty kind)
1842{
1843 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1844 if (!a) {
1845 return NULL;
1846 }
1847 a->kind = kind;
1848 return a;
1849}
1850
1851/* Construct a FunctionDef equivalent to function_def, but with decorators */
1852stmt_ty
1853_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1854{
1855 assert(function_def != NULL);
1856 if (function_def->kind == AsyncFunctionDef_kind) {
1857 return _Py_AsyncFunctionDef(
1858 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1859 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1860 function_def->v.FunctionDef.type_comment, function_def->lineno,
1861 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1862 p->arena);
1863 }
1864
1865 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1866 function_def->v.FunctionDef.body, decorators,
1867 function_def->v.FunctionDef.returns,
1868 function_def->v.FunctionDef.type_comment, function_def->lineno,
1869 function_def->col_offset, function_def->end_lineno,
1870 function_def->end_col_offset, p->arena);
1871}
1872
1873/* Construct a ClassDef equivalent to class_def, but with decorators */
1874stmt_ty
1875_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1876{
1877 assert(class_def != NULL);
1878 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1879 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1880 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1881 class_def->end_col_offset, p->arena);
1882}
1883
1884/* Construct a KeywordOrStarred */
1885KeywordOrStarred *
1886_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1887{
1888 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1889 if (!a) {
1890 return NULL;
1891 }
1892 a->element = element;
1893 a->is_keyword = is_keyword;
1894 return a;
1895}
1896
1897/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1898static int
1899_seq_number_of_starred_exprs(asdl_seq *seq)
1900{
1901 int n = 0;
1902 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1903 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1904 if (!k->is_keyword) {
1905 n++;
1906 }
1907 }
1908 return n;
1909}
1910
1911/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1912asdl_seq *
1913_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1914{
1915 int new_len = _seq_number_of_starred_exprs(kwargs);
1916 if (new_len == 0) {
1917 return NULL;
1918 }
1919 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1920 if (!new_seq) {
1921 return NULL;
1922 }
1923
1924 int idx = 0;
1925 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1926 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1927 if (!k->is_keyword) {
1928 asdl_seq_SET(new_seq, idx++, k->element);
1929 }
1930 }
1931 return new_seq;
1932}
1933
1934/* Return a new asdl_seq* with only the keywords in kwargs */
1935asdl_seq *
1936_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1937{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001938 Py_ssize_t len = asdl_seq_LEN(kwargs);
1939 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001940 if (new_len == 0) {
1941 return NULL;
1942 }
1943 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1944 if (!new_seq) {
1945 return NULL;
1946 }
1947
1948 int idx = 0;
1949 for (Py_ssize_t i = 0; i < len; i++) {
1950 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1951 if (k->is_keyword) {
1952 asdl_seq_SET(new_seq, idx++, k->element);
1953 }
1954 }
1955 return new_seq;
1956}
1957
1958expr_ty
1959_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1960{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001961 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001962 assert(len > 0);
1963
1964 Token *first = asdl_seq_GET(strings, 0);
1965 Token *last = asdl_seq_GET(strings, len - 1);
1966
1967 int bytesmode = 0;
1968 PyObject *bytes_str = NULL;
1969
1970 FstringParser state;
1971 _PyPegen_FstringParser_Init(&state);
1972
1973 for (Py_ssize_t i = 0; i < len; i++) {
1974 Token *t = asdl_seq_GET(strings, i);
1975
1976 int this_bytesmode;
1977 int this_rawmode;
1978 PyObject *s;
1979 const char *fstr;
1980 Py_ssize_t fstrlen = -1;
1981
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001982 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001983 goto error;
1984 }
1985
1986 /* Check that we are not mixing bytes with unicode. */
1987 if (i != 0 && bytesmode != this_bytesmode) {
1988 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1989 Py_XDECREF(s);
1990 goto error;
1991 }
1992 bytesmode = this_bytesmode;
1993
1994 if (fstr != NULL) {
1995 assert(s == NULL && !bytesmode);
1996
1997 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
1998 this_rawmode, 0, first, t, last);
1999 if (result < 0) {
2000 goto error;
2001 }
2002 }
2003 else {
2004 /* String or byte string. */
2005 assert(s != NULL && fstr == NULL);
2006 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2007
2008 if (bytesmode) {
2009 if (i == 0) {
2010 bytes_str = s;
2011 }
2012 else {
2013 PyBytes_ConcatAndDel(&bytes_str, s);
2014 if (!bytes_str) {
2015 goto error;
2016 }
2017 }
2018 }
2019 else {
2020 /* This is a regular string. Concatenate it. */
2021 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2022 goto error;
2023 }
2024 }
2025 }
2026 }
2027
2028 if (bytesmode) {
2029 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2030 goto error;
2031 }
2032 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2033 last->end_col_offset, p->arena);
2034 }
2035
2036 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2037
2038error:
2039 Py_XDECREF(bytes_str);
2040 _PyPegen_FstringParser_Dealloc(&state);
2041 if (PyErr_Occurred()) {
2042 raise_decode_error(p);
2043 }
2044 return NULL;
2045}
Guido van Rossumc001c092020-04-30 12:12:19 -07002046
2047mod_ty
2048_PyPegen_make_module(Parser *p, asdl_seq *a) {
2049 asdl_seq *type_ignores = NULL;
2050 Py_ssize_t num = p->type_ignore_comments.num_items;
2051 if (num > 0) {
2052 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2053 type_ignores = _Py_asdl_seq_new(num, p->arena);
2054 if (type_ignores == NULL) {
2055 return NULL;
2056 }
2057 for (int i = 0; i < num; i++) {
2058 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2059 if (tag == NULL) {
2060 return NULL;
2061 }
2062 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2063 if (ti == NULL) {
2064 return NULL;
2065 }
2066 asdl_seq_SET(type_ignores, i, ti);
2067 }
2068 }
2069 return Module(a, type_ignores, p->arena);
2070}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002071
2072// Error reporting helpers
2073
2074expr_ty
2075_PyPegen_get_invalid_target(expr_ty e)
2076{
2077 if (e == NULL) {
2078 return NULL;
2079 }
2080
2081#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2082 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2083 for (Py_ssize_t i = 0; i < len; i++) {\
2084 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2085 expr_ty child = _PyPegen_get_invalid_target(other);\
2086 if (child != NULL) {\
2087 return child;\
2088 }\
2089 }\
2090 } while (0)
2091
2092 // We only need to visit List and Tuple nodes recursively as those
2093 // are the only ones that can contain valid names in targets when
2094 // they are parsed as expressions. Any other kind of expression
2095 // that is a container (like Sets or Dicts) is directly invalid and
2096 // we don't need to visit it recursively.
2097
2098 switch (e->kind) {
2099 case List_kind: {
2100 VISIT_CONTAINER(e, List);
2101 return NULL;
2102 }
2103 case Tuple_kind: {
2104 VISIT_CONTAINER(e, Tuple);
2105 return NULL;
2106 }
2107 case Starred_kind:
2108 return _PyPegen_get_invalid_target(e->v.Starred.value);
2109 case Name_kind:
2110 case Subscript_kind:
2111 case Attribute_kind:
2112 return NULL;
2113 default:
2114 return e;
2115 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002116}
2117
2118void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2119 int kwarg_unpacking = 0;
2120 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2121 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2122 if (!keyword->arg) {
2123 kwarg_unpacking = 1;
2124 }
2125 }
2126
2127 const char *msg = NULL;
2128 if (kwarg_unpacking) {
2129 msg = "positional argument follows keyword argument unpacking";
2130 } else {
2131 msg = "positional argument follows keyword argument";
2132 }
2133
2134 return RAISE_SYNTAX_ERROR(msg);
2135}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002136
2137void *
2138_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2139{
2140 /* The rule that calls this function is 'args for_if_clauses'.
2141 For the input f(L, x for x in y), L and x are in args and
2142 the for is parsed as a for_if_clause. We have to check if
2143 len <= 1, so that input like dict((a, b) for a, b in x)
2144 gets successfully parsed and then we pass the last
2145 argument (x in the above example) as the location of the
2146 error */
2147 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2148 if (len <= 1) {
2149 return NULL;
2150 }
2151
2152 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2153 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2154 "Generator expression must be parenthesized"
2155 );
2156}