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