blob: 083088bd9657bd547f99c4869a73cb1fb0496a31 [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
303static inline PyObject *
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300304get_error_line(char *buffer, int is_file)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100305{
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300306 const char *newline;
307 if (is_file) {
308 newline = strrchr(buffer, '\n');
309 } else {
310 newline = strchr(buffer, '\n');
311 }
312
Pablo Galindo5b956ca2020-05-11 01:41:26 +0100313 if (is_file) {
314 while (newline > buffer && newline[-1] == '\n') {
315 --newline;
316 }
317 }
318
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100319 if (newline) {
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300320 return PyUnicode_DecodeUTF8(buffer, newline - buffer, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100321 }
322 else {
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300323 return PyUnicode_DecodeUTF8(buffer, strlen(buffer), "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100324 }
325}
326
327static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100328tokenizer_error(Parser *p)
329{
330 if (PyErr_Occurred()) {
331 return -1;
332 }
333
334 const char *msg = NULL;
335 PyObject* errtype = PyExc_SyntaxError;
336 switch (p->tok->done) {
337 case E_TOKEN:
338 msg = "invalid token";
339 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100340 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300341 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
342 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100343 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300344 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
345 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300346 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300347 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
348 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100349 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300350 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
351 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100352 case E_INTR:
353 if (!PyErr_Occurred()) {
354 PyErr_SetNone(PyExc_KeyboardInterrupt);
355 }
356 return -1;
357 case E_NOMEM:
358 PyErr_NoMemory();
359 return -1;
360 case E_TABSPACE:
361 errtype = PyExc_TabError;
362 msg = "inconsistent use of tabs and spaces in indentation";
363 break;
364 case E_TOODEEP:
365 errtype = PyExc_IndentationError;
366 msg = "too many levels of indentation";
367 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100368 case E_LINECONT:
369 msg = "unexpected character after line continuation character";
370 break;
371 default:
372 msg = "unknown parsing error";
373 }
374
375 PyErr_Format(errtype, msg);
376 // There is no reliable column information for this error
377 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
378
379 return -1;
380}
381
382void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300383_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
384{
385 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
386 int col_offset;
387 if (t->col_offset == -1) {
388 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
389 intptr_t, int);
390 } else {
391 col_offset = t->col_offset + 1;
392 }
393
394 va_list va;
395 va_start(va, errmsg);
396 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
397 col_offset, errmsg, va);
398 va_end(va);
399
400 return NULL;
401}
402
403
404void *
405_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
406 int lineno, int col_offset,
407 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100408{
409 PyObject *value = NULL;
410 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300411 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100412 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300413 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100414
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100415 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100416 if (!errstr) {
417 goto error;
418 }
419
420 if (p->start_rule == Py_file_input) {
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300421 error_line = PyErr_ProgramTextObject(p->tok->filename, lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100422 }
423
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300424 if (!error_line) {
425 error_line = get_error_line(p->tok->buf, p->start_rule == Py_file_input);
426 if (!error_line) {
427 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300428 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100429 }
430
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300431 int col_number = byte_offset_to_character_offset(error_line, col_offset);
432
433 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100434 if (!tmp) {
435 goto error;
436 }
437 value = PyTuple_Pack(2, errstr, tmp);
438 Py_DECREF(tmp);
439 if (!value) {
440 goto error;
441 }
442 PyErr_SetObject(errtype, value);
443
444 Py_DECREF(errstr);
445 Py_DECREF(value);
446 return NULL;
447
448error:
449 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300450 Py_XDECREF(error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100451 return NULL;
452}
453
454void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
455 int kwarg_unpacking = 0;
456 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
457 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
458 if (!keyword->arg) {
459 kwarg_unpacking = 1;
460 }
461 }
462
463 const char *msg = NULL;
464 if (kwarg_unpacking) {
465 msg = "positional argument follows keyword argument unpacking";
466 } else {
467 msg = "positional argument follows keyword argument";
468 }
469
470 return RAISE_SYNTAX_ERROR(msg);
471}
472
473#if 0
474static const char *
475token_name(int type)
476{
477 if (0 <= type && type <= N_TOKENS) {
478 return _PyParser_TokenNames[type];
479 }
480 return "<Huh?>";
481}
482#endif
483
484// Here, mark is the start of the node, while p->mark is the end.
485// If node==NULL, they should be the same.
486int
487_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
488{
489 // Insert in front
490 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
491 if (m == NULL) {
492 return -1;
493 }
494 m->type = type;
495 m->node = node;
496 m->mark = p->mark;
497 m->next = p->tokens[mark]->memo;
498 p->tokens[mark]->memo = m;
499 return 0;
500}
501
502// Like _PyPegen_insert_memo(), but updates an existing node if found.
503int
504_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
505{
506 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
507 if (m->type == type) {
508 // Update existing node.
509 m->node = node;
510 m->mark = p->mark;
511 return 0;
512 }
513 }
514 // Insert new node.
515 return _PyPegen_insert_memo(p, mark, type, node);
516}
517
518// Return dummy NAME.
519void *
520_PyPegen_dummy_name(Parser *p, ...)
521{
522 static void *cache = NULL;
523
524 if (cache != NULL) {
525 return cache;
526 }
527
528 PyObject *id = _create_dummy_identifier(p);
529 if (!id) {
530 return NULL;
531 }
532 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
533 return cache;
534}
535
536static int
537_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
538{
539 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
540 return NAME;
541 }
542 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
543 if (strncmp(k->str, name, name_len) == 0) {
544 return k->type;
545 }
546 }
547 return NAME;
548}
549
Guido van Rossumc001c092020-04-30 12:12:19 -0700550static int
551growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
552 assert(initial_size > 0);
553 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
554 arr->size = initial_size;
555 arr->num_items = 0;
556
557 return arr->items != NULL;
558}
559
560static int
561growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
562 if (arr->num_items >= arr->size) {
563 size_t new_size = arr->size * 2;
564 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
565 if (!new_items_array) {
566 return 0;
567 }
568 arr->items = new_items_array;
569 arr->size = new_size;
570 }
571
572 arr->items[arr->num_items].lineno = lineno;
573 arr->items[arr->num_items].comment = comment; // Take ownership
574 arr->num_items++;
575 return 1;
576}
577
578static void
579growable_comment_array_deallocate(growable_comment_array *arr) {
580 for (unsigned i = 0; i < arr->num_items; i++) {
581 PyMem_Free(arr->items[i].comment);
582 }
583 PyMem_Free(arr->items);
584}
585
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100586int
587_PyPegen_fill_token(Parser *p)
588{
589 const char *start, *end;
590 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700591
592 // Record and skip '# type: ignore' comments
593 while (type == TYPE_IGNORE) {
594 Py_ssize_t len = end - start;
595 char *tag = PyMem_Malloc(len + 1);
596 if (tag == NULL) {
597 PyErr_NoMemory();
598 return -1;
599 }
600 strncpy(tag, start, len);
601 tag[len] = '\0';
602 // Ownership of tag passes to the growable array
603 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
604 PyErr_NoMemory();
605 return -1;
606 }
607 type = PyTokenizer_Get(p->tok, &start, &end);
608 }
609
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100610 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
611 type = NEWLINE; /* Add an extra newline */
612 p->parsing_started = 0;
613
Pablo Galindob94dbd72020-04-27 18:35:58 +0100614 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100615 p->tok->pendin = -p->tok->indent;
616 p->tok->indent = 0;
617 }
618 }
619 else {
620 p->parsing_started = 1;
621 }
622
623 if (p->fill == p->size) {
624 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300625 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
626 if (new_tokens == NULL) {
627 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100628 return -1;
629 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300630 else {
631 p->tokens = new_tokens;
632 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100633 for (int i = p->size; i < newsize; i++) {
634 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300635 if (p->tokens[i] == NULL) {
636 p->size = i; // Needed, in order to cleanup correctly after parser fails
637 PyErr_NoMemory();
638 return -1;
639 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100640 memset(p->tokens[i], '\0', sizeof(Token));
641 }
642 p->size = newsize;
643 }
644
645 Token *t = p->tokens[p->fill];
646 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
647 t->bytes = PyBytes_FromStringAndSize(start, end - start);
648 if (t->bytes == NULL) {
649 return -1;
650 }
651 PyArena_AddPyObject(p->arena, t->bytes);
652
653 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
654 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100655 int end_lineno = p->tok->lineno;
656 int col_offset = -1, end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100657 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100658 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100659 }
660 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100661 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100662 }
663
664 t->lineno = p->starting_lineno + lineno;
665 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
666 t->end_lineno = p->starting_lineno + end_lineno;
667 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
668
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100669 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300670
671 if (type == ERRORTOKEN) {
672 if (p->tok->done == E_DECODE) {
673 return raise_decode_error(p);
674 }
675 else {
676 return tokenizer_error(p);
677 }
678 }
679
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100680 return 0;
681}
682
683// Instrumentation to count the effectiveness of memoization.
684// The array counts the number of tokens skipped by memoization,
685// indexed by type.
686
687#define NSTATISTICS 2000
688static long memo_statistics[NSTATISTICS];
689
690void
691_PyPegen_clear_memo_statistics()
692{
693 for (int i = 0; i < NSTATISTICS; i++) {
694 memo_statistics[i] = 0;
695 }
696}
697
698PyObject *
699_PyPegen_get_memo_statistics()
700{
701 PyObject *ret = PyList_New(NSTATISTICS);
702 if (ret == NULL) {
703 return NULL;
704 }
705 for (int i = 0; i < NSTATISTICS; i++) {
706 PyObject *value = PyLong_FromLong(memo_statistics[i]);
707 if (value == NULL) {
708 Py_DECREF(ret);
709 return NULL;
710 }
711 // PyList_SetItem borrows a reference to value.
712 if (PyList_SetItem(ret, i, value) < 0) {
713 Py_DECREF(ret);
714 return NULL;
715 }
716 }
717 return ret;
718}
719
720int // bool
721_PyPegen_is_memoized(Parser *p, int type, void *pres)
722{
723 if (p->mark == p->fill) {
724 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300725 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100726 return -1;
727 }
728 }
729
730 Token *t = p->tokens[p->mark];
731
732 for (Memo *m = t->memo; m != NULL; m = m->next) {
733 if (m->type == type) {
734 if (0 <= type && type < NSTATISTICS) {
735 long count = m->mark - p->mark;
736 // A memoized negative result counts for one.
737 if (count <= 0) {
738 count = 1;
739 }
740 memo_statistics[type] += count;
741 }
742 p->mark = m->mark;
743 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100744 return 1;
745 }
746 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100747 return 0;
748}
749
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100750
751int
752_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
753{
754 int mark = p->mark;
755 void *res = func(p);
756 p->mark = mark;
757 return (res != NULL) == positive;
758}
759
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100760int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100761_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
762{
763 int mark = p->mark;
764 void *res = func(p, arg);
765 p->mark = mark;
766 return (res != NULL) == positive;
767}
768
769int
770_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
771{
772 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100773 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100774 p->mark = mark;
775 return (res != NULL) == positive;
776}
777
778Token *
779_PyPegen_expect_token(Parser *p, int type)
780{
781 if (p->mark == p->fill) {
782 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300783 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100784 return NULL;
785 }
786 }
787 Token *t = p->tokens[p->mark];
788 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100789 return NULL;
790 }
791 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100792 return t;
793}
794
795Token *
796_PyPegen_get_last_nonnwhitespace_token(Parser *p)
797{
798 assert(p->mark >= 0);
799 Token *token = NULL;
800 for (int m = p->mark - 1; m >= 0; m--) {
801 token = p->tokens[m];
802 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
803 break;
804 }
805 }
806 return token;
807}
808
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100809expr_ty
810_PyPegen_name_token(Parser *p)
811{
812 Token *t = _PyPegen_expect_token(p, NAME);
813 if (t == NULL) {
814 return NULL;
815 }
816 char* s = PyBytes_AsString(t->bytes);
817 if (!s) {
818 return NULL;
819 }
820 PyObject *id = _PyPegen_new_identifier(p, s);
821 if (id == NULL) {
822 return NULL;
823 }
824 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
825 p->arena);
826}
827
828void *
829_PyPegen_string_token(Parser *p)
830{
831 return _PyPegen_expect_token(p, STRING);
832}
833
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100834static PyObject *
835parsenumber_raw(const char *s)
836{
837 const char *end;
838 long x;
839 double dx;
840 Py_complex compl;
841 int imflag;
842
843 assert(s != NULL);
844 errno = 0;
845 end = s + strlen(s) - 1;
846 imflag = *end == 'j' || *end == 'J';
847 if (s[0] == '0') {
848 x = (long)PyOS_strtoul(s, (char **)&end, 0);
849 if (x < 0 && errno == 0) {
850 return PyLong_FromString(s, (char **)0, 0);
851 }
852 }
853 else
854 x = PyOS_strtol(s, (char **)&end, 0);
855 if (*end == '\0') {
856 if (errno != 0)
857 return PyLong_FromString(s, (char **)0, 0);
858 return PyLong_FromLong(x);
859 }
860 /* XXX Huge floats may silently fail */
861 if (imflag) {
862 compl.real = 0.;
863 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
864 if (compl.imag == -1.0 && PyErr_Occurred())
865 return NULL;
866 return PyComplex_FromCComplex(compl);
867 }
868 else {
869 dx = PyOS_string_to_double(s, NULL, NULL);
870 if (dx == -1.0 && PyErr_Occurred())
871 return NULL;
872 return PyFloat_FromDouble(dx);
873 }
874}
875
876static PyObject *
877parsenumber(const char *s)
878{
879 char *dup, *end;
880 PyObject *res = NULL;
881
882 assert(s != NULL);
883
884 if (strchr(s, '_') == NULL) {
885 return parsenumber_raw(s);
886 }
887 /* Create a duplicate without underscores. */
888 dup = PyMem_Malloc(strlen(s) + 1);
889 if (dup == NULL) {
890 return PyErr_NoMemory();
891 }
892 end = dup;
893 for (; *s; s++) {
894 if (*s != '_') {
895 *end++ = *s;
896 }
897 }
898 *end = '\0';
899 res = parsenumber_raw(dup);
900 PyMem_Free(dup);
901 return res;
902}
903
904expr_ty
905_PyPegen_number_token(Parser *p)
906{
907 Token *t = _PyPegen_expect_token(p, NUMBER);
908 if (t == NULL) {
909 return NULL;
910 }
911
912 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100913 if (num_raw == NULL) {
914 return NULL;
915 }
916
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300917 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
918 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700919 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300920 "in Python 3.6 and greater");
921 }
922
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100923 PyObject *c = parsenumber(num_raw);
924
925 if (c == NULL) {
926 return NULL;
927 }
928
929 if (PyArena_AddPyObject(p->arena, c) < 0) {
930 Py_DECREF(c);
931 return NULL;
932 }
933
934 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
935 p->arena);
936}
937
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300938static int // bool
939newline_in_string(Parser *p, const char *cur)
940{
941 for (char c = *cur; cur >= p->tok->buf; c = *--cur) {
942 if (c == '\'' || c == '"') {
943 return 1;
944 }
945 }
946 return 0;
947}
948
949/* Check that the source for a single input statement really is a single
950 statement by looking at what is left in the buffer after parsing.
951 Trailing whitespace and comments are OK. */
952static int // bool
953bad_single_statement(Parser *p)
954{
955 const char *cur = strchr(p->tok->buf, '\n');
956
957 /* Newlines are allowed if preceded by a line continuation character
958 or if they appear inside a string. */
959 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
960 return 0;
961 }
962 char c = *cur;
963
964 for (;;) {
965 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
966 c = *++cur;
967 }
968
969 if (!c) {
970 return 0;
971 }
972
973 if (c != '#') {
974 return 1;
975 }
976
977 /* Suck up comment. */
978 while (c && c != '\n') {
979 c = *++cur;
980 }
981 }
982}
983
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100984void
985_PyPegen_Parser_Free(Parser *p)
986{
987 Py_XDECREF(p->normalize);
988 for (int i = 0; i < p->size; i++) {
989 PyMem_Free(p->tokens[i]);
990 }
991 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700992 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100993 PyMem_Free(p);
994}
995
Pablo Galindo2b74c832020-04-27 18:02:07 +0100996static int
997compute_parser_flags(PyCompilerFlags *flags)
998{
999 int parser_flags = 0;
1000 if (!flags) {
1001 return 0;
1002 }
1003 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1004 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1005 }
1006 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1007 parser_flags |= PyPARSE_IGNORE_COOKIE;
1008 }
1009 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1010 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1011 }
1012 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1013 parser_flags |= PyPARSE_TYPE_COMMENTS;
1014 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001015 if (flags->cf_feature_version < 7) {
1016 parser_flags |= PyPARSE_ASYNC_HACKS;
1017 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001018 return parser_flags;
1019}
1020
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001021Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001022_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001023 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001024{
1025 Parser *p = PyMem_Malloc(sizeof(Parser));
1026 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001027 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001028 }
1029 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001030 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1031 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001032 p->tok = tok;
1033 p->keywords = NULL;
1034 p->n_keyword_lists = -1;
1035 p->tokens = PyMem_Malloc(sizeof(Token *));
1036 if (!p->tokens) {
1037 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001038 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001039 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001040 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001041 if (!p->tokens) {
1042 PyMem_Free(p->tokens);
1043 PyMem_Free(p);
1044 return (Parser *) PyErr_NoMemory();
1045 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001046 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1047 PyMem_Free(p->tokens[0]);
1048 PyMem_Free(p->tokens);
1049 PyMem_Free(p);
1050 return (Parser *) PyErr_NoMemory();
1051 }
1052
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001053 p->mark = 0;
1054 p->fill = 0;
1055 p->size = 1;
1056
1057 p->errcode = errcode;
1058 p->arena = arena;
1059 p->start_rule = start_rule;
1060 p->parsing_started = 0;
1061 p->normalize = NULL;
1062 p->error_indicator = 0;
1063
1064 p->starting_lineno = 0;
1065 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001066 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001067 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001068 p->known_err_token = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001069
1070 return p;
1071}
1072
1073void *
1074_PyPegen_run_parser(Parser *p)
1075{
1076 void *res = _PyPegen_parse(p);
1077 if (res == NULL) {
1078 if (PyErr_Occurred()) {
1079 return NULL;
1080 }
1081 if (p->fill == 0) {
1082 RAISE_SYNTAX_ERROR("error at start before reading any input");
1083 }
1084 else if (p->tok->done == E_EOF) {
1085 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1086 }
1087 else {
1088 if (p->tokens[p->fill-1]->type == INDENT) {
1089 RAISE_INDENTATION_ERROR("unexpected indent");
1090 }
1091 else if (p->tokens[p->fill-1]->type == DEDENT) {
1092 RAISE_INDENTATION_ERROR("unexpected unindent");
1093 }
1094 else {
1095 RAISE_SYNTAX_ERROR("invalid syntax");
1096 }
1097 }
1098 return NULL;
1099 }
1100
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001101 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1102 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1103 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1104 }
1105
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001106 return res;
1107}
1108
1109mod_ty
1110_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1111 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001112 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001113{
1114 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1115 if (tok == NULL) {
1116 if (PyErr_Occurred()) {
1117 raise_tokenizer_init_error(filename_ob);
1118 return NULL;
1119 }
1120 return NULL;
1121 }
1122 // This transfers the ownership to the tokenizer
1123 tok->filename = filename_ob;
1124 Py_INCREF(filename_ob);
1125
1126 // From here on we need to clean up even if there's an error
1127 mod_ty result = NULL;
1128
Pablo Galindo2b74c832020-04-27 18:02:07 +01001129 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001130 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1131 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001132 if (p == NULL) {
1133 goto error;
1134 }
1135
1136 result = _PyPegen_run_parser(p);
1137 _PyPegen_Parser_Free(p);
1138
1139error:
1140 PyTokenizer_Free(tok);
1141 return result;
1142}
1143
1144mod_ty
1145_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001146 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001147{
1148 FILE *fp = fopen(filename, "rb");
1149 if (fp == NULL) {
1150 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1151 return NULL;
1152 }
1153
1154 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001155 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001156
1157 fclose(fp);
1158 return result;
1159}
1160
1161mod_ty
1162_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001163 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001164{
1165 int exec_input = start_rule == Py_file_input;
1166
1167 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001168 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001169 tok = PyTokenizer_FromUTF8(str, exec_input);
1170 } else {
1171 tok = PyTokenizer_FromString(str, exec_input);
1172 }
1173 if (tok == NULL) {
1174 if (PyErr_Occurred()) {
1175 raise_tokenizer_init_error(filename_ob);
1176 }
1177 return NULL;
1178 }
1179 // This transfers the ownership to the tokenizer
1180 tok->filename = filename_ob;
1181 Py_INCREF(filename_ob);
1182
1183 // We need to clear up from here on
1184 mod_ty result = NULL;
1185
Pablo Galindo2b74c832020-04-27 18:02:07 +01001186 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001187 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001188 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1189 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001190 if (p == NULL) {
1191 goto error;
1192 }
1193
1194 result = _PyPegen_run_parser(p);
1195 _PyPegen_Parser_Free(p);
1196
1197error:
1198 PyTokenizer_Free(tok);
1199 return result;
1200}
1201
1202void *
1203_PyPegen_interactive_exit(Parser *p)
1204{
1205 if (p->errcode) {
1206 *(p->errcode) = E_EOF;
1207 }
1208 return NULL;
1209}
1210
1211/* Creates a single-element asdl_seq* that contains a */
1212asdl_seq *
1213_PyPegen_singleton_seq(Parser *p, void *a)
1214{
1215 assert(a != NULL);
1216 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1217 if (!seq) {
1218 return NULL;
1219 }
1220 asdl_seq_SET(seq, 0, a);
1221 return seq;
1222}
1223
1224/* Creates a copy of seq and prepends a to it */
1225asdl_seq *
1226_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1227{
1228 assert(a != NULL);
1229 if (!seq) {
1230 return _PyPegen_singleton_seq(p, a);
1231 }
1232
1233 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1234 if (!new_seq) {
1235 return NULL;
1236 }
1237
1238 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001239 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001240 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1241 }
1242 return new_seq;
1243}
1244
Guido van Rossumc001c092020-04-30 12:12:19 -07001245/* Creates a copy of seq and appends a to it */
1246asdl_seq *
1247_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1248{
1249 assert(a != NULL);
1250 if (!seq) {
1251 return _PyPegen_singleton_seq(p, a);
1252 }
1253
1254 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1255 if (!new_seq) {
1256 return NULL;
1257 }
1258
1259 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1260 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1261 }
1262 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1263 return new_seq;
1264}
1265
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001266static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001267_get_flattened_seq_size(asdl_seq *seqs)
1268{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001269 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001270 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1271 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1272 size += asdl_seq_LEN(inner_seq);
1273 }
1274 return size;
1275}
1276
1277/* Flattens an asdl_seq* of asdl_seq*s */
1278asdl_seq *
1279_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1280{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001281 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001282 assert(flattened_seq_size > 0);
1283
1284 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1285 if (!flattened_seq) {
1286 return NULL;
1287 }
1288
1289 int flattened_seq_idx = 0;
1290 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1291 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001292 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001293 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1294 }
1295 }
1296 assert(flattened_seq_idx == flattened_seq_size);
1297
1298 return flattened_seq;
1299}
1300
1301/* Creates a new name of the form <first_name>.<second_name> */
1302expr_ty
1303_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1304{
1305 assert(first_name != NULL && second_name != NULL);
1306 PyObject *first_identifier = first_name->v.Name.id;
1307 PyObject *second_identifier = second_name->v.Name.id;
1308
1309 if (PyUnicode_READY(first_identifier) == -1) {
1310 return NULL;
1311 }
1312 if (PyUnicode_READY(second_identifier) == -1) {
1313 return NULL;
1314 }
1315 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1316 if (!first_str) {
1317 return NULL;
1318 }
1319 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1320 if (!second_str) {
1321 return NULL;
1322 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001323 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001324
1325 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1326 if (!str) {
1327 return NULL;
1328 }
1329
1330 char *s = PyBytes_AS_STRING(str);
1331 if (!s) {
1332 return NULL;
1333 }
1334
1335 strcpy(s, first_str);
1336 s += strlen(first_str);
1337 *s++ = '.';
1338 strcpy(s, second_str);
1339 s += strlen(second_str);
1340 *s = '\0';
1341
1342 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1343 Py_DECREF(str);
1344 if (!uni) {
1345 return NULL;
1346 }
1347 PyUnicode_InternInPlace(&uni);
1348 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1349 Py_DECREF(uni);
1350 return NULL;
1351 }
1352
1353 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1354}
1355
1356/* Counts the total number of dots in seq's tokens */
1357int
1358_PyPegen_seq_count_dots(asdl_seq *seq)
1359{
1360 int number_of_dots = 0;
1361 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1362 Token *current_expr = asdl_seq_GET(seq, i);
1363 switch (current_expr->type) {
1364 case ELLIPSIS:
1365 number_of_dots += 3;
1366 break;
1367 case DOT:
1368 number_of_dots += 1;
1369 break;
1370 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001371 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001372 }
1373 }
1374
1375 return number_of_dots;
1376}
1377
1378/* Creates an alias with '*' as the identifier name */
1379alias_ty
1380_PyPegen_alias_for_star(Parser *p)
1381{
1382 PyObject *str = PyUnicode_InternFromString("*");
1383 if (!str) {
1384 return NULL;
1385 }
1386 if (PyArena_AddPyObject(p->arena, str) < 0) {
1387 Py_DECREF(str);
1388 return NULL;
1389 }
1390 return alias(str, NULL, p->arena);
1391}
1392
1393/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1394asdl_seq *
1395_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1396{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001397 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001398 assert(len > 0);
1399
1400 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1401 if (!new_seq) {
1402 return NULL;
1403 }
1404 for (Py_ssize_t i = 0; i < len; i++) {
1405 expr_ty e = asdl_seq_GET(seq, i);
1406 asdl_seq_SET(new_seq, i, e->v.Name.id);
1407 }
1408 return new_seq;
1409}
1410
1411/* Constructs a CmpopExprPair */
1412CmpopExprPair *
1413_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1414{
1415 assert(expr != NULL);
1416 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1417 if (!a) {
1418 return NULL;
1419 }
1420 a->cmpop = cmpop;
1421 a->expr = expr;
1422 return a;
1423}
1424
1425asdl_int_seq *
1426_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1427{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001428 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001429 assert(len > 0);
1430
1431 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1432 if (!new_seq) {
1433 return NULL;
1434 }
1435 for (Py_ssize_t i = 0; i < len; i++) {
1436 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1437 asdl_seq_SET(new_seq, i, pair->cmpop);
1438 }
1439 return new_seq;
1440}
1441
1442asdl_seq *
1443_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1444{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001445 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001446 assert(len > 0);
1447
1448 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1449 if (!new_seq) {
1450 return NULL;
1451 }
1452 for (Py_ssize_t i = 0; i < len; i++) {
1453 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1454 asdl_seq_SET(new_seq, i, pair->expr);
1455 }
1456 return new_seq;
1457}
1458
1459/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1460static asdl_seq *
1461_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1462{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001463 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001464 if (len == 0) {
1465 return NULL;
1466 }
1467
1468 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1469 if (!new_seq) {
1470 return NULL;
1471 }
1472 for (Py_ssize_t i = 0; i < len; i++) {
1473 expr_ty e = asdl_seq_GET(seq, i);
1474 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1475 }
1476 return new_seq;
1477}
1478
1479static expr_ty
1480_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1481{
1482 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1483}
1484
1485static expr_ty
1486_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1487{
1488 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1489}
1490
1491static expr_ty
1492_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1493{
1494 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1495}
1496
1497static expr_ty
1498_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1499{
1500 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1501}
1502
1503static expr_ty
1504_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1505{
1506 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1507}
1508
1509static expr_ty
1510_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1511{
1512 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1513}
1514
1515/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1516expr_ty
1517_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1518{
1519 assert(expr != NULL);
1520
1521 expr_ty new = NULL;
1522 switch (expr->kind) {
1523 case Name_kind:
1524 new = _set_name_context(p, expr, ctx);
1525 break;
1526 case Tuple_kind:
1527 new = _set_tuple_context(p, expr, ctx);
1528 break;
1529 case List_kind:
1530 new = _set_list_context(p, expr, ctx);
1531 break;
1532 case Subscript_kind:
1533 new = _set_subscript_context(p, expr, ctx);
1534 break;
1535 case Attribute_kind:
1536 new = _set_attribute_context(p, expr, ctx);
1537 break;
1538 case Starred_kind:
1539 new = _set_starred_context(p, expr, ctx);
1540 break;
1541 default:
1542 new = expr;
1543 }
1544 return new;
1545}
1546
1547/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1548KeyValuePair *
1549_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1550{
1551 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1552 if (!a) {
1553 return NULL;
1554 }
1555 a->key = key;
1556 a->value = value;
1557 return a;
1558}
1559
1560/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1561asdl_seq *
1562_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1563{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001564 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001565 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1566 if (!new_seq) {
1567 return NULL;
1568 }
1569 for (Py_ssize_t i = 0; i < len; i++) {
1570 KeyValuePair *pair = asdl_seq_GET(seq, i);
1571 asdl_seq_SET(new_seq, i, pair->key);
1572 }
1573 return new_seq;
1574}
1575
1576/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1577asdl_seq *
1578_PyPegen_get_values(Parser *p, asdl_seq *seq)
1579{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001580 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001581 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1582 if (!new_seq) {
1583 return NULL;
1584 }
1585 for (Py_ssize_t i = 0; i < len; i++) {
1586 KeyValuePair *pair = asdl_seq_GET(seq, i);
1587 asdl_seq_SET(new_seq, i, pair->value);
1588 }
1589 return new_seq;
1590}
1591
1592/* Constructs a NameDefaultPair */
1593NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001594_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001595{
1596 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1597 if (!a) {
1598 return NULL;
1599 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001600 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001601 a->value = value;
1602 return a;
1603}
1604
1605/* Constructs a SlashWithDefault */
1606SlashWithDefault *
1607_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1608{
1609 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1610 if (!a) {
1611 return NULL;
1612 }
1613 a->plain_names = plain_names;
1614 a->names_with_defaults = names_with_defaults;
1615 return a;
1616}
1617
1618/* Constructs a StarEtc */
1619StarEtc *
1620_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1621{
1622 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1623 if (!a) {
1624 return NULL;
1625 }
1626 a->vararg = vararg;
1627 a->kwonlyargs = kwonlyargs;
1628 a->kwarg = kwarg;
1629 return a;
1630}
1631
1632asdl_seq *
1633_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1634{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001635 Py_ssize_t first_len = asdl_seq_LEN(a);
1636 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001637 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1638 if (!new_seq) {
1639 return NULL;
1640 }
1641
1642 int k = 0;
1643 for (Py_ssize_t i = 0; i < first_len; i++) {
1644 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1645 }
1646 for (Py_ssize_t i = 0; i < second_len; i++) {
1647 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1648 }
1649
1650 return new_seq;
1651}
1652
1653static asdl_seq *
1654_get_names(Parser *p, asdl_seq *names_with_defaults)
1655{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001656 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001657 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1658 if (!seq) {
1659 return NULL;
1660 }
1661 for (Py_ssize_t i = 0; i < len; i++) {
1662 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1663 asdl_seq_SET(seq, i, pair->arg);
1664 }
1665 return seq;
1666}
1667
1668static asdl_seq *
1669_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1670{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001671 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001672 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1673 if (!seq) {
1674 return NULL;
1675 }
1676 for (Py_ssize_t i = 0; i < len; i++) {
1677 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1678 asdl_seq_SET(seq, i, pair->value);
1679 }
1680 return seq;
1681}
1682
1683/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1684arguments_ty
1685_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1686 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1687 asdl_seq *names_with_default, StarEtc *star_etc)
1688{
1689 asdl_seq *posonlyargs;
1690 if (slash_without_default != NULL) {
1691 posonlyargs = slash_without_default;
1692 }
1693 else if (slash_with_default != NULL) {
1694 asdl_seq *slash_with_default_names =
1695 _get_names(p, slash_with_default->names_with_defaults);
1696 if (!slash_with_default_names) {
1697 return NULL;
1698 }
1699 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1700 if (!posonlyargs) {
1701 return NULL;
1702 }
1703 }
1704 else {
1705 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1706 if (!posonlyargs) {
1707 return NULL;
1708 }
1709 }
1710
1711 asdl_seq *posargs;
1712 if (plain_names != NULL && names_with_default != NULL) {
1713 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1714 if (!names_with_default_names) {
1715 return NULL;
1716 }
1717 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1718 if (!posargs) {
1719 return NULL;
1720 }
1721 }
1722 else if (plain_names == NULL && names_with_default != NULL) {
1723 posargs = _get_names(p, names_with_default);
1724 if (!posargs) {
1725 return NULL;
1726 }
1727 }
1728 else if (plain_names != NULL && names_with_default == NULL) {
1729 posargs = plain_names;
1730 }
1731 else {
1732 posargs = _Py_asdl_seq_new(0, p->arena);
1733 if (!posargs) {
1734 return NULL;
1735 }
1736 }
1737
1738 asdl_seq *posdefaults;
1739 if (slash_with_default != NULL && names_with_default != NULL) {
1740 asdl_seq *slash_with_default_values =
1741 _get_defaults(p, slash_with_default->names_with_defaults);
1742 if (!slash_with_default_values) {
1743 return NULL;
1744 }
1745 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1746 if (!names_with_default_values) {
1747 return NULL;
1748 }
1749 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1750 if (!posdefaults) {
1751 return NULL;
1752 }
1753 }
1754 else if (slash_with_default == NULL && names_with_default != NULL) {
1755 posdefaults = _get_defaults(p, names_with_default);
1756 if (!posdefaults) {
1757 return NULL;
1758 }
1759 }
1760 else if (slash_with_default != NULL && names_with_default == NULL) {
1761 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1762 if (!posdefaults) {
1763 return NULL;
1764 }
1765 }
1766 else {
1767 posdefaults = _Py_asdl_seq_new(0, p->arena);
1768 if (!posdefaults) {
1769 return NULL;
1770 }
1771 }
1772
1773 arg_ty vararg = NULL;
1774 if (star_etc != NULL && star_etc->vararg != NULL) {
1775 vararg = star_etc->vararg;
1776 }
1777
1778 asdl_seq *kwonlyargs;
1779 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1780 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1781 if (!kwonlyargs) {
1782 return NULL;
1783 }
1784 }
1785 else {
1786 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1787 if (!kwonlyargs) {
1788 return NULL;
1789 }
1790 }
1791
1792 asdl_seq *kwdefaults;
1793 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1794 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1795 if (!kwdefaults) {
1796 return NULL;
1797 }
1798 }
1799 else {
1800 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1801 if (!kwdefaults) {
1802 return NULL;
1803 }
1804 }
1805
1806 arg_ty kwarg = NULL;
1807 if (star_etc != NULL && star_etc->kwarg != NULL) {
1808 kwarg = star_etc->kwarg;
1809 }
1810
1811 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1812 posdefaults, p->arena);
1813}
1814
1815/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1816 * arguments. */
1817arguments_ty
1818_PyPegen_empty_arguments(Parser *p)
1819{
1820 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1821 if (!posonlyargs) {
1822 return NULL;
1823 }
1824 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1825 if (!posargs) {
1826 return NULL;
1827 }
1828 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1829 if (!posdefaults) {
1830 return NULL;
1831 }
1832 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1833 if (!kwonlyargs) {
1834 return NULL;
1835 }
1836 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1837 if (!kwdefaults) {
1838 return NULL;
1839 }
1840
1841 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1842 p->arena);
1843}
1844
1845/* Encapsulates the value of an operator_ty into an AugOperator struct */
1846AugOperator *
1847_PyPegen_augoperator(Parser *p, operator_ty kind)
1848{
1849 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1850 if (!a) {
1851 return NULL;
1852 }
1853 a->kind = kind;
1854 return a;
1855}
1856
1857/* Construct a FunctionDef equivalent to function_def, but with decorators */
1858stmt_ty
1859_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1860{
1861 assert(function_def != NULL);
1862 if (function_def->kind == AsyncFunctionDef_kind) {
1863 return _Py_AsyncFunctionDef(
1864 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1865 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1866 function_def->v.FunctionDef.type_comment, function_def->lineno,
1867 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1868 p->arena);
1869 }
1870
1871 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1872 function_def->v.FunctionDef.body, decorators,
1873 function_def->v.FunctionDef.returns,
1874 function_def->v.FunctionDef.type_comment, function_def->lineno,
1875 function_def->col_offset, function_def->end_lineno,
1876 function_def->end_col_offset, p->arena);
1877}
1878
1879/* Construct a ClassDef equivalent to class_def, but with decorators */
1880stmt_ty
1881_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1882{
1883 assert(class_def != NULL);
1884 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1885 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1886 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1887 class_def->end_col_offset, p->arena);
1888}
1889
1890/* Construct a KeywordOrStarred */
1891KeywordOrStarred *
1892_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1893{
1894 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1895 if (!a) {
1896 return NULL;
1897 }
1898 a->element = element;
1899 a->is_keyword = is_keyword;
1900 return a;
1901}
1902
1903/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1904static int
1905_seq_number_of_starred_exprs(asdl_seq *seq)
1906{
1907 int n = 0;
1908 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1909 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1910 if (!k->is_keyword) {
1911 n++;
1912 }
1913 }
1914 return n;
1915}
1916
1917/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1918asdl_seq *
1919_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1920{
1921 int new_len = _seq_number_of_starred_exprs(kwargs);
1922 if (new_len == 0) {
1923 return NULL;
1924 }
1925 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1926 if (!new_seq) {
1927 return NULL;
1928 }
1929
1930 int idx = 0;
1931 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1932 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1933 if (!k->is_keyword) {
1934 asdl_seq_SET(new_seq, idx++, k->element);
1935 }
1936 }
1937 return new_seq;
1938}
1939
1940/* Return a new asdl_seq* with only the keywords in kwargs */
1941asdl_seq *
1942_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1943{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001944 Py_ssize_t len = asdl_seq_LEN(kwargs);
1945 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001946 if (new_len == 0) {
1947 return NULL;
1948 }
1949 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1950 if (!new_seq) {
1951 return NULL;
1952 }
1953
1954 int idx = 0;
1955 for (Py_ssize_t i = 0; i < len; i++) {
1956 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1957 if (k->is_keyword) {
1958 asdl_seq_SET(new_seq, idx++, k->element);
1959 }
1960 }
1961 return new_seq;
1962}
1963
1964expr_ty
1965_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1966{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001967 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001968 assert(len > 0);
1969
1970 Token *first = asdl_seq_GET(strings, 0);
1971 Token *last = asdl_seq_GET(strings, len - 1);
1972
1973 int bytesmode = 0;
1974 PyObject *bytes_str = NULL;
1975
1976 FstringParser state;
1977 _PyPegen_FstringParser_Init(&state);
1978
1979 for (Py_ssize_t i = 0; i < len; i++) {
1980 Token *t = asdl_seq_GET(strings, i);
1981
1982 int this_bytesmode;
1983 int this_rawmode;
1984 PyObject *s;
1985 const char *fstr;
1986 Py_ssize_t fstrlen = -1;
1987
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001988 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001989 goto error;
1990 }
1991
1992 /* Check that we are not mixing bytes with unicode. */
1993 if (i != 0 && bytesmode != this_bytesmode) {
1994 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1995 Py_XDECREF(s);
1996 goto error;
1997 }
1998 bytesmode = this_bytesmode;
1999
2000 if (fstr != NULL) {
2001 assert(s == NULL && !bytesmode);
2002
2003 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2004 this_rawmode, 0, first, t, last);
2005 if (result < 0) {
2006 goto error;
2007 }
2008 }
2009 else {
2010 /* String or byte string. */
2011 assert(s != NULL && fstr == NULL);
2012 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2013
2014 if (bytesmode) {
2015 if (i == 0) {
2016 bytes_str = s;
2017 }
2018 else {
2019 PyBytes_ConcatAndDel(&bytes_str, s);
2020 if (!bytes_str) {
2021 goto error;
2022 }
2023 }
2024 }
2025 else {
2026 /* This is a regular string. Concatenate it. */
2027 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2028 goto error;
2029 }
2030 }
2031 }
2032 }
2033
2034 if (bytesmode) {
2035 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2036 goto error;
2037 }
2038 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2039 last->end_col_offset, p->arena);
2040 }
2041
2042 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2043
2044error:
2045 Py_XDECREF(bytes_str);
2046 _PyPegen_FstringParser_Dealloc(&state);
2047 if (PyErr_Occurred()) {
2048 raise_decode_error(p);
2049 }
2050 return NULL;
2051}
Guido van Rossumc001c092020-04-30 12:12:19 -07002052
2053mod_ty
2054_PyPegen_make_module(Parser *p, asdl_seq *a) {
2055 asdl_seq *type_ignores = NULL;
2056 Py_ssize_t num = p->type_ignore_comments.num_items;
2057 if (num > 0) {
2058 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2059 type_ignores = _Py_asdl_seq_new(num, p->arena);
2060 if (type_ignores == NULL) {
2061 return NULL;
2062 }
2063 for (int i = 0; i < num; i++) {
2064 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2065 if (tag == NULL) {
2066 return NULL;
2067 }
2068 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2069 if (ti == NULL) {
2070 return NULL;
2071 }
2072 asdl_seq_SET(type_ignores, i, ti);
2073 }
2074 }
2075 return Module(a, type_ignores, p->arena);
2076}