blob: ca4ea824b3f28e3b69d9e9d04d44d5576c7f3681 [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
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300411 int col_number = byte_offset_to_character_offset(error_line, col_offset);
412
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 Galindoc5fc1562020-04-22 23:29:27 +01001030
1031 return p;
1032}
1033
1034void *
1035_PyPegen_run_parser(Parser *p)
1036{
1037 void *res = _PyPegen_parse(p);
1038 if (res == NULL) {
1039 if (PyErr_Occurred()) {
1040 return NULL;
1041 }
1042 if (p->fill == 0) {
1043 RAISE_SYNTAX_ERROR("error at start before reading any input");
1044 }
1045 else if (p->tok->done == E_EOF) {
1046 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1047 }
1048 else {
1049 if (p->tokens[p->fill-1]->type == INDENT) {
1050 RAISE_INDENTATION_ERROR("unexpected indent");
1051 }
1052 else if (p->tokens[p->fill-1]->type == DEDENT) {
1053 RAISE_INDENTATION_ERROR("unexpected unindent");
1054 }
1055 else {
1056 RAISE_SYNTAX_ERROR("invalid syntax");
1057 }
1058 }
1059 return NULL;
1060 }
1061
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001062 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1063 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1064 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1065 }
1066
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001067 return res;
1068}
1069
1070mod_ty
1071_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1072 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001073 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001074{
1075 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1076 if (tok == NULL) {
1077 if (PyErr_Occurred()) {
1078 raise_tokenizer_init_error(filename_ob);
1079 return NULL;
1080 }
1081 return NULL;
1082 }
1083 // This transfers the ownership to the tokenizer
1084 tok->filename = filename_ob;
1085 Py_INCREF(filename_ob);
1086
1087 // From here on we need to clean up even if there's an error
1088 mod_ty result = NULL;
1089
Pablo Galindo2b74c832020-04-27 18:02:07 +01001090 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001091 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1092 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001093 if (p == NULL) {
1094 goto error;
1095 }
1096
1097 result = _PyPegen_run_parser(p);
1098 _PyPegen_Parser_Free(p);
1099
1100error:
1101 PyTokenizer_Free(tok);
1102 return result;
1103}
1104
1105mod_ty
1106_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001107 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001108{
1109 FILE *fp = fopen(filename, "rb");
1110 if (fp == NULL) {
1111 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1112 return NULL;
1113 }
1114
1115 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001116 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001117
1118 fclose(fp);
1119 return result;
1120}
1121
1122mod_ty
1123_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001124 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001125{
1126 int exec_input = start_rule == Py_file_input;
1127
1128 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001129 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001130 tok = PyTokenizer_FromUTF8(str, exec_input);
1131 } else {
1132 tok = PyTokenizer_FromString(str, exec_input);
1133 }
1134 if (tok == NULL) {
1135 if (PyErr_Occurred()) {
1136 raise_tokenizer_init_error(filename_ob);
1137 }
1138 return NULL;
1139 }
1140 // This transfers the ownership to the tokenizer
1141 tok->filename = filename_ob;
1142 Py_INCREF(filename_ob);
1143
1144 // We need to clear up from here on
1145 mod_ty result = NULL;
1146
Pablo Galindo2b74c832020-04-27 18:02:07 +01001147 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001148 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001149 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1150 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001151 if (p == NULL) {
1152 goto error;
1153 }
1154
1155 result = _PyPegen_run_parser(p);
1156 _PyPegen_Parser_Free(p);
1157
1158error:
1159 PyTokenizer_Free(tok);
1160 return result;
1161}
1162
1163void *
1164_PyPegen_interactive_exit(Parser *p)
1165{
1166 if (p->errcode) {
1167 *(p->errcode) = E_EOF;
1168 }
1169 return NULL;
1170}
1171
1172/* Creates a single-element asdl_seq* that contains a */
1173asdl_seq *
1174_PyPegen_singleton_seq(Parser *p, void *a)
1175{
1176 assert(a != NULL);
1177 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1178 if (!seq) {
1179 return NULL;
1180 }
1181 asdl_seq_SET(seq, 0, a);
1182 return seq;
1183}
1184
1185/* Creates a copy of seq and prepends a to it */
1186asdl_seq *
1187_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1188{
1189 assert(a != NULL);
1190 if (!seq) {
1191 return _PyPegen_singleton_seq(p, a);
1192 }
1193
1194 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1195 if (!new_seq) {
1196 return NULL;
1197 }
1198
1199 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001200 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001201 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1202 }
1203 return new_seq;
1204}
1205
Guido van Rossumc001c092020-04-30 12:12:19 -07001206/* Creates a copy of seq and appends a to it */
1207asdl_seq *
1208_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1209{
1210 assert(a != NULL);
1211 if (!seq) {
1212 return _PyPegen_singleton_seq(p, a);
1213 }
1214
1215 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1216 if (!new_seq) {
1217 return NULL;
1218 }
1219
1220 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1221 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1222 }
1223 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1224 return new_seq;
1225}
1226
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001227static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001228_get_flattened_seq_size(asdl_seq *seqs)
1229{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001230 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001231 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1232 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1233 size += asdl_seq_LEN(inner_seq);
1234 }
1235 return size;
1236}
1237
1238/* Flattens an asdl_seq* of asdl_seq*s */
1239asdl_seq *
1240_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1241{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001242 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001243 assert(flattened_seq_size > 0);
1244
1245 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1246 if (!flattened_seq) {
1247 return NULL;
1248 }
1249
1250 int flattened_seq_idx = 0;
1251 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1252 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001253 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001254 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1255 }
1256 }
1257 assert(flattened_seq_idx == flattened_seq_size);
1258
1259 return flattened_seq;
1260}
1261
1262/* Creates a new name of the form <first_name>.<second_name> */
1263expr_ty
1264_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1265{
1266 assert(first_name != NULL && second_name != NULL);
1267 PyObject *first_identifier = first_name->v.Name.id;
1268 PyObject *second_identifier = second_name->v.Name.id;
1269
1270 if (PyUnicode_READY(first_identifier) == -1) {
1271 return NULL;
1272 }
1273 if (PyUnicode_READY(second_identifier) == -1) {
1274 return NULL;
1275 }
1276 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1277 if (!first_str) {
1278 return NULL;
1279 }
1280 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1281 if (!second_str) {
1282 return NULL;
1283 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001284 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001285
1286 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1287 if (!str) {
1288 return NULL;
1289 }
1290
1291 char *s = PyBytes_AS_STRING(str);
1292 if (!s) {
1293 return NULL;
1294 }
1295
1296 strcpy(s, first_str);
1297 s += strlen(first_str);
1298 *s++ = '.';
1299 strcpy(s, second_str);
1300 s += strlen(second_str);
1301 *s = '\0';
1302
1303 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1304 Py_DECREF(str);
1305 if (!uni) {
1306 return NULL;
1307 }
1308 PyUnicode_InternInPlace(&uni);
1309 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1310 Py_DECREF(uni);
1311 return NULL;
1312 }
1313
1314 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1315}
1316
1317/* Counts the total number of dots in seq's tokens */
1318int
1319_PyPegen_seq_count_dots(asdl_seq *seq)
1320{
1321 int number_of_dots = 0;
1322 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1323 Token *current_expr = asdl_seq_GET(seq, i);
1324 switch (current_expr->type) {
1325 case ELLIPSIS:
1326 number_of_dots += 3;
1327 break;
1328 case DOT:
1329 number_of_dots += 1;
1330 break;
1331 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001332 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001333 }
1334 }
1335
1336 return number_of_dots;
1337}
1338
1339/* Creates an alias with '*' as the identifier name */
1340alias_ty
1341_PyPegen_alias_for_star(Parser *p)
1342{
1343 PyObject *str = PyUnicode_InternFromString("*");
1344 if (!str) {
1345 return NULL;
1346 }
1347 if (PyArena_AddPyObject(p->arena, str) < 0) {
1348 Py_DECREF(str);
1349 return NULL;
1350 }
1351 return alias(str, NULL, p->arena);
1352}
1353
1354/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1355asdl_seq *
1356_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1357{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001358 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001359 assert(len > 0);
1360
1361 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1362 if (!new_seq) {
1363 return NULL;
1364 }
1365 for (Py_ssize_t i = 0; i < len; i++) {
1366 expr_ty e = asdl_seq_GET(seq, i);
1367 asdl_seq_SET(new_seq, i, e->v.Name.id);
1368 }
1369 return new_seq;
1370}
1371
1372/* Constructs a CmpopExprPair */
1373CmpopExprPair *
1374_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1375{
1376 assert(expr != NULL);
1377 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1378 if (!a) {
1379 return NULL;
1380 }
1381 a->cmpop = cmpop;
1382 a->expr = expr;
1383 return a;
1384}
1385
1386asdl_int_seq *
1387_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1388{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001389 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001390 assert(len > 0);
1391
1392 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1393 if (!new_seq) {
1394 return NULL;
1395 }
1396 for (Py_ssize_t i = 0; i < len; i++) {
1397 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1398 asdl_seq_SET(new_seq, i, pair->cmpop);
1399 }
1400 return new_seq;
1401}
1402
1403asdl_seq *
1404_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1405{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001406 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001407 assert(len > 0);
1408
1409 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1410 if (!new_seq) {
1411 return NULL;
1412 }
1413 for (Py_ssize_t i = 0; i < len; i++) {
1414 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1415 asdl_seq_SET(new_seq, i, pair->expr);
1416 }
1417 return new_seq;
1418}
1419
1420/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1421static asdl_seq *
1422_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1423{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001424 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001425 if (len == 0) {
1426 return NULL;
1427 }
1428
1429 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1430 if (!new_seq) {
1431 return NULL;
1432 }
1433 for (Py_ssize_t i = 0; i < len; i++) {
1434 expr_ty e = asdl_seq_GET(seq, i);
1435 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1436 }
1437 return new_seq;
1438}
1439
1440static expr_ty
1441_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1442{
1443 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1444}
1445
1446static expr_ty
1447_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1448{
1449 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1450}
1451
1452static expr_ty
1453_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1454{
1455 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1456}
1457
1458static expr_ty
1459_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1460{
1461 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1462}
1463
1464static expr_ty
1465_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1466{
1467 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1468}
1469
1470static expr_ty
1471_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1472{
1473 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1474}
1475
1476/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1477expr_ty
1478_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1479{
1480 assert(expr != NULL);
1481
1482 expr_ty new = NULL;
1483 switch (expr->kind) {
1484 case Name_kind:
1485 new = _set_name_context(p, expr, ctx);
1486 break;
1487 case Tuple_kind:
1488 new = _set_tuple_context(p, expr, ctx);
1489 break;
1490 case List_kind:
1491 new = _set_list_context(p, expr, ctx);
1492 break;
1493 case Subscript_kind:
1494 new = _set_subscript_context(p, expr, ctx);
1495 break;
1496 case Attribute_kind:
1497 new = _set_attribute_context(p, expr, ctx);
1498 break;
1499 case Starred_kind:
1500 new = _set_starred_context(p, expr, ctx);
1501 break;
1502 default:
1503 new = expr;
1504 }
1505 return new;
1506}
1507
1508/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1509KeyValuePair *
1510_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1511{
1512 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1513 if (!a) {
1514 return NULL;
1515 }
1516 a->key = key;
1517 a->value = value;
1518 return a;
1519}
1520
1521/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1522asdl_seq *
1523_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1524{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001525 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001526 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1527 if (!new_seq) {
1528 return NULL;
1529 }
1530 for (Py_ssize_t i = 0; i < len; i++) {
1531 KeyValuePair *pair = asdl_seq_GET(seq, i);
1532 asdl_seq_SET(new_seq, i, pair->key);
1533 }
1534 return new_seq;
1535}
1536
1537/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1538asdl_seq *
1539_PyPegen_get_values(Parser *p, asdl_seq *seq)
1540{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001541 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001542 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1543 if (!new_seq) {
1544 return NULL;
1545 }
1546 for (Py_ssize_t i = 0; i < len; i++) {
1547 KeyValuePair *pair = asdl_seq_GET(seq, i);
1548 asdl_seq_SET(new_seq, i, pair->value);
1549 }
1550 return new_seq;
1551}
1552
1553/* Constructs a NameDefaultPair */
1554NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001555_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001556{
1557 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1558 if (!a) {
1559 return NULL;
1560 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001561 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001562 a->value = value;
1563 return a;
1564}
1565
1566/* Constructs a SlashWithDefault */
1567SlashWithDefault *
1568_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1569{
1570 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1571 if (!a) {
1572 return NULL;
1573 }
1574 a->plain_names = plain_names;
1575 a->names_with_defaults = names_with_defaults;
1576 return a;
1577}
1578
1579/* Constructs a StarEtc */
1580StarEtc *
1581_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1582{
1583 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1584 if (!a) {
1585 return NULL;
1586 }
1587 a->vararg = vararg;
1588 a->kwonlyargs = kwonlyargs;
1589 a->kwarg = kwarg;
1590 return a;
1591}
1592
1593asdl_seq *
1594_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1595{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001596 Py_ssize_t first_len = asdl_seq_LEN(a);
1597 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001598 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1599 if (!new_seq) {
1600 return NULL;
1601 }
1602
1603 int k = 0;
1604 for (Py_ssize_t i = 0; i < first_len; i++) {
1605 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1606 }
1607 for (Py_ssize_t i = 0; i < second_len; i++) {
1608 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1609 }
1610
1611 return new_seq;
1612}
1613
1614static asdl_seq *
1615_get_names(Parser *p, asdl_seq *names_with_defaults)
1616{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001617 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001618 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1619 if (!seq) {
1620 return NULL;
1621 }
1622 for (Py_ssize_t i = 0; i < len; i++) {
1623 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1624 asdl_seq_SET(seq, i, pair->arg);
1625 }
1626 return seq;
1627}
1628
1629static asdl_seq *
1630_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1631{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001632 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001633 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1634 if (!seq) {
1635 return NULL;
1636 }
1637 for (Py_ssize_t i = 0; i < len; i++) {
1638 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1639 asdl_seq_SET(seq, i, pair->value);
1640 }
1641 return seq;
1642}
1643
1644/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1645arguments_ty
1646_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1647 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1648 asdl_seq *names_with_default, StarEtc *star_etc)
1649{
1650 asdl_seq *posonlyargs;
1651 if (slash_without_default != NULL) {
1652 posonlyargs = slash_without_default;
1653 }
1654 else if (slash_with_default != NULL) {
1655 asdl_seq *slash_with_default_names =
1656 _get_names(p, slash_with_default->names_with_defaults);
1657 if (!slash_with_default_names) {
1658 return NULL;
1659 }
1660 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1661 if (!posonlyargs) {
1662 return NULL;
1663 }
1664 }
1665 else {
1666 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1667 if (!posonlyargs) {
1668 return NULL;
1669 }
1670 }
1671
1672 asdl_seq *posargs;
1673 if (plain_names != NULL && names_with_default != NULL) {
1674 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1675 if (!names_with_default_names) {
1676 return NULL;
1677 }
1678 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1679 if (!posargs) {
1680 return NULL;
1681 }
1682 }
1683 else if (plain_names == NULL && names_with_default != NULL) {
1684 posargs = _get_names(p, names_with_default);
1685 if (!posargs) {
1686 return NULL;
1687 }
1688 }
1689 else if (plain_names != NULL && names_with_default == NULL) {
1690 posargs = plain_names;
1691 }
1692 else {
1693 posargs = _Py_asdl_seq_new(0, p->arena);
1694 if (!posargs) {
1695 return NULL;
1696 }
1697 }
1698
1699 asdl_seq *posdefaults;
1700 if (slash_with_default != NULL && names_with_default != NULL) {
1701 asdl_seq *slash_with_default_values =
1702 _get_defaults(p, slash_with_default->names_with_defaults);
1703 if (!slash_with_default_values) {
1704 return NULL;
1705 }
1706 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1707 if (!names_with_default_values) {
1708 return NULL;
1709 }
1710 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1711 if (!posdefaults) {
1712 return NULL;
1713 }
1714 }
1715 else if (slash_with_default == NULL && names_with_default != NULL) {
1716 posdefaults = _get_defaults(p, names_with_default);
1717 if (!posdefaults) {
1718 return NULL;
1719 }
1720 }
1721 else if (slash_with_default != NULL && names_with_default == NULL) {
1722 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1723 if (!posdefaults) {
1724 return NULL;
1725 }
1726 }
1727 else {
1728 posdefaults = _Py_asdl_seq_new(0, p->arena);
1729 if (!posdefaults) {
1730 return NULL;
1731 }
1732 }
1733
1734 arg_ty vararg = NULL;
1735 if (star_etc != NULL && star_etc->vararg != NULL) {
1736 vararg = star_etc->vararg;
1737 }
1738
1739 asdl_seq *kwonlyargs;
1740 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1741 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1742 if (!kwonlyargs) {
1743 return NULL;
1744 }
1745 }
1746 else {
1747 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1748 if (!kwonlyargs) {
1749 return NULL;
1750 }
1751 }
1752
1753 asdl_seq *kwdefaults;
1754 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1755 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1756 if (!kwdefaults) {
1757 return NULL;
1758 }
1759 }
1760 else {
1761 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1762 if (!kwdefaults) {
1763 return NULL;
1764 }
1765 }
1766
1767 arg_ty kwarg = NULL;
1768 if (star_etc != NULL && star_etc->kwarg != NULL) {
1769 kwarg = star_etc->kwarg;
1770 }
1771
1772 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1773 posdefaults, p->arena);
1774}
1775
1776/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1777 * arguments. */
1778arguments_ty
1779_PyPegen_empty_arguments(Parser *p)
1780{
1781 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1782 if (!posonlyargs) {
1783 return NULL;
1784 }
1785 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1786 if (!posargs) {
1787 return NULL;
1788 }
1789 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1790 if (!posdefaults) {
1791 return NULL;
1792 }
1793 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1794 if (!kwonlyargs) {
1795 return NULL;
1796 }
1797 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1798 if (!kwdefaults) {
1799 return NULL;
1800 }
1801
1802 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1803 p->arena);
1804}
1805
1806/* Encapsulates the value of an operator_ty into an AugOperator struct */
1807AugOperator *
1808_PyPegen_augoperator(Parser *p, operator_ty kind)
1809{
1810 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1811 if (!a) {
1812 return NULL;
1813 }
1814 a->kind = kind;
1815 return a;
1816}
1817
1818/* Construct a FunctionDef equivalent to function_def, but with decorators */
1819stmt_ty
1820_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1821{
1822 assert(function_def != NULL);
1823 if (function_def->kind == AsyncFunctionDef_kind) {
1824 return _Py_AsyncFunctionDef(
1825 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1826 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1827 function_def->v.FunctionDef.type_comment, function_def->lineno,
1828 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1829 p->arena);
1830 }
1831
1832 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1833 function_def->v.FunctionDef.body, decorators,
1834 function_def->v.FunctionDef.returns,
1835 function_def->v.FunctionDef.type_comment, function_def->lineno,
1836 function_def->col_offset, function_def->end_lineno,
1837 function_def->end_col_offset, p->arena);
1838}
1839
1840/* Construct a ClassDef equivalent to class_def, but with decorators */
1841stmt_ty
1842_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1843{
1844 assert(class_def != NULL);
1845 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1846 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1847 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1848 class_def->end_col_offset, p->arena);
1849}
1850
1851/* Construct a KeywordOrStarred */
1852KeywordOrStarred *
1853_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1854{
1855 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1856 if (!a) {
1857 return NULL;
1858 }
1859 a->element = element;
1860 a->is_keyword = is_keyword;
1861 return a;
1862}
1863
1864/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1865static int
1866_seq_number_of_starred_exprs(asdl_seq *seq)
1867{
1868 int n = 0;
1869 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1870 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1871 if (!k->is_keyword) {
1872 n++;
1873 }
1874 }
1875 return n;
1876}
1877
1878/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1879asdl_seq *
1880_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1881{
1882 int new_len = _seq_number_of_starred_exprs(kwargs);
1883 if (new_len == 0) {
1884 return NULL;
1885 }
1886 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1887 if (!new_seq) {
1888 return NULL;
1889 }
1890
1891 int idx = 0;
1892 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1893 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1894 if (!k->is_keyword) {
1895 asdl_seq_SET(new_seq, idx++, k->element);
1896 }
1897 }
1898 return new_seq;
1899}
1900
1901/* Return a new asdl_seq* with only the keywords in kwargs */
1902asdl_seq *
1903_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1904{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001905 Py_ssize_t len = asdl_seq_LEN(kwargs);
1906 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001907 if (new_len == 0) {
1908 return NULL;
1909 }
1910 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1911 if (!new_seq) {
1912 return NULL;
1913 }
1914
1915 int idx = 0;
1916 for (Py_ssize_t i = 0; i < len; i++) {
1917 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1918 if (k->is_keyword) {
1919 asdl_seq_SET(new_seq, idx++, k->element);
1920 }
1921 }
1922 return new_seq;
1923}
1924
1925expr_ty
1926_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1927{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001928 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001929 assert(len > 0);
1930
1931 Token *first = asdl_seq_GET(strings, 0);
1932 Token *last = asdl_seq_GET(strings, len - 1);
1933
1934 int bytesmode = 0;
1935 PyObject *bytes_str = NULL;
1936
1937 FstringParser state;
1938 _PyPegen_FstringParser_Init(&state);
1939
1940 for (Py_ssize_t i = 0; i < len; i++) {
1941 Token *t = asdl_seq_GET(strings, i);
1942
1943 int this_bytesmode;
1944 int this_rawmode;
1945 PyObject *s;
1946 const char *fstr;
1947 Py_ssize_t fstrlen = -1;
1948
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001949 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001950 goto error;
1951 }
1952
1953 /* Check that we are not mixing bytes with unicode. */
1954 if (i != 0 && bytesmode != this_bytesmode) {
1955 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1956 Py_XDECREF(s);
1957 goto error;
1958 }
1959 bytesmode = this_bytesmode;
1960
1961 if (fstr != NULL) {
1962 assert(s == NULL && !bytesmode);
1963
1964 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
1965 this_rawmode, 0, first, t, last);
1966 if (result < 0) {
1967 goto error;
1968 }
1969 }
1970 else {
1971 /* String or byte string. */
1972 assert(s != NULL && fstr == NULL);
1973 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
1974
1975 if (bytesmode) {
1976 if (i == 0) {
1977 bytes_str = s;
1978 }
1979 else {
1980 PyBytes_ConcatAndDel(&bytes_str, s);
1981 if (!bytes_str) {
1982 goto error;
1983 }
1984 }
1985 }
1986 else {
1987 /* This is a regular string. Concatenate it. */
1988 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
1989 goto error;
1990 }
1991 }
1992 }
1993 }
1994
1995 if (bytesmode) {
1996 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
1997 goto error;
1998 }
1999 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2000 last->end_col_offset, p->arena);
2001 }
2002
2003 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2004
2005error:
2006 Py_XDECREF(bytes_str);
2007 _PyPegen_FstringParser_Dealloc(&state);
2008 if (PyErr_Occurred()) {
2009 raise_decode_error(p);
2010 }
2011 return NULL;
2012}
Guido van Rossumc001c092020-04-30 12:12:19 -07002013
2014mod_ty
2015_PyPegen_make_module(Parser *p, asdl_seq *a) {
2016 asdl_seq *type_ignores = NULL;
2017 Py_ssize_t num = p->type_ignore_comments.num_items;
2018 if (num > 0) {
2019 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2020 type_ignores = _Py_asdl_seq_new(num, p->arena);
2021 if (type_ignores == NULL) {
2022 return NULL;
2023 }
2024 for (int i = 0; i < num; i++) {
2025 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2026 if (tag == NULL) {
2027 return NULL;
2028 }
2029 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2030 if (ti == NULL) {
2031 return NULL;
2032 }
2033 asdl_seq_SET(type_ignores, i, ti);
2034 }
2035 }
2036 return Module(a, type_ignores, p->arena);
2037}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002038
2039// Error reporting helpers
2040
2041expr_ty
2042_PyPegen_get_invalid_target(expr_ty e)
2043{
2044 if (e == NULL) {
2045 return NULL;
2046 }
2047
2048#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2049 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2050 for (Py_ssize_t i = 0; i < len; i++) {\
2051 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2052 expr_ty child = _PyPegen_get_invalid_target(other);\
2053 if (child != NULL) {\
2054 return child;\
2055 }\
2056 }\
2057 } while (0)
2058
2059 // We only need to visit List and Tuple nodes recursively as those
2060 // are the only ones that can contain valid names in targets when
2061 // they are parsed as expressions. Any other kind of expression
2062 // that is a container (like Sets or Dicts) is directly invalid and
2063 // we don't need to visit it recursively.
2064
2065 switch (e->kind) {
2066 case List_kind: {
2067 VISIT_CONTAINER(e, List);
2068 return NULL;
2069 }
2070 case Tuple_kind: {
2071 VISIT_CONTAINER(e, Tuple);
2072 return NULL;
2073 }
2074 case Starred_kind:
2075 return _PyPegen_get_invalid_target(e->v.Starred.value);
2076 case Name_kind:
2077 case Subscript_kind:
2078 case Attribute_kind:
2079 return NULL;
2080 default:
2081 return e;
2082 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002083}
2084
2085void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2086 int kwarg_unpacking = 0;
2087 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2088 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2089 if (!keyword->arg) {
2090 kwarg_unpacking = 1;
2091 }
2092 }
2093
2094 const char *msg = NULL;
2095 if (kwarg_unpacking) {
2096 msg = "positional argument follows keyword argument unpacking";
2097 } else {
2098 msg = "positional argument follows keyword argument";
2099 }
2100
2101 return RAISE_SYNTAX_ERROR(msg);
2102}