blob: ee30c2c0688f89026c405b6e5dd632d3fb037ff0 [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
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700756expr_ty
757_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
758{
759 if (p->mark == p->fill) {
760 if (_PyPegen_fill_token(p) < 0) {
761 p->error_indicator = 1;
762 return NULL;
763 }
764 }
765 Token *t = p->tokens[p->mark];
766 if (t->type != NAME) {
767 return NULL;
768 }
769 char* s = PyBytes_AsString(t->bytes);
770 if (!s) {
771 return NULL;
772 }
773 if (strcmp(s, keyword) != 0) {
774 return NULL;
775 }
776 expr_ty res = _PyPegen_name_token(p);
777 return res;
778}
779
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100780Token *
781_PyPegen_get_last_nonnwhitespace_token(Parser *p)
782{
783 assert(p->mark >= 0);
784 Token *token = NULL;
785 for (int m = p->mark - 1; m >= 0; m--) {
786 token = p->tokens[m];
787 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
788 break;
789 }
790 }
791 return token;
792}
793
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100794expr_ty
795_PyPegen_name_token(Parser *p)
796{
797 Token *t = _PyPegen_expect_token(p, NAME);
798 if (t == NULL) {
799 return NULL;
800 }
801 char* s = PyBytes_AsString(t->bytes);
802 if (!s) {
803 return NULL;
804 }
805 PyObject *id = _PyPegen_new_identifier(p, s);
806 if (id == NULL) {
807 return NULL;
808 }
809 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
810 p->arena);
811}
812
813void *
814_PyPegen_string_token(Parser *p)
815{
816 return _PyPegen_expect_token(p, STRING);
817}
818
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100819static PyObject *
820parsenumber_raw(const char *s)
821{
822 const char *end;
823 long x;
824 double dx;
825 Py_complex compl;
826 int imflag;
827
828 assert(s != NULL);
829 errno = 0;
830 end = s + strlen(s) - 1;
831 imflag = *end == 'j' || *end == 'J';
832 if (s[0] == '0') {
833 x = (long)PyOS_strtoul(s, (char **)&end, 0);
834 if (x < 0 && errno == 0) {
835 return PyLong_FromString(s, (char **)0, 0);
836 }
837 }
838 else
839 x = PyOS_strtol(s, (char **)&end, 0);
840 if (*end == '\0') {
841 if (errno != 0)
842 return PyLong_FromString(s, (char **)0, 0);
843 return PyLong_FromLong(x);
844 }
845 /* XXX Huge floats may silently fail */
846 if (imflag) {
847 compl.real = 0.;
848 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
849 if (compl.imag == -1.0 && PyErr_Occurred())
850 return NULL;
851 return PyComplex_FromCComplex(compl);
852 }
853 else {
854 dx = PyOS_string_to_double(s, NULL, NULL);
855 if (dx == -1.0 && PyErr_Occurred())
856 return NULL;
857 return PyFloat_FromDouble(dx);
858 }
859}
860
861static PyObject *
862parsenumber(const char *s)
863{
864 char *dup, *end;
865 PyObject *res = NULL;
866
867 assert(s != NULL);
868
869 if (strchr(s, '_') == NULL) {
870 return parsenumber_raw(s);
871 }
872 /* Create a duplicate without underscores. */
873 dup = PyMem_Malloc(strlen(s) + 1);
874 if (dup == NULL) {
875 return PyErr_NoMemory();
876 }
877 end = dup;
878 for (; *s; s++) {
879 if (*s != '_') {
880 *end++ = *s;
881 }
882 }
883 *end = '\0';
884 res = parsenumber_raw(dup);
885 PyMem_Free(dup);
886 return res;
887}
888
889expr_ty
890_PyPegen_number_token(Parser *p)
891{
892 Token *t = _PyPegen_expect_token(p, NUMBER);
893 if (t == NULL) {
894 return NULL;
895 }
896
897 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100898 if (num_raw == NULL) {
899 return NULL;
900 }
901
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300902 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
903 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700904 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300905 "in Python 3.6 and greater");
906 }
907
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100908 PyObject *c = parsenumber(num_raw);
909
910 if (c == NULL) {
911 return NULL;
912 }
913
914 if (PyArena_AddPyObject(p->arena, c) < 0) {
915 Py_DECREF(c);
916 return NULL;
917 }
918
919 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
920 p->arena);
921}
922
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300923static int // bool
924newline_in_string(Parser *p, const char *cur)
925{
926 for (char c = *cur; cur >= p->tok->buf; c = *--cur) {
927 if (c == '\'' || c == '"') {
928 return 1;
929 }
930 }
931 return 0;
932}
933
934/* Check that the source for a single input statement really is a single
935 statement by looking at what is left in the buffer after parsing.
936 Trailing whitespace and comments are OK. */
937static int // bool
938bad_single_statement(Parser *p)
939{
940 const char *cur = strchr(p->tok->buf, '\n');
941
942 /* Newlines are allowed if preceded by a line continuation character
943 or if they appear inside a string. */
944 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
945 return 0;
946 }
947 char c = *cur;
948
949 for (;;) {
950 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
951 c = *++cur;
952 }
953
954 if (!c) {
955 return 0;
956 }
957
958 if (c != '#') {
959 return 1;
960 }
961
962 /* Suck up comment. */
963 while (c && c != '\n') {
964 c = *++cur;
965 }
966 }
967}
968
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100969void
970_PyPegen_Parser_Free(Parser *p)
971{
972 Py_XDECREF(p->normalize);
973 for (int i = 0; i < p->size; i++) {
974 PyMem_Free(p->tokens[i]);
975 }
976 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700977 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100978 PyMem_Free(p);
979}
980
Pablo Galindo2b74c832020-04-27 18:02:07 +0100981static int
982compute_parser_flags(PyCompilerFlags *flags)
983{
984 int parser_flags = 0;
985 if (!flags) {
986 return 0;
987 }
988 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
989 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
990 }
991 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
992 parser_flags |= PyPARSE_IGNORE_COOKIE;
993 }
994 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
995 parser_flags |= PyPARSE_BARRY_AS_BDFL;
996 }
997 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
998 parser_flags |= PyPARSE_TYPE_COMMENTS;
999 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001000 if (flags->cf_feature_version < 7) {
1001 parser_flags |= PyPARSE_ASYNC_HACKS;
1002 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001003 return parser_flags;
1004}
1005
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001006Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001007_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001008 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001009{
1010 Parser *p = PyMem_Malloc(sizeof(Parser));
1011 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001012 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001013 }
1014 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001015 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1016 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001017 p->tok = tok;
1018 p->keywords = NULL;
1019 p->n_keyword_lists = -1;
1020 p->tokens = PyMem_Malloc(sizeof(Token *));
1021 if (!p->tokens) {
1022 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001023 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001024 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001025 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001026 if (!p->tokens) {
1027 PyMem_Free(p->tokens);
1028 PyMem_Free(p);
1029 return (Parser *) PyErr_NoMemory();
1030 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001031 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1032 PyMem_Free(p->tokens[0]);
1033 PyMem_Free(p->tokens);
1034 PyMem_Free(p);
1035 return (Parser *) PyErr_NoMemory();
1036 }
1037
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001038 p->mark = 0;
1039 p->fill = 0;
1040 p->size = 1;
1041
1042 p->errcode = errcode;
1043 p->arena = arena;
1044 p->start_rule = start_rule;
1045 p->parsing_started = 0;
1046 p->normalize = NULL;
1047 p->error_indicator = 0;
1048
1049 p->starting_lineno = 0;
1050 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001051 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001052 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001053 p->known_err_token = NULL;
Pablo Galindo800a35c62020-05-25 18:38:45 +01001054 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001055
1056 return p;
1057}
1058
1059void *
1060_PyPegen_run_parser(Parser *p)
1061{
1062 void *res = _PyPegen_parse(p);
1063 if (res == NULL) {
1064 if (PyErr_Occurred()) {
1065 return NULL;
1066 }
1067 if (p->fill == 0) {
1068 RAISE_SYNTAX_ERROR("error at start before reading any input");
1069 }
1070 else if (p->tok->done == E_EOF) {
1071 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1072 }
1073 else {
1074 if (p->tokens[p->fill-1]->type == INDENT) {
1075 RAISE_INDENTATION_ERROR("unexpected indent");
1076 }
1077 else if (p->tokens[p->fill-1]->type == DEDENT) {
1078 RAISE_INDENTATION_ERROR("unexpected unindent");
1079 }
1080 else {
1081 RAISE_SYNTAX_ERROR("invalid syntax");
1082 }
1083 }
1084 return NULL;
1085 }
1086
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001087 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1088 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1089 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1090 }
1091
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001092 return res;
1093}
1094
1095mod_ty
1096_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1097 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001098 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001099{
1100 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1101 if (tok == NULL) {
1102 if (PyErr_Occurred()) {
1103 raise_tokenizer_init_error(filename_ob);
1104 return NULL;
1105 }
1106 return NULL;
1107 }
1108 // This transfers the ownership to the tokenizer
1109 tok->filename = filename_ob;
1110 Py_INCREF(filename_ob);
1111
1112 // From here on we need to clean up even if there's an error
1113 mod_ty result = NULL;
1114
Pablo Galindo2b74c832020-04-27 18:02:07 +01001115 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001116 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1117 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001118 if (p == NULL) {
1119 goto error;
1120 }
1121
1122 result = _PyPegen_run_parser(p);
1123 _PyPegen_Parser_Free(p);
1124
1125error:
1126 PyTokenizer_Free(tok);
1127 return result;
1128}
1129
1130mod_ty
1131_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001132 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001133{
1134 FILE *fp = fopen(filename, "rb");
1135 if (fp == NULL) {
1136 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1137 return NULL;
1138 }
1139
1140 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001141 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001142
1143 fclose(fp);
1144 return result;
1145}
1146
1147mod_ty
1148_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001149 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001150{
1151 int exec_input = start_rule == Py_file_input;
1152
1153 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001154 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001155 tok = PyTokenizer_FromUTF8(str, exec_input);
1156 } else {
1157 tok = PyTokenizer_FromString(str, exec_input);
1158 }
1159 if (tok == NULL) {
1160 if (PyErr_Occurred()) {
1161 raise_tokenizer_init_error(filename_ob);
1162 }
1163 return NULL;
1164 }
1165 // This transfers the ownership to the tokenizer
1166 tok->filename = filename_ob;
1167 Py_INCREF(filename_ob);
1168
1169 // We need to clear up from here on
1170 mod_ty result = NULL;
1171
Pablo Galindo2b74c832020-04-27 18:02:07 +01001172 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001173 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001174 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1175 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001176 if (p == NULL) {
1177 goto error;
1178 }
1179
1180 result = _PyPegen_run_parser(p);
1181 _PyPegen_Parser_Free(p);
1182
1183error:
1184 PyTokenizer_Free(tok);
1185 return result;
1186}
1187
1188void *
1189_PyPegen_interactive_exit(Parser *p)
1190{
1191 if (p->errcode) {
1192 *(p->errcode) = E_EOF;
1193 }
1194 return NULL;
1195}
1196
1197/* Creates a single-element asdl_seq* that contains a */
1198asdl_seq *
1199_PyPegen_singleton_seq(Parser *p, void *a)
1200{
1201 assert(a != NULL);
1202 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1203 if (!seq) {
1204 return NULL;
1205 }
1206 asdl_seq_SET(seq, 0, a);
1207 return seq;
1208}
1209
1210/* Creates a copy of seq and prepends a to it */
1211asdl_seq *
1212_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1213{
1214 assert(a != NULL);
1215 if (!seq) {
1216 return _PyPegen_singleton_seq(p, a);
1217 }
1218
1219 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1220 if (!new_seq) {
1221 return NULL;
1222 }
1223
1224 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001225 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001226 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1227 }
1228 return new_seq;
1229}
1230
Guido van Rossumc001c092020-04-30 12:12:19 -07001231/* Creates a copy of seq and appends a to it */
1232asdl_seq *
1233_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1234{
1235 assert(a != NULL);
1236 if (!seq) {
1237 return _PyPegen_singleton_seq(p, a);
1238 }
1239
1240 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1241 if (!new_seq) {
1242 return NULL;
1243 }
1244
1245 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1246 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1247 }
1248 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1249 return new_seq;
1250}
1251
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001252static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001253_get_flattened_seq_size(asdl_seq *seqs)
1254{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001255 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001256 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1257 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1258 size += asdl_seq_LEN(inner_seq);
1259 }
1260 return size;
1261}
1262
1263/* Flattens an asdl_seq* of asdl_seq*s */
1264asdl_seq *
1265_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1266{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001267 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001268 assert(flattened_seq_size > 0);
1269
1270 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1271 if (!flattened_seq) {
1272 return NULL;
1273 }
1274
1275 int flattened_seq_idx = 0;
1276 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1277 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001278 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001279 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1280 }
1281 }
1282 assert(flattened_seq_idx == flattened_seq_size);
1283
1284 return flattened_seq;
1285}
1286
1287/* Creates a new name of the form <first_name>.<second_name> */
1288expr_ty
1289_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1290{
1291 assert(first_name != NULL && second_name != NULL);
1292 PyObject *first_identifier = first_name->v.Name.id;
1293 PyObject *second_identifier = second_name->v.Name.id;
1294
1295 if (PyUnicode_READY(first_identifier) == -1) {
1296 return NULL;
1297 }
1298 if (PyUnicode_READY(second_identifier) == -1) {
1299 return NULL;
1300 }
1301 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1302 if (!first_str) {
1303 return NULL;
1304 }
1305 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1306 if (!second_str) {
1307 return NULL;
1308 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001309 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001310
1311 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1312 if (!str) {
1313 return NULL;
1314 }
1315
1316 char *s = PyBytes_AS_STRING(str);
1317 if (!s) {
1318 return NULL;
1319 }
1320
1321 strcpy(s, first_str);
1322 s += strlen(first_str);
1323 *s++ = '.';
1324 strcpy(s, second_str);
1325 s += strlen(second_str);
1326 *s = '\0';
1327
1328 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1329 Py_DECREF(str);
1330 if (!uni) {
1331 return NULL;
1332 }
1333 PyUnicode_InternInPlace(&uni);
1334 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1335 Py_DECREF(uni);
1336 return NULL;
1337 }
1338
1339 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1340}
1341
1342/* Counts the total number of dots in seq's tokens */
1343int
1344_PyPegen_seq_count_dots(asdl_seq *seq)
1345{
1346 int number_of_dots = 0;
1347 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1348 Token *current_expr = asdl_seq_GET(seq, i);
1349 switch (current_expr->type) {
1350 case ELLIPSIS:
1351 number_of_dots += 3;
1352 break;
1353 case DOT:
1354 number_of_dots += 1;
1355 break;
1356 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001357 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001358 }
1359 }
1360
1361 return number_of_dots;
1362}
1363
1364/* Creates an alias with '*' as the identifier name */
1365alias_ty
1366_PyPegen_alias_for_star(Parser *p)
1367{
1368 PyObject *str = PyUnicode_InternFromString("*");
1369 if (!str) {
1370 return NULL;
1371 }
1372 if (PyArena_AddPyObject(p->arena, str) < 0) {
1373 Py_DECREF(str);
1374 return NULL;
1375 }
1376 return alias(str, NULL, p->arena);
1377}
1378
1379/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1380asdl_seq *
1381_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1382{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001383 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001384 assert(len > 0);
1385
1386 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1387 if (!new_seq) {
1388 return NULL;
1389 }
1390 for (Py_ssize_t i = 0; i < len; i++) {
1391 expr_ty e = asdl_seq_GET(seq, i);
1392 asdl_seq_SET(new_seq, i, e->v.Name.id);
1393 }
1394 return new_seq;
1395}
1396
1397/* Constructs a CmpopExprPair */
1398CmpopExprPair *
1399_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1400{
1401 assert(expr != NULL);
1402 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1403 if (!a) {
1404 return NULL;
1405 }
1406 a->cmpop = cmpop;
1407 a->expr = expr;
1408 return a;
1409}
1410
1411asdl_int_seq *
1412_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1413{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001414 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001415 assert(len > 0);
1416
1417 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1418 if (!new_seq) {
1419 return NULL;
1420 }
1421 for (Py_ssize_t i = 0; i < len; i++) {
1422 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1423 asdl_seq_SET(new_seq, i, pair->cmpop);
1424 }
1425 return new_seq;
1426}
1427
1428asdl_seq *
1429_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1430{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001431 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001432 assert(len > 0);
1433
1434 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1435 if (!new_seq) {
1436 return NULL;
1437 }
1438 for (Py_ssize_t i = 0; i < len; i++) {
1439 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1440 asdl_seq_SET(new_seq, i, pair->expr);
1441 }
1442 return new_seq;
1443}
1444
1445/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1446static asdl_seq *
1447_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1448{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001449 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001450 if (len == 0) {
1451 return NULL;
1452 }
1453
1454 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1455 if (!new_seq) {
1456 return NULL;
1457 }
1458 for (Py_ssize_t i = 0; i < len; i++) {
1459 expr_ty e = asdl_seq_GET(seq, i);
1460 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1461 }
1462 return new_seq;
1463}
1464
1465static expr_ty
1466_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1467{
1468 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1469}
1470
1471static expr_ty
1472_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1473{
1474 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1475}
1476
1477static expr_ty
1478_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1479{
1480 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1481}
1482
1483static expr_ty
1484_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1485{
1486 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1487}
1488
1489static expr_ty
1490_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1491{
1492 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1493}
1494
1495static expr_ty
1496_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1497{
1498 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1499}
1500
1501/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1502expr_ty
1503_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1504{
1505 assert(expr != NULL);
1506
1507 expr_ty new = NULL;
1508 switch (expr->kind) {
1509 case Name_kind:
1510 new = _set_name_context(p, expr, ctx);
1511 break;
1512 case Tuple_kind:
1513 new = _set_tuple_context(p, expr, ctx);
1514 break;
1515 case List_kind:
1516 new = _set_list_context(p, expr, ctx);
1517 break;
1518 case Subscript_kind:
1519 new = _set_subscript_context(p, expr, ctx);
1520 break;
1521 case Attribute_kind:
1522 new = _set_attribute_context(p, expr, ctx);
1523 break;
1524 case Starred_kind:
1525 new = _set_starred_context(p, expr, ctx);
1526 break;
1527 default:
1528 new = expr;
1529 }
1530 return new;
1531}
1532
1533/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1534KeyValuePair *
1535_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1536{
1537 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1538 if (!a) {
1539 return NULL;
1540 }
1541 a->key = key;
1542 a->value = value;
1543 return a;
1544}
1545
1546/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1547asdl_seq *
1548_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1549{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001550 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001551 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1552 if (!new_seq) {
1553 return NULL;
1554 }
1555 for (Py_ssize_t i = 0; i < len; i++) {
1556 KeyValuePair *pair = asdl_seq_GET(seq, i);
1557 asdl_seq_SET(new_seq, i, pair->key);
1558 }
1559 return new_seq;
1560}
1561
1562/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1563asdl_seq *
1564_PyPegen_get_values(Parser *p, asdl_seq *seq)
1565{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001566 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001567 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1568 if (!new_seq) {
1569 return NULL;
1570 }
1571 for (Py_ssize_t i = 0; i < len; i++) {
1572 KeyValuePair *pair = asdl_seq_GET(seq, i);
1573 asdl_seq_SET(new_seq, i, pair->value);
1574 }
1575 return new_seq;
1576}
1577
1578/* Constructs a NameDefaultPair */
1579NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001580_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001581{
1582 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1583 if (!a) {
1584 return NULL;
1585 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001586 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001587 a->value = value;
1588 return a;
1589}
1590
1591/* Constructs a SlashWithDefault */
1592SlashWithDefault *
1593_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1594{
1595 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1596 if (!a) {
1597 return NULL;
1598 }
1599 a->plain_names = plain_names;
1600 a->names_with_defaults = names_with_defaults;
1601 return a;
1602}
1603
1604/* Constructs a StarEtc */
1605StarEtc *
1606_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1607{
1608 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1609 if (!a) {
1610 return NULL;
1611 }
1612 a->vararg = vararg;
1613 a->kwonlyargs = kwonlyargs;
1614 a->kwarg = kwarg;
1615 return a;
1616}
1617
1618asdl_seq *
1619_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1620{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001621 Py_ssize_t first_len = asdl_seq_LEN(a);
1622 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001623 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1624 if (!new_seq) {
1625 return NULL;
1626 }
1627
1628 int k = 0;
1629 for (Py_ssize_t i = 0; i < first_len; i++) {
1630 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1631 }
1632 for (Py_ssize_t i = 0; i < second_len; i++) {
1633 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1634 }
1635
1636 return new_seq;
1637}
1638
1639static asdl_seq *
1640_get_names(Parser *p, asdl_seq *names_with_defaults)
1641{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001642 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001643 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1644 if (!seq) {
1645 return NULL;
1646 }
1647 for (Py_ssize_t i = 0; i < len; i++) {
1648 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1649 asdl_seq_SET(seq, i, pair->arg);
1650 }
1651 return seq;
1652}
1653
1654static asdl_seq *
1655_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1656{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001657 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001658 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1659 if (!seq) {
1660 return NULL;
1661 }
1662 for (Py_ssize_t i = 0; i < len; i++) {
1663 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1664 asdl_seq_SET(seq, i, pair->value);
1665 }
1666 return seq;
1667}
1668
1669/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1670arguments_ty
1671_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1672 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1673 asdl_seq *names_with_default, StarEtc *star_etc)
1674{
1675 asdl_seq *posonlyargs;
1676 if (slash_without_default != NULL) {
1677 posonlyargs = slash_without_default;
1678 }
1679 else if (slash_with_default != NULL) {
1680 asdl_seq *slash_with_default_names =
1681 _get_names(p, slash_with_default->names_with_defaults);
1682 if (!slash_with_default_names) {
1683 return NULL;
1684 }
1685 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1686 if (!posonlyargs) {
1687 return NULL;
1688 }
1689 }
1690 else {
1691 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1692 if (!posonlyargs) {
1693 return NULL;
1694 }
1695 }
1696
1697 asdl_seq *posargs;
1698 if (plain_names != NULL && names_with_default != NULL) {
1699 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1700 if (!names_with_default_names) {
1701 return NULL;
1702 }
1703 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1704 if (!posargs) {
1705 return NULL;
1706 }
1707 }
1708 else if (plain_names == NULL && names_with_default != NULL) {
1709 posargs = _get_names(p, names_with_default);
1710 if (!posargs) {
1711 return NULL;
1712 }
1713 }
1714 else if (plain_names != NULL && names_with_default == NULL) {
1715 posargs = plain_names;
1716 }
1717 else {
1718 posargs = _Py_asdl_seq_new(0, p->arena);
1719 if (!posargs) {
1720 return NULL;
1721 }
1722 }
1723
1724 asdl_seq *posdefaults;
1725 if (slash_with_default != NULL && names_with_default != NULL) {
1726 asdl_seq *slash_with_default_values =
1727 _get_defaults(p, slash_with_default->names_with_defaults);
1728 if (!slash_with_default_values) {
1729 return NULL;
1730 }
1731 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1732 if (!names_with_default_values) {
1733 return NULL;
1734 }
1735 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1736 if (!posdefaults) {
1737 return NULL;
1738 }
1739 }
1740 else if (slash_with_default == NULL && names_with_default != NULL) {
1741 posdefaults = _get_defaults(p, names_with_default);
1742 if (!posdefaults) {
1743 return NULL;
1744 }
1745 }
1746 else if (slash_with_default != NULL && names_with_default == NULL) {
1747 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1748 if (!posdefaults) {
1749 return NULL;
1750 }
1751 }
1752 else {
1753 posdefaults = _Py_asdl_seq_new(0, p->arena);
1754 if (!posdefaults) {
1755 return NULL;
1756 }
1757 }
1758
1759 arg_ty vararg = NULL;
1760 if (star_etc != NULL && star_etc->vararg != NULL) {
1761 vararg = star_etc->vararg;
1762 }
1763
1764 asdl_seq *kwonlyargs;
1765 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1766 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1767 if (!kwonlyargs) {
1768 return NULL;
1769 }
1770 }
1771 else {
1772 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1773 if (!kwonlyargs) {
1774 return NULL;
1775 }
1776 }
1777
1778 asdl_seq *kwdefaults;
1779 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1780 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1781 if (!kwdefaults) {
1782 return NULL;
1783 }
1784 }
1785 else {
1786 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1787 if (!kwdefaults) {
1788 return NULL;
1789 }
1790 }
1791
1792 arg_ty kwarg = NULL;
1793 if (star_etc != NULL && star_etc->kwarg != NULL) {
1794 kwarg = star_etc->kwarg;
1795 }
1796
1797 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1798 posdefaults, p->arena);
1799}
1800
1801/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1802 * arguments. */
1803arguments_ty
1804_PyPegen_empty_arguments(Parser *p)
1805{
1806 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1807 if (!posonlyargs) {
1808 return NULL;
1809 }
1810 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1811 if (!posargs) {
1812 return NULL;
1813 }
1814 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1815 if (!posdefaults) {
1816 return NULL;
1817 }
1818 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1819 if (!kwonlyargs) {
1820 return NULL;
1821 }
1822 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1823 if (!kwdefaults) {
1824 return NULL;
1825 }
1826
1827 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1828 p->arena);
1829}
1830
1831/* Encapsulates the value of an operator_ty into an AugOperator struct */
1832AugOperator *
1833_PyPegen_augoperator(Parser *p, operator_ty kind)
1834{
1835 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1836 if (!a) {
1837 return NULL;
1838 }
1839 a->kind = kind;
1840 return a;
1841}
1842
1843/* Construct a FunctionDef equivalent to function_def, but with decorators */
1844stmt_ty
1845_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1846{
1847 assert(function_def != NULL);
1848 if (function_def->kind == AsyncFunctionDef_kind) {
1849 return _Py_AsyncFunctionDef(
1850 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1851 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1852 function_def->v.FunctionDef.type_comment, function_def->lineno,
1853 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1854 p->arena);
1855 }
1856
1857 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1858 function_def->v.FunctionDef.body, decorators,
1859 function_def->v.FunctionDef.returns,
1860 function_def->v.FunctionDef.type_comment, function_def->lineno,
1861 function_def->col_offset, function_def->end_lineno,
1862 function_def->end_col_offset, p->arena);
1863}
1864
1865/* Construct a ClassDef equivalent to class_def, but with decorators */
1866stmt_ty
1867_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1868{
1869 assert(class_def != NULL);
1870 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1871 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1872 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1873 class_def->end_col_offset, p->arena);
1874}
1875
1876/* Construct a KeywordOrStarred */
1877KeywordOrStarred *
1878_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1879{
1880 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1881 if (!a) {
1882 return NULL;
1883 }
1884 a->element = element;
1885 a->is_keyword = is_keyword;
1886 return a;
1887}
1888
1889/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1890static int
1891_seq_number_of_starred_exprs(asdl_seq *seq)
1892{
1893 int n = 0;
1894 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1895 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1896 if (!k->is_keyword) {
1897 n++;
1898 }
1899 }
1900 return n;
1901}
1902
1903/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1904asdl_seq *
1905_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1906{
1907 int new_len = _seq_number_of_starred_exprs(kwargs);
1908 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, len = asdl_seq_LEN(kwargs); 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
1926/* Return a new asdl_seq* with only the keywords in kwargs */
1927asdl_seq *
1928_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1929{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001930 Py_ssize_t len = asdl_seq_LEN(kwargs);
1931 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001932 if (new_len == 0) {
1933 return NULL;
1934 }
1935 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1936 if (!new_seq) {
1937 return NULL;
1938 }
1939
1940 int idx = 0;
1941 for (Py_ssize_t i = 0; i < len; i++) {
1942 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1943 if (k->is_keyword) {
1944 asdl_seq_SET(new_seq, idx++, k->element);
1945 }
1946 }
1947 return new_seq;
1948}
1949
1950expr_ty
1951_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1952{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001953 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001954 assert(len > 0);
1955
1956 Token *first = asdl_seq_GET(strings, 0);
1957 Token *last = asdl_seq_GET(strings, len - 1);
1958
1959 int bytesmode = 0;
1960 PyObject *bytes_str = NULL;
1961
1962 FstringParser state;
1963 _PyPegen_FstringParser_Init(&state);
1964
1965 for (Py_ssize_t i = 0; i < len; i++) {
1966 Token *t = asdl_seq_GET(strings, i);
1967
1968 int this_bytesmode;
1969 int this_rawmode;
1970 PyObject *s;
1971 const char *fstr;
1972 Py_ssize_t fstrlen = -1;
1973
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001974 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001975 goto error;
1976 }
1977
1978 /* Check that we are not mixing bytes with unicode. */
1979 if (i != 0 && bytesmode != this_bytesmode) {
1980 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1981 Py_XDECREF(s);
1982 goto error;
1983 }
1984 bytesmode = this_bytesmode;
1985
1986 if (fstr != NULL) {
1987 assert(s == NULL && !bytesmode);
1988
1989 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
1990 this_rawmode, 0, first, t, last);
1991 if (result < 0) {
1992 goto error;
1993 }
1994 }
1995 else {
1996 /* String or byte string. */
1997 assert(s != NULL && fstr == NULL);
1998 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
1999
2000 if (bytesmode) {
2001 if (i == 0) {
2002 bytes_str = s;
2003 }
2004 else {
2005 PyBytes_ConcatAndDel(&bytes_str, s);
2006 if (!bytes_str) {
2007 goto error;
2008 }
2009 }
2010 }
2011 else {
2012 /* This is a regular string. Concatenate it. */
2013 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2014 goto error;
2015 }
2016 }
2017 }
2018 }
2019
2020 if (bytesmode) {
2021 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2022 goto error;
2023 }
2024 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2025 last->end_col_offset, p->arena);
2026 }
2027
2028 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2029
2030error:
2031 Py_XDECREF(bytes_str);
2032 _PyPegen_FstringParser_Dealloc(&state);
2033 if (PyErr_Occurred()) {
2034 raise_decode_error(p);
2035 }
2036 return NULL;
2037}
Guido van Rossumc001c092020-04-30 12:12:19 -07002038
2039mod_ty
2040_PyPegen_make_module(Parser *p, asdl_seq *a) {
2041 asdl_seq *type_ignores = NULL;
2042 Py_ssize_t num = p->type_ignore_comments.num_items;
2043 if (num > 0) {
2044 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2045 type_ignores = _Py_asdl_seq_new(num, p->arena);
2046 if (type_ignores == NULL) {
2047 return NULL;
2048 }
2049 for (int i = 0; i < num; i++) {
2050 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2051 if (tag == NULL) {
2052 return NULL;
2053 }
2054 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2055 if (ti == NULL) {
2056 return NULL;
2057 }
2058 asdl_seq_SET(type_ignores, i, ti);
2059 }
2060 }
2061 return Module(a, type_ignores, p->arena);
2062}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002063
2064// Error reporting helpers
2065
2066expr_ty
2067_PyPegen_get_invalid_target(expr_ty e)
2068{
2069 if (e == NULL) {
2070 return NULL;
2071 }
2072
2073#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2074 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2075 for (Py_ssize_t i = 0; i < len; i++) {\
2076 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2077 expr_ty child = _PyPegen_get_invalid_target(other);\
2078 if (child != NULL) {\
2079 return child;\
2080 }\
2081 }\
2082 } while (0)
2083
2084 // We only need to visit List and Tuple nodes recursively as those
2085 // are the only ones that can contain valid names in targets when
2086 // they are parsed as expressions. Any other kind of expression
2087 // that is a container (like Sets or Dicts) is directly invalid and
2088 // we don't need to visit it recursively.
2089
2090 switch (e->kind) {
2091 case List_kind: {
2092 VISIT_CONTAINER(e, List);
2093 return NULL;
2094 }
2095 case Tuple_kind: {
2096 VISIT_CONTAINER(e, Tuple);
2097 return NULL;
2098 }
2099 case Starred_kind:
2100 return _PyPegen_get_invalid_target(e->v.Starred.value);
2101 case Name_kind:
2102 case Subscript_kind:
2103 case Attribute_kind:
2104 return NULL;
2105 default:
2106 return e;
2107 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002108}
2109
2110void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2111 int kwarg_unpacking = 0;
2112 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2113 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2114 if (!keyword->arg) {
2115 kwarg_unpacking = 1;
2116 }
2117 }
2118
2119 const char *msg = NULL;
2120 if (kwarg_unpacking) {
2121 msg = "positional argument follows keyword argument unpacking";
2122 } else {
2123 msg = "positional argument follows keyword argument";
2124 }
2125
2126 return RAISE_SYNTAX_ERROR(msg);
2127}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002128
2129void *
2130_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2131{
2132 /* The rule that calls this function is 'args for_if_clauses'.
2133 For the input f(L, x for x in y), L and x are in args and
2134 the for is parsed as a for_if_clause. We have to check if
2135 len <= 1, so that input like dict((a, b) for a, b in x)
2136 gets successfully parsed and then we pass the last
2137 argument (x in the above example) as the location of the
2138 error */
2139 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2140 if (len <= 1) {
2141 return NULL;
2142 }
2143
2144 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2145 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2146 "Generator expression must be parenthesized"
2147 );
2148}