blob: cd87a9ffd9365361723af28f499e75e2e88a7dfa [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
Pablo Galindob23d7ad2020-05-24 06:01:34 +0100411 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 +0100711
712int
713_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
714{
715 int mark = p->mark;
716 void *res = func(p);
717 p->mark = mark;
718 return (res != NULL) == positive;
719}
720
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100721int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100722_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
723{
724 int mark = p->mark;
725 void *res = func(p, arg);
726 p->mark = mark;
727 return (res != NULL) == positive;
728}
729
730int
731_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
732{
733 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100734 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100735 p->mark = mark;
736 return (res != NULL) == positive;
737}
738
739Token *
740_PyPegen_expect_token(Parser *p, int type)
741{
742 if (p->mark == p->fill) {
743 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300744 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100745 return NULL;
746 }
747 }
748 Token *t = p->tokens[p->mark];
749 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100750 return NULL;
751 }
752 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100753 return t;
754}
755
756Token *
757_PyPegen_get_last_nonnwhitespace_token(Parser *p)
758{
759 assert(p->mark >= 0);
760 Token *token = NULL;
761 for (int m = p->mark - 1; m >= 0; m--) {
762 token = p->tokens[m];
763 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
764 break;
765 }
766 }
767 return token;
768}
769
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100770expr_ty
771_PyPegen_name_token(Parser *p)
772{
773 Token *t = _PyPegen_expect_token(p, NAME);
774 if (t == NULL) {
775 return NULL;
776 }
777 char* s = PyBytes_AsString(t->bytes);
778 if (!s) {
779 return NULL;
780 }
781 PyObject *id = _PyPegen_new_identifier(p, s);
782 if (id == NULL) {
783 return NULL;
784 }
785 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
786 p->arena);
787}
788
789void *
790_PyPegen_string_token(Parser *p)
791{
792 return _PyPegen_expect_token(p, STRING);
793}
794
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100795static PyObject *
796parsenumber_raw(const char *s)
797{
798 const char *end;
799 long x;
800 double dx;
801 Py_complex compl;
802 int imflag;
803
804 assert(s != NULL);
805 errno = 0;
806 end = s + strlen(s) - 1;
807 imflag = *end == 'j' || *end == 'J';
808 if (s[0] == '0') {
809 x = (long)PyOS_strtoul(s, (char **)&end, 0);
810 if (x < 0 && errno == 0) {
811 return PyLong_FromString(s, (char **)0, 0);
812 }
813 }
814 else
815 x = PyOS_strtol(s, (char **)&end, 0);
816 if (*end == '\0') {
817 if (errno != 0)
818 return PyLong_FromString(s, (char **)0, 0);
819 return PyLong_FromLong(x);
820 }
821 /* XXX Huge floats may silently fail */
822 if (imflag) {
823 compl.real = 0.;
824 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
825 if (compl.imag == -1.0 && PyErr_Occurred())
826 return NULL;
827 return PyComplex_FromCComplex(compl);
828 }
829 else {
830 dx = PyOS_string_to_double(s, NULL, NULL);
831 if (dx == -1.0 && PyErr_Occurred())
832 return NULL;
833 return PyFloat_FromDouble(dx);
834 }
835}
836
837static PyObject *
838parsenumber(const char *s)
839{
840 char *dup, *end;
841 PyObject *res = NULL;
842
843 assert(s != NULL);
844
845 if (strchr(s, '_') == NULL) {
846 return parsenumber_raw(s);
847 }
848 /* Create a duplicate without underscores. */
849 dup = PyMem_Malloc(strlen(s) + 1);
850 if (dup == NULL) {
851 return PyErr_NoMemory();
852 }
853 end = dup;
854 for (; *s; s++) {
855 if (*s != '_') {
856 *end++ = *s;
857 }
858 }
859 *end = '\0';
860 res = parsenumber_raw(dup);
861 PyMem_Free(dup);
862 return res;
863}
864
865expr_ty
866_PyPegen_number_token(Parser *p)
867{
868 Token *t = _PyPegen_expect_token(p, NUMBER);
869 if (t == NULL) {
870 return NULL;
871 }
872
873 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100874 if (num_raw == NULL) {
875 return NULL;
876 }
877
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300878 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
879 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700880 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300881 "in Python 3.6 and greater");
882 }
883
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100884 PyObject *c = parsenumber(num_raw);
885
886 if (c == NULL) {
887 return NULL;
888 }
889
890 if (PyArena_AddPyObject(p->arena, c) < 0) {
891 Py_DECREF(c);
892 return NULL;
893 }
894
895 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
896 p->arena);
897}
898
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300899static int // bool
900newline_in_string(Parser *p, const char *cur)
901{
902 for (char c = *cur; cur >= p->tok->buf; c = *--cur) {
903 if (c == '\'' || c == '"') {
904 return 1;
905 }
906 }
907 return 0;
908}
909
910/* Check that the source for a single input statement really is a single
911 statement by looking at what is left in the buffer after parsing.
912 Trailing whitespace and comments are OK. */
913static int // bool
914bad_single_statement(Parser *p)
915{
916 const char *cur = strchr(p->tok->buf, '\n');
917
918 /* Newlines are allowed if preceded by a line continuation character
919 or if they appear inside a string. */
920 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
921 return 0;
922 }
923 char c = *cur;
924
925 for (;;) {
926 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
927 c = *++cur;
928 }
929
930 if (!c) {
931 return 0;
932 }
933
934 if (c != '#') {
935 return 1;
936 }
937
938 /* Suck up comment. */
939 while (c && c != '\n') {
940 c = *++cur;
941 }
942 }
943}
944
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100945void
946_PyPegen_Parser_Free(Parser *p)
947{
948 Py_XDECREF(p->normalize);
949 for (int i = 0; i < p->size; i++) {
950 PyMem_Free(p->tokens[i]);
951 }
952 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700953 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100954 PyMem_Free(p);
955}
956
Pablo Galindo2b74c832020-04-27 18:02:07 +0100957static int
958compute_parser_flags(PyCompilerFlags *flags)
959{
960 int parser_flags = 0;
961 if (!flags) {
962 return 0;
963 }
964 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
965 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
966 }
967 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
968 parser_flags |= PyPARSE_IGNORE_COOKIE;
969 }
970 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
971 parser_flags |= PyPARSE_BARRY_AS_BDFL;
972 }
973 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
974 parser_flags |= PyPARSE_TYPE_COMMENTS;
975 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300976 if (flags->cf_feature_version < 7) {
977 parser_flags |= PyPARSE_ASYNC_HACKS;
978 }
Pablo Galindo2b74c832020-04-27 18:02:07 +0100979 return parser_flags;
980}
981
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100982Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +0100983_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300984 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100985{
986 Parser *p = PyMem_Malloc(sizeof(Parser));
987 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300988 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100989 }
990 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -0700991 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
992 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100993 p->tok = tok;
994 p->keywords = NULL;
995 p->n_keyword_lists = -1;
996 p->tokens = PyMem_Malloc(sizeof(Token *));
997 if (!p->tokens) {
998 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300999 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001000 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001001 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001002 if (!p->tokens) {
1003 PyMem_Free(p->tokens);
1004 PyMem_Free(p);
1005 return (Parser *) PyErr_NoMemory();
1006 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001007 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1008 PyMem_Free(p->tokens[0]);
1009 PyMem_Free(p->tokens);
1010 PyMem_Free(p);
1011 return (Parser *) PyErr_NoMemory();
1012 }
1013
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001014 p->mark = 0;
1015 p->fill = 0;
1016 p->size = 1;
1017
1018 p->errcode = errcode;
1019 p->arena = arena;
1020 p->start_rule = start_rule;
1021 p->parsing_started = 0;
1022 p->normalize = NULL;
1023 p->error_indicator = 0;
1024
1025 p->starting_lineno = 0;
1026 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001027 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001028 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001029 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001030 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001031
1032 return p;
1033}
1034
1035void *
1036_PyPegen_run_parser(Parser *p)
1037{
1038 void *res = _PyPegen_parse(p);
1039 if (res == NULL) {
1040 if (PyErr_Occurred()) {
1041 return NULL;
1042 }
1043 if (p->fill == 0) {
1044 RAISE_SYNTAX_ERROR("error at start before reading any input");
1045 }
1046 else if (p->tok->done == E_EOF) {
1047 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1048 }
1049 else {
1050 if (p->tokens[p->fill-1]->type == INDENT) {
1051 RAISE_INDENTATION_ERROR("unexpected indent");
1052 }
1053 else if (p->tokens[p->fill-1]->type == DEDENT) {
1054 RAISE_INDENTATION_ERROR("unexpected unindent");
1055 }
1056 else {
1057 RAISE_SYNTAX_ERROR("invalid syntax");
1058 }
1059 }
1060 return NULL;
1061 }
1062
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001063 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1064 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1065 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1066 }
1067
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001068 return res;
1069}
1070
1071mod_ty
1072_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1073 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001074 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001075{
1076 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1077 if (tok == NULL) {
1078 if (PyErr_Occurred()) {
1079 raise_tokenizer_init_error(filename_ob);
1080 return NULL;
1081 }
1082 return NULL;
1083 }
1084 // This transfers the ownership to the tokenizer
1085 tok->filename = filename_ob;
1086 Py_INCREF(filename_ob);
1087
1088 // From here on we need to clean up even if there's an error
1089 mod_ty result = NULL;
1090
Pablo Galindo2b74c832020-04-27 18:02:07 +01001091 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001092 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1093 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001094 if (p == NULL) {
1095 goto error;
1096 }
1097
1098 result = _PyPegen_run_parser(p);
1099 _PyPegen_Parser_Free(p);
1100
1101error:
1102 PyTokenizer_Free(tok);
1103 return result;
1104}
1105
1106mod_ty
1107_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001108 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001109{
1110 FILE *fp = fopen(filename, "rb");
1111 if (fp == NULL) {
1112 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1113 return NULL;
1114 }
1115
1116 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001117 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001118
1119 fclose(fp);
1120 return result;
1121}
1122
1123mod_ty
1124_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001125 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001126{
1127 int exec_input = start_rule == Py_file_input;
1128
1129 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001130 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001131 tok = PyTokenizer_FromUTF8(str, exec_input);
1132 } else {
1133 tok = PyTokenizer_FromString(str, exec_input);
1134 }
1135 if (tok == NULL) {
1136 if (PyErr_Occurred()) {
1137 raise_tokenizer_init_error(filename_ob);
1138 }
1139 return NULL;
1140 }
1141 // This transfers the ownership to the tokenizer
1142 tok->filename = filename_ob;
1143 Py_INCREF(filename_ob);
1144
1145 // We need to clear up from here on
1146 mod_ty result = NULL;
1147
Pablo Galindo2b74c832020-04-27 18:02:07 +01001148 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001149 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001150 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1151 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001152 if (p == NULL) {
1153 goto error;
1154 }
1155
1156 result = _PyPegen_run_parser(p);
1157 _PyPegen_Parser_Free(p);
1158
1159error:
1160 PyTokenizer_Free(tok);
1161 return result;
1162}
1163
1164void *
1165_PyPegen_interactive_exit(Parser *p)
1166{
1167 if (p->errcode) {
1168 *(p->errcode) = E_EOF;
1169 }
1170 return NULL;
1171}
1172
1173/* Creates a single-element asdl_seq* that contains a */
1174asdl_seq *
1175_PyPegen_singleton_seq(Parser *p, void *a)
1176{
1177 assert(a != NULL);
1178 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1179 if (!seq) {
1180 return NULL;
1181 }
1182 asdl_seq_SET(seq, 0, a);
1183 return seq;
1184}
1185
1186/* Creates a copy of seq and prepends a to it */
1187asdl_seq *
1188_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1189{
1190 assert(a != NULL);
1191 if (!seq) {
1192 return _PyPegen_singleton_seq(p, a);
1193 }
1194
1195 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1196 if (!new_seq) {
1197 return NULL;
1198 }
1199
1200 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001201 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001202 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1203 }
1204 return new_seq;
1205}
1206
Guido van Rossumc001c092020-04-30 12:12:19 -07001207/* Creates a copy of seq and appends a to it */
1208asdl_seq *
1209_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1210{
1211 assert(a != NULL);
1212 if (!seq) {
1213 return _PyPegen_singleton_seq(p, a);
1214 }
1215
1216 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1217 if (!new_seq) {
1218 return NULL;
1219 }
1220
1221 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1222 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1223 }
1224 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1225 return new_seq;
1226}
1227
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001228static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001229_get_flattened_seq_size(asdl_seq *seqs)
1230{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001231 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001232 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1233 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1234 size += asdl_seq_LEN(inner_seq);
1235 }
1236 return size;
1237}
1238
1239/* Flattens an asdl_seq* of asdl_seq*s */
1240asdl_seq *
1241_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1242{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001243 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001244 assert(flattened_seq_size > 0);
1245
1246 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1247 if (!flattened_seq) {
1248 return NULL;
1249 }
1250
1251 int flattened_seq_idx = 0;
1252 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1253 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001254 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001255 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1256 }
1257 }
1258 assert(flattened_seq_idx == flattened_seq_size);
1259
1260 return flattened_seq;
1261}
1262
1263/* Creates a new name of the form <first_name>.<second_name> */
1264expr_ty
1265_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1266{
1267 assert(first_name != NULL && second_name != NULL);
1268 PyObject *first_identifier = first_name->v.Name.id;
1269 PyObject *second_identifier = second_name->v.Name.id;
1270
1271 if (PyUnicode_READY(first_identifier) == -1) {
1272 return NULL;
1273 }
1274 if (PyUnicode_READY(second_identifier) == -1) {
1275 return NULL;
1276 }
1277 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1278 if (!first_str) {
1279 return NULL;
1280 }
1281 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1282 if (!second_str) {
1283 return NULL;
1284 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001285 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001286
1287 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1288 if (!str) {
1289 return NULL;
1290 }
1291
1292 char *s = PyBytes_AS_STRING(str);
1293 if (!s) {
1294 return NULL;
1295 }
1296
1297 strcpy(s, first_str);
1298 s += strlen(first_str);
1299 *s++ = '.';
1300 strcpy(s, second_str);
1301 s += strlen(second_str);
1302 *s = '\0';
1303
1304 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1305 Py_DECREF(str);
1306 if (!uni) {
1307 return NULL;
1308 }
1309 PyUnicode_InternInPlace(&uni);
1310 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1311 Py_DECREF(uni);
1312 return NULL;
1313 }
1314
1315 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1316}
1317
1318/* Counts the total number of dots in seq's tokens */
1319int
1320_PyPegen_seq_count_dots(asdl_seq *seq)
1321{
1322 int number_of_dots = 0;
1323 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1324 Token *current_expr = asdl_seq_GET(seq, i);
1325 switch (current_expr->type) {
1326 case ELLIPSIS:
1327 number_of_dots += 3;
1328 break;
1329 case DOT:
1330 number_of_dots += 1;
1331 break;
1332 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001333 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001334 }
1335 }
1336
1337 return number_of_dots;
1338}
1339
1340/* Creates an alias with '*' as the identifier name */
1341alias_ty
1342_PyPegen_alias_for_star(Parser *p)
1343{
1344 PyObject *str = PyUnicode_InternFromString("*");
1345 if (!str) {
1346 return NULL;
1347 }
1348 if (PyArena_AddPyObject(p->arena, str) < 0) {
1349 Py_DECREF(str);
1350 return NULL;
1351 }
1352 return alias(str, NULL, p->arena);
1353}
1354
1355/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1356asdl_seq *
1357_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1358{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001359 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001360 assert(len > 0);
1361
1362 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1363 if (!new_seq) {
1364 return NULL;
1365 }
1366 for (Py_ssize_t i = 0; i < len; i++) {
1367 expr_ty e = asdl_seq_GET(seq, i);
1368 asdl_seq_SET(new_seq, i, e->v.Name.id);
1369 }
1370 return new_seq;
1371}
1372
1373/* Constructs a CmpopExprPair */
1374CmpopExprPair *
1375_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1376{
1377 assert(expr != NULL);
1378 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1379 if (!a) {
1380 return NULL;
1381 }
1382 a->cmpop = cmpop;
1383 a->expr = expr;
1384 return a;
1385}
1386
1387asdl_int_seq *
1388_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1389{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001390 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001391 assert(len > 0);
1392
1393 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1394 if (!new_seq) {
1395 return NULL;
1396 }
1397 for (Py_ssize_t i = 0; i < len; i++) {
1398 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1399 asdl_seq_SET(new_seq, i, pair->cmpop);
1400 }
1401 return new_seq;
1402}
1403
1404asdl_seq *
1405_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1406{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001407 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001408 assert(len > 0);
1409
1410 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1411 if (!new_seq) {
1412 return NULL;
1413 }
1414 for (Py_ssize_t i = 0; i < len; i++) {
1415 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1416 asdl_seq_SET(new_seq, i, pair->expr);
1417 }
1418 return new_seq;
1419}
1420
1421/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1422static asdl_seq *
1423_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1424{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001425 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001426 if (len == 0) {
1427 return NULL;
1428 }
1429
1430 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1431 if (!new_seq) {
1432 return NULL;
1433 }
1434 for (Py_ssize_t i = 0; i < len; i++) {
1435 expr_ty e = asdl_seq_GET(seq, i);
1436 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1437 }
1438 return new_seq;
1439}
1440
1441static expr_ty
1442_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1443{
1444 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1445}
1446
1447static expr_ty
1448_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1449{
1450 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1451}
1452
1453static expr_ty
1454_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1455{
1456 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1457}
1458
1459static expr_ty
1460_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1461{
1462 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1463}
1464
1465static expr_ty
1466_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1467{
1468 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1469}
1470
1471static expr_ty
1472_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1473{
1474 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1475}
1476
1477/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1478expr_ty
1479_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1480{
1481 assert(expr != NULL);
1482
1483 expr_ty new = NULL;
1484 switch (expr->kind) {
1485 case Name_kind:
1486 new = _set_name_context(p, expr, ctx);
1487 break;
1488 case Tuple_kind:
1489 new = _set_tuple_context(p, expr, ctx);
1490 break;
1491 case List_kind:
1492 new = _set_list_context(p, expr, ctx);
1493 break;
1494 case Subscript_kind:
1495 new = _set_subscript_context(p, expr, ctx);
1496 break;
1497 case Attribute_kind:
1498 new = _set_attribute_context(p, expr, ctx);
1499 break;
1500 case Starred_kind:
1501 new = _set_starred_context(p, expr, ctx);
1502 break;
1503 default:
1504 new = expr;
1505 }
1506 return new;
1507}
1508
1509/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1510KeyValuePair *
1511_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1512{
1513 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1514 if (!a) {
1515 return NULL;
1516 }
1517 a->key = key;
1518 a->value = value;
1519 return a;
1520}
1521
1522/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1523asdl_seq *
1524_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1525{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001526 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001527 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1528 if (!new_seq) {
1529 return NULL;
1530 }
1531 for (Py_ssize_t i = 0; i < len; i++) {
1532 KeyValuePair *pair = asdl_seq_GET(seq, i);
1533 asdl_seq_SET(new_seq, i, pair->key);
1534 }
1535 return new_seq;
1536}
1537
1538/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1539asdl_seq *
1540_PyPegen_get_values(Parser *p, asdl_seq *seq)
1541{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001542 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001543 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1544 if (!new_seq) {
1545 return NULL;
1546 }
1547 for (Py_ssize_t i = 0; i < len; i++) {
1548 KeyValuePair *pair = asdl_seq_GET(seq, i);
1549 asdl_seq_SET(new_seq, i, pair->value);
1550 }
1551 return new_seq;
1552}
1553
1554/* Constructs a NameDefaultPair */
1555NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001556_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001557{
1558 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1559 if (!a) {
1560 return NULL;
1561 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001562 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001563 a->value = value;
1564 return a;
1565}
1566
1567/* Constructs a SlashWithDefault */
1568SlashWithDefault *
1569_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1570{
1571 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1572 if (!a) {
1573 return NULL;
1574 }
1575 a->plain_names = plain_names;
1576 a->names_with_defaults = names_with_defaults;
1577 return a;
1578}
1579
1580/* Constructs a StarEtc */
1581StarEtc *
1582_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1583{
1584 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1585 if (!a) {
1586 return NULL;
1587 }
1588 a->vararg = vararg;
1589 a->kwonlyargs = kwonlyargs;
1590 a->kwarg = kwarg;
1591 return a;
1592}
1593
1594asdl_seq *
1595_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1596{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001597 Py_ssize_t first_len = asdl_seq_LEN(a);
1598 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001599 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1600 if (!new_seq) {
1601 return NULL;
1602 }
1603
1604 int k = 0;
1605 for (Py_ssize_t i = 0; i < first_len; i++) {
1606 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1607 }
1608 for (Py_ssize_t i = 0; i < second_len; i++) {
1609 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1610 }
1611
1612 return new_seq;
1613}
1614
1615static asdl_seq *
1616_get_names(Parser *p, asdl_seq *names_with_defaults)
1617{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001618 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001619 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1620 if (!seq) {
1621 return NULL;
1622 }
1623 for (Py_ssize_t i = 0; i < len; i++) {
1624 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1625 asdl_seq_SET(seq, i, pair->arg);
1626 }
1627 return seq;
1628}
1629
1630static asdl_seq *
1631_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1632{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001633 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001634 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1635 if (!seq) {
1636 return NULL;
1637 }
1638 for (Py_ssize_t i = 0; i < len; i++) {
1639 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1640 asdl_seq_SET(seq, i, pair->value);
1641 }
1642 return seq;
1643}
1644
1645/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1646arguments_ty
1647_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1648 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1649 asdl_seq *names_with_default, StarEtc *star_etc)
1650{
1651 asdl_seq *posonlyargs;
1652 if (slash_without_default != NULL) {
1653 posonlyargs = slash_without_default;
1654 }
1655 else if (slash_with_default != NULL) {
1656 asdl_seq *slash_with_default_names =
1657 _get_names(p, slash_with_default->names_with_defaults);
1658 if (!slash_with_default_names) {
1659 return NULL;
1660 }
1661 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1662 if (!posonlyargs) {
1663 return NULL;
1664 }
1665 }
1666 else {
1667 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1668 if (!posonlyargs) {
1669 return NULL;
1670 }
1671 }
1672
1673 asdl_seq *posargs;
1674 if (plain_names != NULL && names_with_default != NULL) {
1675 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1676 if (!names_with_default_names) {
1677 return NULL;
1678 }
1679 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1680 if (!posargs) {
1681 return NULL;
1682 }
1683 }
1684 else if (plain_names == NULL && names_with_default != NULL) {
1685 posargs = _get_names(p, names_with_default);
1686 if (!posargs) {
1687 return NULL;
1688 }
1689 }
1690 else if (plain_names != NULL && names_with_default == NULL) {
1691 posargs = plain_names;
1692 }
1693 else {
1694 posargs = _Py_asdl_seq_new(0, p->arena);
1695 if (!posargs) {
1696 return NULL;
1697 }
1698 }
1699
1700 asdl_seq *posdefaults;
1701 if (slash_with_default != NULL && names_with_default != NULL) {
1702 asdl_seq *slash_with_default_values =
1703 _get_defaults(p, slash_with_default->names_with_defaults);
1704 if (!slash_with_default_values) {
1705 return NULL;
1706 }
1707 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1708 if (!names_with_default_values) {
1709 return NULL;
1710 }
1711 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1712 if (!posdefaults) {
1713 return NULL;
1714 }
1715 }
1716 else if (slash_with_default == NULL && names_with_default != NULL) {
1717 posdefaults = _get_defaults(p, names_with_default);
1718 if (!posdefaults) {
1719 return NULL;
1720 }
1721 }
1722 else if (slash_with_default != NULL && names_with_default == NULL) {
1723 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1724 if (!posdefaults) {
1725 return NULL;
1726 }
1727 }
1728 else {
1729 posdefaults = _Py_asdl_seq_new(0, p->arena);
1730 if (!posdefaults) {
1731 return NULL;
1732 }
1733 }
1734
1735 arg_ty vararg = NULL;
1736 if (star_etc != NULL && star_etc->vararg != NULL) {
1737 vararg = star_etc->vararg;
1738 }
1739
1740 asdl_seq *kwonlyargs;
1741 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1742 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1743 if (!kwonlyargs) {
1744 return NULL;
1745 }
1746 }
1747 else {
1748 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1749 if (!kwonlyargs) {
1750 return NULL;
1751 }
1752 }
1753
1754 asdl_seq *kwdefaults;
1755 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1756 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1757 if (!kwdefaults) {
1758 return NULL;
1759 }
1760 }
1761 else {
1762 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1763 if (!kwdefaults) {
1764 return NULL;
1765 }
1766 }
1767
1768 arg_ty kwarg = NULL;
1769 if (star_etc != NULL && star_etc->kwarg != NULL) {
1770 kwarg = star_etc->kwarg;
1771 }
1772
1773 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1774 posdefaults, p->arena);
1775}
1776
1777/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1778 * arguments. */
1779arguments_ty
1780_PyPegen_empty_arguments(Parser *p)
1781{
1782 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1783 if (!posonlyargs) {
1784 return NULL;
1785 }
1786 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1787 if (!posargs) {
1788 return NULL;
1789 }
1790 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1791 if (!posdefaults) {
1792 return NULL;
1793 }
1794 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1795 if (!kwonlyargs) {
1796 return NULL;
1797 }
1798 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1799 if (!kwdefaults) {
1800 return NULL;
1801 }
1802
1803 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1804 p->arena);
1805}
1806
1807/* Encapsulates the value of an operator_ty into an AugOperator struct */
1808AugOperator *
1809_PyPegen_augoperator(Parser *p, operator_ty kind)
1810{
1811 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1812 if (!a) {
1813 return NULL;
1814 }
1815 a->kind = kind;
1816 return a;
1817}
1818
1819/* Construct a FunctionDef equivalent to function_def, but with decorators */
1820stmt_ty
1821_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1822{
1823 assert(function_def != NULL);
1824 if (function_def->kind == AsyncFunctionDef_kind) {
1825 return _Py_AsyncFunctionDef(
1826 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1827 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1828 function_def->v.FunctionDef.type_comment, function_def->lineno,
1829 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1830 p->arena);
1831 }
1832
1833 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1834 function_def->v.FunctionDef.body, decorators,
1835 function_def->v.FunctionDef.returns,
1836 function_def->v.FunctionDef.type_comment, function_def->lineno,
1837 function_def->col_offset, function_def->end_lineno,
1838 function_def->end_col_offset, p->arena);
1839}
1840
1841/* Construct a ClassDef equivalent to class_def, but with decorators */
1842stmt_ty
1843_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1844{
1845 assert(class_def != NULL);
1846 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1847 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1848 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1849 class_def->end_col_offset, p->arena);
1850}
1851
1852/* Construct a KeywordOrStarred */
1853KeywordOrStarred *
1854_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1855{
1856 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1857 if (!a) {
1858 return NULL;
1859 }
1860 a->element = element;
1861 a->is_keyword = is_keyword;
1862 return a;
1863}
1864
1865/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1866static int
1867_seq_number_of_starred_exprs(asdl_seq *seq)
1868{
1869 int n = 0;
1870 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1871 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1872 if (!k->is_keyword) {
1873 n++;
1874 }
1875 }
1876 return n;
1877}
1878
1879/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1880asdl_seq *
1881_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1882{
1883 int new_len = _seq_number_of_starred_exprs(kwargs);
1884 if (new_len == 0) {
1885 return NULL;
1886 }
1887 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1888 if (!new_seq) {
1889 return NULL;
1890 }
1891
1892 int idx = 0;
1893 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1894 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1895 if (!k->is_keyword) {
1896 asdl_seq_SET(new_seq, idx++, k->element);
1897 }
1898 }
1899 return new_seq;
1900}
1901
1902/* Return a new asdl_seq* with only the keywords in kwargs */
1903asdl_seq *
1904_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1905{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001906 Py_ssize_t len = asdl_seq_LEN(kwargs);
1907 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001908 if (new_len == 0) {
1909 return NULL;
1910 }
1911 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1912 if (!new_seq) {
1913 return NULL;
1914 }
1915
1916 int idx = 0;
1917 for (Py_ssize_t i = 0; i < len; i++) {
1918 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1919 if (k->is_keyword) {
1920 asdl_seq_SET(new_seq, idx++, k->element);
1921 }
1922 }
1923 return new_seq;
1924}
1925
1926expr_ty
1927_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1928{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001929 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001930 assert(len > 0);
1931
1932 Token *first = asdl_seq_GET(strings, 0);
1933 Token *last = asdl_seq_GET(strings, len - 1);
1934
1935 int bytesmode = 0;
1936 PyObject *bytes_str = NULL;
1937
1938 FstringParser state;
1939 _PyPegen_FstringParser_Init(&state);
1940
1941 for (Py_ssize_t i = 0; i < len; i++) {
1942 Token *t = asdl_seq_GET(strings, i);
1943
1944 int this_bytesmode;
1945 int this_rawmode;
1946 PyObject *s;
1947 const char *fstr;
1948 Py_ssize_t fstrlen = -1;
1949
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001950 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001951 goto error;
1952 }
1953
1954 /* Check that we are not mixing bytes with unicode. */
1955 if (i != 0 && bytesmode != this_bytesmode) {
1956 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1957 Py_XDECREF(s);
1958 goto error;
1959 }
1960 bytesmode = this_bytesmode;
1961
1962 if (fstr != NULL) {
1963 assert(s == NULL && !bytesmode);
1964
1965 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
1966 this_rawmode, 0, first, t, last);
1967 if (result < 0) {
1968 goto error;
1969 }
1970 }
1971 else {
1972 /* String or byte string. */
1973 assert(s != NULL && fstr == NULL);
1974 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
1975
1976 if (bytesmode) {
1977 if (i == 0) {
1978 bytes_str = s;
1979 }
1980 else {
1981 PyBytes_ConcatAndDel(&bytes_str, s);
1982 if (!bytes_str) {
1983 goto error;
1984 }
1985 }
1986 }
1987 else {
1988 /* This is a regular string. Concatenate it. */
1989 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
1990 goto error;
1991 }
1992 }
1993 }
1994 }
1995
1996 if (bytesmode) {
1997 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
1998 goto error;
1999 }
2000 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2001 last->end_col_offset, p->arena);
2002 }
2003
2004 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2005
2006error:
2007 Py_XDECREF(bytes_str);
2008 _PyPegen_FstringParser_Dealloc(&state);
2009 if (PyErr_Occurred()) {
2010 raise_decode_error(p);
2011 }
2012 return NULL;
2013}
Guido van Rossumc001c092020-04-30 12:12:19 -07002014
2015mod_ty
2016_PyPegen_make_module(Parser *p, asdl_seq *a) {
2017 asdl_seq *type_ignores = NULL;
2018 Py_ssize_t num = p->type_ignore_comments.num_items;
2019 if (num > 0) {
2020 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2021 type_ignores = _Py_asdl_seq_new(num, p->arena);
2022 if (type_ignores == NULL) {
2023 return NULL;
2024 }
2025 for (int i = 0; i < num; i++) {
2026 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2027 if (tag == NULL) {
2028 return NULL;
2029 }
2030 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2031 if (ti == NULL) {
2032 return NULL;
2033 }
2034 asdl_seq_SET(type_ignores, i, ti);
2035 }
2036 }
2037 return Module(a, type_ignores, p->arena);
2038}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002039
2040// Error reporting helpers
2041
2042expr_ty
2043_PyPegen_get_invalid_target(expr_ty e)
2044{
2045 if (e == NULL) {
2046 return NULL;
2047 }
2048
2049#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2050 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2051 for (Py_ssize_t i = 0; i < len; i++) {\
2052 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2053 expr_ty child = _PyPegen_get_invalid_target(other);\
2054 if (child != NULL) {\
2055 return child;\
2056 }\
2057 }\
2058 } while (0)
2059
2060 // We only need to visit List and Tuple nodes recursively as those
2061 // are the only ones that can contain valid names in targets when
2062 // they are parsed as expressions. Any other kind of expression
2063 // that is a container (like Sets or Dicts) is directly invalid and
2064 // we don't need to visit it recursively.
2065
2066 switch (e->kind) {
2067 case List_kind: {
2068 VISIT_CONTAINER(e, List);
2069 return NULL;
2070 }
2071 case Tuple_kind: {
2072 VISIT_CONTAINER(e, Tuple);
2073 return NULL;
2074 }
2075 case Starred_kind:
2076 return _PyPegen_get_invalid_target(e->v.Starred.value);
2077 case Name_kind:
2078 case Subscript_kind:
2079 case Attribute_kind:
2080 return NULL;
2081 default:
2082 return e;
2083 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002084}
2085
2086void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2087 int kwarg_unpacking = 0;
2088 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2089 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2090 if (!keyword->arg) {
2091 kwarg_unpacking = 1;
2092 }
2093 }
2094
2095 const char *msg = NULL;
2096 if (kwarg_unpacking) {
2097 msg = "positional argument follows keyword argument unpacking";
2098 } else {
2099 msg = "positional argument follows keyword argument";
2100 }
2101
2102 return RAISE_SYNTAX_ERROR(msg);
2103}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002104
2105void *
2106_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2107{
2108 /* The rule that calls this function is 'args for_if_clauses'.
2109 For the input f(L, x for x in y), L and x are in args and
2110 the for is parsed as a for_if_clause. We have to check if
2111 len <= 1, so that input like dict((a, b) for a, b in x)
2112 gets successfully parsed and then we pass the last
2113 argument (x in the above example) as the location of the
2114 error */
2115 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2116 if (len <= 1) {
2117 return NULL;
2118 }
2119
2120 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2121 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2122 "Generator expression must be parenthesized"
2123 );
2124}