blob: 7b581cadfb64a4da4966fd8b953227e70beefa79 [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{
Pablo Galindo9f495902020-06-08 02:57:00 +0100164 assert(e != NULL);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100165 switch (e->kind) {
166 case Attribute_kind:
167 return "attribute";
168 case Subscript_kind:
169 return "subscript";
170 case Starred_kind:
171 return "starred";
172 case Name_kind:
173 return "name";
174 case List_kind:
175 return "list";
176 case Tuple_kind:
177 return "tuple";
178 case Lambda_kind:
179 return "lambda";
180 case Call_kind:
181 return "function call";
182 case BoolOp_kind:
183 case BinOp_kind:
184 case UnaryOp_kind:
185 return "operator";
186 case GeneratorExp_kind:
187 return "generator expression";
188 case Yield_kind:
189 case YieldFrom_kind:
190 return "yield expression";
191 case Await_kind:
192 return "await expression";
193 case ListComp_kind:
194 return "list comprehension";
195 case SetComp_kind:
196 return "set comprehension";
197 case DictComp_kind:
198 return "dict comprehension";
199 case Dict_kind:
200 return "dict display";
201 case Set_kind:
202 return "set display";
203 case JoinedStr_kind:
204 case FormattedValue_kind:
205 return "f-string expression";
206 case Constant_kind: {
207 PyObject *value = e->v.Constant.value;
208 if (value == Py_None) {
209 return "None";
210 }
211 if (value == Py_False) {
212 return "False";
213 }
214 if (value == Py_True) {
215 return "True";
216 }
217 if (value == Py_Ellipsis) {
218 return "Ellipsis";
219 }
220 return "literal";
221 }
222 case Compare_kind:
223 return "comparison";
224 case IfExp_kind:
225 return "conditional expression";
226 case NamedExpr_kind:
227 return "named expression";
228 default:
229 PyErr_Format(PyExc_SystemError,
230 "unexpected expression in assignment %d (line %d)",
231 e->kind, e->lineno);
232 return NULL;
233 }
234}
235
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300236static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100237raise_decode_error(Parser *p)
238{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300239 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100240 const char *errtype = NULL;
241 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
242 errtype = "unicode error";
243 }
244 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
245 errtype = "value error";
246 }
247 if (errtype) {
248 PyObject *type, *value, *tback, *errstr;
249 PyErr_Fetch(&type, &value, &tback);
250 errstr = PyObject_Str(value);
251 if (errstr) {
252 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
253 Py_DECREF(errstr);
254 }
255 else {
256 PyErr_Clear();
257 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
258 }
259 Py_XDECREF(type);
260 Py_XDECREF(value);
261 Py_XDECREF(tback);
262 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300263
264 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100265}
266
267static void
268raise_tokenizer_init_error(PyObject *filename)
269{
270 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
271 || PyErr_ExceptionMatches(PyExc_ValueError)
272 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
273 return;
274 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300275 PyObject *errstr = NULL;
276 PyObject *tuple = NULL;
277 PyObject *type, *value, *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100278 PyErr_Fetch(&type, &value, &tback);
279 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300280 if (!errstr) {
281 goto error;
282 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100283
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300284 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100285 if (!tmp) {
286 goto error;
287 }
288
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300289 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100290 Py_DECREF(tmp);
291 if (!value) {
292 goto error;
293 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300294 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100295
296error:
297 Py_XDECREF(type);
298 Py_XDECREF(value);
299 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300300 Py_XDECREF(errstr);
301 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100302}
303
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100304static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100305tokenizer_error(Parser *p)
306{
307 if (PyErr_Occurred()) {
308 return -1;
309 }
310
311 const char *msg = NULL;
312 PyObject* errtype = PyExc_SyntaxError;
313 switch (p->tok->done) {
314 case E_TOKEN:
315 msg = "invalid token";
316 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100317 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300318 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
319 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100320 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300321 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
322 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300323 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300324 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
325 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100326 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300327 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
328 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100329 case E_INTR:
330 if (!PyErr_Occurred()) {
331 PyErr_SetNone(PyExc_KeyboardInterrupt);
332 }
333 return -1;
334 case E_NOMEM:
335 PyErr_NoMemory();
336 return -1;
337 case E_TABSPACE:
338 errtype = PyExc_TabError;
339 msg = "inconsistent use of tabs and spaces in indentation";
340 break;
341 case E_TOODEEP:
342 errtype = PyExc_IndentationError;
343 msg = "too many levels of indentation";
344 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100345 case E_LINECONT:
346 msg = "unexpected character after line continuation character";
347 break;
348 default:
349 msg = "unknown parsing error";
350 }
351
352 PyErr_Format(errtype, msg);
353 // There is no reliable column information for this error
354 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
355
356 return -1;
357}
358
359void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300360_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
361{
362 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
363 int col_offset;
364 if (t->col_offset == -1) {
365 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
366 intptr_t, int);
367 } else {
368 col_offset = t->col_offset + 1;
369 }
370
371 va_list va;
372 va_start(va, errmsg);
373 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
374 col_offset, errmsg, va);
375 va_end(va);
376
377 return NULL;
378}
379
380
381void *
382_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
383 int lineno, int col_offset,
384 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100385{
386 PyObject *value = NULL;
387 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300388 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100389 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300390 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100392 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100393 if (!errstr) {
394 goto error;
395 }
396
397 if (p->start_rule == Py_file_input) {
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300398 error_line = PyErr_ProgramTextObject(p->tok->filename, lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100399 }
400
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300401 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100402 Py_ssize_t size = p->tok->inp - p->tok->buf;
403 if (size && p->tok->buf[size-1] == '\n') {
404 size--;
405 }
406 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300407 if (!error_line) {
408 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300409 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100410 }
411
Pablo Galindob23d7ad2020-05-24 06:01:34 +0100412 Py_ssize_t col_number = byte_offset_to_character_offset(error_line, col_offset);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300413
414 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100415 if (!tmp) {
416 goto error;
417 }
418 value = PyTuple_Pack(2, errstr, tmp);
419 Py_DECREF(tmp);
420 if (!value) {
421 goto error;
422 }
423 PyErr_SetObject(errtype, value);
424
425 Py_DECREF(errstr);
426 Py_DECREF(value);
427 return NULL;
428
429error:
430 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300431 Py_XDECREF(error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100432 return NULL;
433}
434
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100435#if 0
436static const char *
437token_name(int type)
438{
439 if (0 <= type && type <= N_TOKENS) {
440 return _PyParser_TokenNames[type];
441 }
442 return "<Huh?>";
443}
444#endif
445
446// Here, mark is the start of the node, while p->mark is the end.
447// If node==NULL, they should be the same.
448int
449_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
450{
451 // Insert in front
452 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
453 if (m == NULL) {
454 return -1;
455 }
456 m->type = type;
457 m->node = node;
458 m->mark = p->mark;
459 m->next = p->tokens[mark]->memo;
460 p->tokens[mark]->memo = m;
461 return 0;
462}
463
464// Like _PyPegen_insert_memo(), but updates an existing node if found.
465int
466_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
467{
468 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
469 if (m->type == type) {
470 // Update existing node.
471 m->node = node;
472 m->mark = p->mark;
473 return 0;
474 }
475 }
476 // Insert new node.
477 return _PyPegen_insert_memo(p, mark, type, node);
478}
479
480// Return dummy NAME.
481void *
482_PyPegen_dummy_name(Parser *p, ...)
483{
484 static void *cache = NULL;
485
486 if (cache != NULL) {
487 return cache;
488 }
489
490 PyObject *id = _create_dummy_identifier(p);
491 if (!id) {
492 return NULL;
493 }
494 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
495 return cache;
496}
497
498static int
499_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
500{
501 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
502 return NAME;
503 }
504 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
505 if (strncmp(k->str, name, name_len) == 0) {
506 return k->type;
507 }
508 }
509 return NAME;
510}
511
Guido van Rossumc001c092020-04-30 12:12:19 -0700512static int
513growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
514 assert(initial_size > 0);
515 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
516 arr->size = initial_size;
517 arr->num_items = 0;
518
519 return arr->items != NULL;
520}
521
522static int
523growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
524 if (arr->num_items >= arr->size) {
525 size_t new_size = arr->size * 2;
526 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
527 if (!new_items_array) {
528 return 0;
529 }
530 arr->items = new_items_array;
531 arr->size = new_size;
532 }
533
534 arr->items[arr->num_items].lineno = lineno;
535 arr->items[arr->num_items].comment = comment; // Take ownership
536 arr->num_items++;
537 return 1;
538}
539
540static void
541growable_comment_array_deallocate(growable_comment_array *arr) {
542 for (unsigned i = 0; i < arr->num_items; i++) {
543 PyMem_Free(arr->items[i].comment);
544 }
545 PyMem_Free(arr->items);
546}
547
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100548int
549_PyPegen_fill_token(Parser *p)
550{
551 const char *start, *end;
552 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700553
554 // Record and skip '# type: ignore' comments
555 while (type == TYPE_IGNORE) {
556 Py_ssize_t len = end - start;
557 char *tag = PyMem_Malloc(len + 1);
558 if (tag == NULL) {
559 PyErr_NoMemory();
560 return -1;
561 }
562 strncpy(tag, start, len);
563 tag[len] = '\0';
564 // Ownership of tag passes to the growable array
565 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
566 PyErr_NoMemory();
567 return -1;
568 }
569 type = PyTokenizer_Get(p->tok, &start, &end);
570 }
571
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100572 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
573 type = NEWLINE; /* Add an extra newline */
574 p->parsing_started = 0;
575
Pablo Galindob94dbd72020-04-27 18:35:58 +0100576 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100577 p->tok->pendin = -p->tok->indent;
578 p->tok->indent = 0;
579 }
580 }
581 else {
582 p->parsing_started = 1;
583 }
584
585 if (p->fill == p->size) {
586 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300587 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
588 if (new_tokens == NULL) {
589 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100590 return -1;
591 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300592 else {
593 p->tokens = new_tokens;
594 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100595 for (int i = p->size; i < newsize; i++) {
596 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300597 if (p->tokens[i] == NULL) {
598 p->size = i; // Needed, in order to cleanup correctly after parser fails
599 PyErr_NoMemory();
600 return -1;
601 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100602 memset(p->tokens[i], '\0', sizeof(Token));
603 }
604 p->size = newsize;
605 }
606
607 Token *t = p->tokens[p->fill];
608 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
609 t->bytes = PyBytes_FromStringAndSize(start, end - start);
610 if (t->bytes == NULL) {
611 return -1;
612 }
613 PyArena_AddPyObject(p->arena, t->bytes);
614
615 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
616 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100617 int end_lineno = p->tok->lineno;
618 int col_offset = -1, end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100619 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100620 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100621 }
622 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100623 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100624 }
625
626 t->lineno = p->starting_lineno + lineno;
627 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
628 t->end_lineno = p->starting_lineno + end_lineno;
629 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
630
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100631 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300632
633 if (type == ERRORTOKEN) {
634 if (p->tok->done == E_DECODE) {
635 return raise_decode_error(p);
636 }
637 else {
638 return tokenizer_error(p);
639 }
640 }
641
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100642 return 0;
643}
644
645// Instrumentation to count the effectiveness of memoization.
646// The array counts the number of tokens skipped by memoization,
647// indexed by type.
648
649#define NSTATISTICS 2000
650static long memo_statistics[NSTATISTICS];
651
652void
653_PyPegen_clear_memo_statistics()
654{
655 for (int i = 0; i < NSTATISTICS; i++) {
656 memo_statistics[i] = 0;
657 }
658}
659
660PyObject *
661_PyPegen_get_memo_statistics()
662{
663 PyObject *ret = PyList_New(NSTATISTICS);
664 if (ret == NULL) {
665 return NULL;
666 }
667 for (int i = 0; i < NSTATISTICS; i++) {
668 PyObject *value = PyLong_FromLong(memo_statistics[i]);
669 if (value == NULL) {
670 Py_DECREF(ret);
671 return NULL;
672 }
673 // PyList_SetItem borrows a reference to value.
674 if (PyList_SetItem(ret, i, value) < 0) {
675 Py_DECREF(ret);
676 return NULL;
677 }
678 }
679 return ret;
680}
681
682int // bool
683_PyPegen_is_memoized(Parser *p, int type, void *pres)
684{
685 if (p->mark == p->fill) {
686 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300687 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100688 return -1;
689 }
690 }
691
692 Token *t = p->tokens[p->mark];
693
694 for (Memo *m = t->memo; m != NULL; m = m->next) {
695 if (m->type == type) {
696 if (0 <= type && type < NSTATISTICS) {
697 long count = m->mark - p->mark;
698 // A memoized negative result counts for one.
699 if (count <= 0) {
700 count = 1;
701 }
702 memo_statistics[type] += count;
703 }
704 p->mark = m->mark;
705 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100706 return 1;
707 }
708 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100709 return 0;
710}
711
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100712
713int
714_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
715{
716 int mark = p->mark;
717 void *res = func(p);
718 p->mark = mark;
719 return (res != NULL) == positive;
720}
721
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100722int
Pablo Galindo404b23b2020-05-27 00:15:52 +0100723_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
724{
725 int mark = p->mark;
726 void *res = func(p, arg);
727 p->mark = mark;
728 return (res != NULL) == positive;
729}
730
731int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100732_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
733{
734 int mark = p->mark;
735 void *res = func(p, arg);
736 p->mark = mark;
737 return (res != NULL) == positive;
738}
739
740int
741_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
742{
743 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100744 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100745 p->mark = mark;
746 return (res != NULL) == positive;
747}
748
749Token *
750_PyPegen_expect_token(Parser *p, int type)
751{
752 if (p->mark == p->fill) {
753 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300754 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100755 return NULL;
756 }
757 }
758 Token *t = p->tokens[p->mark];
759 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100760 return NULL;
761 }
762 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100763 return t;
764}
765
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700766expr_ty
767_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
768{
769 if (p->mark == p->fill) {
770 if (_PyPegen_fill_token(p) < 0) {
771 p->error_indicator = 1;
772 return NULL;
773 }
774 }
775 Token *t = p->tokens[p->mark];
776 if (t->type != NAME) {
777 return NULL;
778 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300779 char *s = PyBytes_AsString(t->bytes);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700780 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300781 p->error_indicator = 1;
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700782 return NULL;
783 }
784 if (strcmp(s, keyword) != 0) {
785 return NULL;
786 }
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300787 return _PyPegen_name_token(p);
Guido van Rossumb45af1a2020-05-26 10:58:44 -0700788}
789
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100790Token *
791_PyPegen_get_last_nonnwhitespace_token(Parser *p)
792{
793 assert(p->mark >= 0);
794 Token *token = NULL;
795 for (int m = p->mark - 1; m >= 0; m--) {
796 token = p->tokens[m];
797 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
798 break;
799 }
800 }
801 return token;
802}
803
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100804expr_ty
805_PyPegen_name_token(Parser *p)
806{
807 Token *t = _PyPegen_expect_token(p, NAME);
808 if (t == NULL) {
809 return NULL;
810 }
811 char* s = PyBytes_AsString(t->bytes);
812 if (!s) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300813 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100814 return NULL;
815 }
816 PyObject *id = _PyPegen_new_identifier(p, s);
817 if (id == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300818 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100819 return NULL;
820 }
821 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
822 p->arena);
823}
824
825void *
826_PyPegen_string_token(Parser *p)
827{
828 return _PyPegen_expect_token(p, STRING);
829}
830
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100831static PyObject *
832parsenumber_raw(const char *s)
833{
834 const char *end;
835 long x;
836 double dx;
837 Py_complex compl;
838 int imflag;
839
840 assert(s != NULL);
841 errno = 0;
842 end = s + strlen(s) - 1;
843 imflag = *end == 'j' || *end == 'J';
844 if (s[0] == '0') {
845 x = (long)PyOS_strtoul(s, (char **)&end, 0);
846 if (x < 0 && errno == 0) {
847 return PyLong_FromString(s, (char **)0, 0);
848 }
849 }
850 else
851 x = PyOS_strtol(s, (char **)&end, 0);
852 if (*end == '\0') {
853 if (errno != 0)
854 return PyLong_FromString(s, (char **)0, 0);
855 return PyLong_FromLong(x);
856 }
857 /* XXX Huge floats may silently fail */
858 if (imflag) {
859 compl.real = 0.;
860 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
861 if (compl.imag == -1.0 && PyErr_Occurred())
862 return NULL;
863 return PyComplex_FromCComplex(compl);
864 }
865 else {
866 dx = PyOS_string_to_double(s, NULL, NULL);
867 if (dx == -1.0 && PyErr_Occurred())
868 return NULL;
869 return PyFloat_FromDouble(dx);
870 }
871}
872
873static PyObject *
874parsenumber(const char *s)
875{
876 char *dup, *end;
877 PyObject *res = NULL;
878
879 assert(s != NULL);
880
881 if (strchr(s, '_') == NULL) {
882 return parsenumber_raw(s);
883 }
884 /* Create a duplicate without underscores. */
885 dup = PyMem_Malloc(strlen(s) + 1);
886 if (dup == NULL) {
887 return PyErr_NoMemory();
888 }
889 end = dup;
890 for (; *s; s++) {
891 if (*s != '_') {
892 *end++ = *s;
893 }
894 }
895 *end = '\0';
896 res = parsenumber_raw(dup);
897 PyMem_Free(dup);
898 return res;
899}
900
901expr_ty
902_PyPegen_number_token(Parser *p)
903{
904 Token *t = _PyPegen_expect_token(p, NUMBER);
905 if (t == NULL) {
906 return NULL;
907 }
908
909 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100910 if (num_raw == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300911 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100912 return NULL;
913 }
914
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300915 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
916 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700917 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300918 "in Python 3.6 and greater");
919 }
920
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100921 PyObject *c = parsenumber(num_raw);
922
923 if (c == NULL) {
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300924 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100925 return NULL;
926 }
927
928 if (PyArena_AddPyObject(p->arena, c) < 0) {
929 Py_DECREF(c);
Lysandros Nikolaou526e23f2020-05-27 19:04:11 +0300930 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100931 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{
Pablo Galindo2e6593d2020-06-06 00:52:27 +0100941 for (const char *c = cur; c >= p->tok->buf; c--) {
942 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300943 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 Galindo800a35c62020-05-25 18:38:45 +01001069 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001070
1071 return p;
1072}
1073
1074void *
1075_PyPegen_run_parser(Parser *p)
1076{
1077 void *res = _PyPegen_parse(p);
1078 if (res == NULL) {
1079 if (PyErr_Occurred()) {
1080 return NULL;
1081 }
1082 if (p->fill == 0) {
1083 RAISE_SYNTAX_ERROR("error at start before reading any input");
1084 }
1085 else if (p->tok->done == E_EOF) {
1086 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1087 }
1088 else {
1089 if (p->tokens[p->fill-1]->type == INDENT) {
1090 RAISE_INDENTATION_ERROR("unexpected indent");
1091 }
1092 else if (p->tokens[p->fill-1]->type == DEDENT) {
1093 RAISE_INDENTATION_ERROR("unexpected unindent");
1094 }
1095 else {
1096 RAISE_SYNTAX_ERROR("invalid syntax");
1097 }
1098 }
1099 return NULL;
1100 }
1101
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001102 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1103 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1104 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1105 }
1106
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001107 return res;
1108}
1109
1110mod_ty
1111_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1112 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001113 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001114{
1115 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1116 if (tok == NULL) {
1117 if (PyErr_Occurred()) {
1118 raise_tokenizer_init_error(filename_ob);
1119 return NULL;
1120 }
1121 return NULL;
1122 }
1123 // This transfers the ownership to the tokenizer
1124 tok->filename = filename_ob;
1125 Py_INCREF(filename_ob);
1126
1127 // From here on we need to clean up even if there's an error
1128 mod_ty result = NULL;
1129
Pablo Galindo2b74c832020-04-27 18:02:07 +01001130 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001131 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1132 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001133 if (p == NULL) {
1134 goto error;
1135 }
1136
1137 result = _PyPegen_run_parser(p);
1138 _PyPegen_Parser_Free(p);
1139
1140error:
1141 PyTokenizer_Free(tok);
1142 return result;
1143}
1144
1145mod_ty
1146_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001147 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001148{
1149 FILE *fp = fopen(filename, "rb");
1150 if (fp == NULL) {
1151 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1152 return NULL;
1153 }
1154
1155 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001156 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001157
1158 fclose(fp);
1159 return result;
1160}
1161
1162mod_ty
1163_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001164 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001165{
1166 int exec_input = start_rule == Py_file_input;
1167
1168 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001169 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001170 tok = PyTokenizer_FromUTF8(str, exec_input);
1171 } else {
1172 tok = PyTokenizer_FromString(str, exec_input);
1173 }
1174 if (tok == NULL) {
1175 if (PyErr_Occurred()) {
1176 raise_tokenizer_init_error(filename_ob);
1177 }
1178 return NULL;
1179 }
1180 // This transfers the ownership to the tokenizer
1181 tok->filename = filename_ob;
1182 Py_INCREF(filename_ob);
1183
1184 // We need to clear up from here on
1185 mod_ty result = NULL;
1186
Pablo Galindo2b74c832020-04-27 18:02:07 +01001187 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001188 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001189 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1190 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001191 if (p == NULL) {
1192 goto error;
1193 }
1194
1195 result = _PyPegen_run_parser(p);
1196 _PyPegen_Parser_Free(p);
1197
1198error:
1199 PyTokenizer_Free(tok);
1200 return result;
1201}
1202
1203void *
1204_PyPegen_interactive_exit(Parser *p)
1205{
1206 if (p->errcode) {
1207 *(p->errcode) = E_EOF;
1208 }
1209 return NULL;
1210}
1211
1212/* Creates a single-element asdl_seq* that contains a */
1213asdl_seq *
1214_PyPegen_singleton_seq(Parser *p, void *a)
1215{
1216 assert(a != NULL);
1217 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1218 if (!seq) {
1219 return NULL;
1220 }
1221 asdl_seq_SET(seq, 0, a);
1222 return seq;
1223}
1224
1225/* Creates a copy of seq and prepends a to it */
1226asdl_seq *
1227_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1228{
1229 assert(a != NULL);
1230 if (!seq) {
1231 return _PyPegen_singleton_seq(p, a);
1232 }
1233
1234 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1235 if (!new_seq) {
1236 return NULL;
1237 }
1238
1239 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001240 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001241 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1242 }
1243 return new_seq;
1244}
1245
Guido van Rossumc001c092020-04-30 12:12:19 -07001246/* Creates a copy of seq and appends a to it */
1247asdl_seq *
1248_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1249{
1250 assert(a != NULL);
1251 if (!seq) {
1252 return _PyPegen_singleton_seq(p, a);
1253 }
1254
1255 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1256 if (!new_seq) {
1257 return NULL;
1258 }
1259
1260 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1261 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1262 }
1263 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1264 return new_seq;
1265}
1266
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001267static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001268_get_flattened_seq_size(asdl_seq *seqs)
1269{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001270 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001271 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1272 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1273 size += asdl_seq_LEN(inner_seq);
1274 }
1275 return size;
1276}
1277
1278/* Flattens an asdl_seq* of asdl_seq*s */
1279asdl_seq *
1280_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1281{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001282 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001283 assert(flattened_seq_size > 0);
1284
1285 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1286 if (!flattened_seq) {
1287 return NULL;
1288 }
1289
1290 int flattened_seq_idx = 0;
1291 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1292 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001293 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001294 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1295 }
1296 }
1297 assert(flattened_seq_idx == flattened_seq_size);
1298
1299 return flattened_seq;
1300}
1301
1302/* Creates a new name of the form <first_name>.<second_name> */
1303expr_ty
1304_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1305{
1306 assert(first_name != NULL && second_name != NULL);
1307 PyObject *first_identifier = first_name->v.Name.id;
1308 PyObject *second_identifier = second_name->v.Name.id;
1309
1310 if (PyUnicode_READY(first_identifier) == -1) {
1311 return NULL;
1312 }
1313 if (PyUnicode_READY(second_identifier) == -1) {
1314 return NULL;
1315 }
1316 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1317 if (!first_str) {
1318 return NULL;
1319 }
1320 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1321 if (!second_str) {
1322 return NULL;
1323 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001324 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001325
1326 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1327 if (!str) {
1328 return NULL;
1329 }
1330
1331 char *s = PyBytes_AS_STRING(str);
1332 if (!s) {
1333 return NULL;
1334 }
1335
1336 strcpy(s, first_str);
1337 s += strlen(first_str);
1338 *s++ = '.';
1339 strcpy(s, second_str);
1340 s += strlen(second_str);
1341 *s = '\0';
1342
1343 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1344 Py_DECREF(str);
1345 if (!uni) {
1346 return NULL;
1347 }
1348 PyUnicode_InternInPlace(&uni);
1349 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1350 Py_DECREF(uni);
1351 return NULL;
1352 }
1353
1354 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1355}
1356
1357/* Counts the total number of dots in seq's tokens */
1358int
1359_PyPegen_seq_count_dots(asdl_seq *seq)
1360{
1361 int number_of_dots = 0;
1362 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1363 Token *current_expr = asdl_seq_GET(seq, i);
1364 switch (current_expr->type) {
1365 case ELLIPSIS:
1366 number_of_dots += 3;
1367 break;
1368 case DOT:
1369 number_of_dots += 1;
1370 break;
1371 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001372 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001373 }
1374 }
1375
1376 return number_of_dots;
1377}
1378
1379/* Creates an alias with '*' as the identifier name */
1380alias_ty
1381_PyPegen_alias_for_star(Parser *p)
1382{
1383 PyObject *str = PyUnicode_InternFromString("*");
1384 if (!str) {
1385 return NULL;
1386 }
1387 if (PyArena_AddPyObject(p->arena, str) < 0) {
1388 Py_DECREF(str);
1389 return NULL;
1390 }
1391 return alias(str, NULL, p->arena);
1392}
1393
1394/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1395asdl_seq *
1396_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1397{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001398 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001399 assert(len > 0);
1400
1401 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1402 if (!new_seq) {
1403 return NULL;
1404 }
1405 for (Py_ssize_t i = 0; i < len; i++) {
1406 expr_ty e = asdl_seq_GET(seq, i);
1407 asdl_seq_SET(new_seq, i, e->v.Name.id);
1408 }
1409 return new_seq;
1410}
1411
1412/* Constructs a CmpopExprPair */
1413CmpopExprPair *
1414_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1415{
1416 assert(expr != NULL);
1417 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1418 if (!a) {
1419 return NULL;
1420 }
1421 a->cmpop = cmpop;
1422 a->expr = expr;
1423 return a;
1424}
1425
1426asdl_int_seq *
1427_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1428{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001429 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001430 assert(len > 0);
1431
1432 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1433 if (!new_seq) {
1434 return NULL;
1435 }
1436 for (Py_ssize_t i = 0; i < len; i++) {
1437 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1438 asdl_seq_SET(new_seq, i, pair->cmpop);
1439 }
1440 return new_seq;
1441}
1442
1443asdl_seq *
1444_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1445{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001446 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001447 assert(len > 0);
1448
1449 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1450 if (!new_seq) {
1451 return NULL;
1452 }
1453 for (Py_ssize_t i = 0; i < len; i++) {
1454 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1455 asdl_seq_SET(new_seq, i, pair->expr);
1456 }
1457 return new_seq;
1458}
1459
1460/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1461static asdl_seq *
1462_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1463{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001464 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001465 if (len == 0) {
1466 return NULL;
1467 }
1468
1469 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1470 if (!new_seq) {
1471 return NULL;
1472 }
1473 for (Py_ssize_t i = 0; i < len; i++) {
1474 expr_ty e = asdl_seq_GET(seq, i);
1475 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1476 }
1477 return new_seq;
1478}
1479
1480static expr_ty
1481_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1482{
1483 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1484}
1485
1486static expr_ty
1487_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1488{
1489 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1490}
1491
1492static expr_ty
1493_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1494{
1495 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1496}
1497
1498static expr_ty
1499_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1500{
1501 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1502}
1503
1504static expr_ty
1505_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1506{
1507 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1508}
1509
1510static expr_ty
1511_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1512{
1513 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1514}
1515
1516/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1517expr_ty
1518_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1519{
1520 assert(expr != NULL);
1521
1522 expr_ty new = NULL;
1523 switch (expr->kind) {
1524 case Name_kind:
1525 new = _set_name_context(p, expr, ctx);
1526 break;
1527 case Tuple_kind:
1528 new = _set_tuple_context(p, expr, ctx);
1529 break;
1530 case List_kind:
1531 new = _set_list_context(p, expr, ctx);
1532 break;
1533 case Subscript_kind:
1534 new = _set_subscript_context(p, expr, ctx);
1535 break;
1536 case Attribute_kind:
1537 new = _set_attribute_context(p, expr, ctx);
1538 break;
1539 case Starred_kind:
1540 new = _set_starred_context(p, expr, ctx);
1541 break;
1542 default:
1543 new = expr;
1544 }
1545 return new;
1546}
1547
1548/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1549KeyValuePair *
1550_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1551{
1552 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1553 if (!a) {
1554 return NULL;
1555 }
1556 a->key = key;
1557 a->value = value;
1558 return a;
1559}
1560
1561/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1562asdl_seq *
1563_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1564{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001565 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001566 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1567 if (!new_seq) {
1568 return NULL;
1569 }
1570 for (Py_ssize_t i = 0; i < len; i++) {
1571 KeyValuePair *pair = asdl_seq_GET(seq, i);
1572 asdl_seq_SET(new_seq, i, pair->key);
1573 }
1574 return new_seq;
1575}
1576
1577/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1578asdl_seq *
1579_PyPegen_get_values(Parser *p, asdl_seq *seq)
1580{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001581 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001582 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1583 if (!new_seq) {
1584 return NULL;
1585 }
1586 for (Py_ssize_t i = 0; i < len; i++) {
1587 KeyValuePair *pair = asdl_seq_GET(seq, i);
1588 asdl_seq_SET(new_seq, i, pair->value);
1589 }
1590 return new_seq;
1591}
1592
1593/* Constructs a NameDefaultPair */
1594NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001595_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001596{
1597 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1598 if (!a) {
1599 return NULL;
1600 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001601 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001602 a->value = value;
1603 return a;
1604}
1605
1606/* Constructs a SlashWithDefault */
1607SlashWithDefault *
1608_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1609{
1610 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1611 if (!a) {
1612 return NULL;
1613 }
1614 a->plain_names = plain_names;
1615 a->names_with_defaults = names_with_defaults;
1616 return a;
1617}
1618
1619/* Constructs a StarEtc */
1620StarEtc *
1621_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1622{
1623 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1624 if (!a) {
1625 return NULL;
1626 }
1627 a->vararg = vararg;
1628 a->kwonlyargs = kwonlyargs;
1629 a->kwarg = kwarg;
1630 return a;
1631}
1632
1633asdl_seq *
1634_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1635{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001636 Py_ssize_t first_len = asdl_seq_LEN(a);
1637 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001638 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1639 if (!new_seq) {
1640 return NULL;
1641 }
1642
1643 int k = 0;
1644 for (Py_ssize_t i = 0; i < first_len; i++) {
1645 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1646 }
1647 for (Py_ssize_t i = 0; i < second_len; i++) {
1648 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1649 }
1650
1651 return new_seq;
1652}
1653
1654static asdl_seq *
1655_get_names(Parser *p, asdl_seq *names_with_defaults)
1656{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001657 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001658 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1659 if (!seq) {
1660 return NULL;
1661 }
1662 for (Py_ssize_t i = 0; i < len; i++) {
1663 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1664 asdl_seq_SET(seq, i, pair->arg);
1665 }
1666 return seq;
1667}
1668
1669static asdl_seq *
1670_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1671{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001672 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001673 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1674 if (!seq) {
1675 return NULL;
1676 }
1677 for (Py_ssize_t i = 0; i < len; i++) {
1678 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1679 asdl_seq_SET(seq, i, pair->value);
1680 }
1681 return seq;
1682}
1683
1684/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1685arguments_ty
1686_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1687 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1688 asdl_seq *names_with_default, StarEtc *star_etc)
1689{
1690 asdl_seq *posonlyargs;
1691 if (slash_without_default != NULL) {
1692 posonlyargs = slash_without_default;
1693 }
1694 else if (slash_with_default != NULL) {
1695 asdl_seq *slash_with_default_names =
1696 _get_names(p, slash_with_default->names_with_defaults);
1697 if (!slash_with_default_names) {
1698 return NULL;
1699 }
1700 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1701 if (!posonlyargs) {
1702 return NULL;
1703 }
1704 }
1705 else {
1706 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1707 if (!posonlyargs) {
1708 return NULL;
1709 }
1710 }
1711
1712 asdl_seq *posargs;
1713 if (plain_names != NULL && names_with_default != NULL) {
1714 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1715 if (!names_with_default_names) {
1716 return NULL;
1717 }
1718 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1719 if (!posargs) {
1720 return NULL;
1721 }
1722 }
1723 else if (plain_names == NULL && names_with_default != NULL) {
1724 posargs = _get_names(p, names_with_default);
1725 if (!posargs) {
1726 return NULL;
1727 }
1728 }
1729 else if (plain_names != NULL && names_with_default == NULL) {
1730 posargs = plain_names;
1731 }
1732 else {
1733 posargs = _Py_asdl_seq_new(0, p->arena);
1734 if (!posargs) {
1735 return NULL;
1736 }
1737 }
1738
1739 asdl_seq *posdefaults;
1740 if (slash_with_default != NULL && names_with_default != NULL) {
1741 asdl_seq *slash_with_default_values =
1742 _get_defaults(p, slash_with_default->names_with_defaults);
1743 if (!slash_with_default_values) {
1744 return NULL;
1745 }
1746 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1747 if (!names_with_default_values) {
1748 return NULL;
1749 }
1750 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1751 if (!posdefaults) {
1752 return NULL;
1753 }
1754 }
1755 else if (slash_with_default == NULL && names_with_default != NULL) {
1756 posdefaults = _get_defaults(p, names_with_default);
1757 if (!posdefaults) {
1758 return NULL;
1759 }
1760 }
1761 else if (slash_with_default != NULL && names_with_default == NULL) {
1762 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1763 if (!posdefaults) {
1764 return NULL;
1765 }
1766 }
1767 else {
1768 posdefaults = _Py_asdl_seq_new(0, p->arena);
1769 if (!posdefaults) {
1770 return NULL;
1771 }
1772 }
1773
1774 arg_ty vararg = NULL;
1775 if (star_etc != NULL && star_etc->vararg != NULL) {
1776 vararg = star_etc->vararg;
1777 }
1778
1779 asdl_seq *kwonlyargs;
1780 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1781 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1782 if (!kwonlyargs) {
1783 return NULL;
1784 }
1785 }
1786 else {
1787 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1788 if (!kwonlyargs) {
1789 return NULL;
1790 }
1791 }
1792
1793 asdl_seq *kwdefaults;
1794 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1795 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1796 if (!kwdefaults) {
1797 return NULL;
1798 }
1799 }
1800 else {
1801 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1802 if (!kwdefaults) {
1803 return NULL;
1804 }
1805 }
1806
1807 arg_ty kwarg = NULL;
1808 if (star_etc != NULL && star_etc->kwarg != NULL) {
1809 kwarg = star_etc->kwarg;
1810 }
1811
1812 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1813 posdefaults, p->arena);
1814}
1815
1816/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1817 * arguments. */
1818arguments_ty
1819_PyPegen_empty_arguments(Parser *p)
1820{
1821 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1822 if (!posonlyargs) {
1823 return NULL;
1824 }
1825 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1826 if (!posargs) {
1827 return NULL;
1828 }
1829 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1830 if (!posdefaults) {
1831 return NULL;
1832 }
1833 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1834 if (!kwonlyargs) {
1835 return NULL;
1836 }
1837 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1838 if (!kwdefaults) {
1839 return NULL;
1840 }
1841
1842 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1843 p->arena);
1844}
1845
1846/* Encapsulates the value of an operator_ty into an AugOperator struct */
1847AugOperator *
1848_PyPegen_augoperator(Parser *p, operator_ty kind)
1849{
1850 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1851 if (!a) {
1852 return NULL;
1853 }
1854 a->kind = kind;
1855 return a;
1856}
1857
1858/* Construct a FunctionDef equivalent to function_def, but with decorators */
1859stmt_ty
1860_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1861{
1862 assert(function_def != NULL);
1863 if (function_def->kind == AsyncFunctionDef_kind) {
1864 return _Py_AsyncFunctionDef(
1865 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1866 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1867 function_def->v.FunctionDef.type_comment, function_def->lineno,
1868 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1869 p->arena);
1870 }
1871
1872 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1873 function_def->v.FunctionDef.body, decorators,
1874 function_def->v.FunctionDef.returns,
1875 function_def->v.FunctionDef.type_comment, function_def->lineno,
1876 function_def->col_offset, function_def->end_lineno,
1877 function_def->end_col_offset, p->arena);
1878}
1879
1880/* Construct a ClassDef equivalent to class_def, but with decorators */
1881stmt_ty
1882_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1883{
1884 assert(class_def != NULL);
1885 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1886 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1887 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1888 class_def->end_col_offset, p->arena);
1889}
1890
1891/* Construct a KeywordOrStarred */
1892KeywordOrStarred *
1893_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1894{
1895 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1896 if (!a) {
1897 return NULL;
1898 }
1899 a->element = element;
1900 a->is_keyword = is_keyword;
1901 return a;
1902}
1903
1904/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1905static int
1906_seq_number_of_starred_exprs(asdl_seq *seq)
1907{
1908 int n = 0;
1909 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1910 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1911 if (!k->is_keyword) {
1912 n++;
1913 }
1914 }
1915 return n;
1916}
1917
1918/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1919asdl_seq *
1920_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1921{
1922 int new_len = _seq_number_of_starred_exprs(kwargs);
1923 if (new_len == 0) {
1924 return NULL;
1925 }
1926 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1927 if (!new_seq) {
1928 return NULL;
1929 }
1930
1931 int idx = 0;
1932 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1933 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1934 if (!k->is_keyword) {
1935 asdl_seq_SET(new_seq, idx++, k->element);
1936 }
1937 }
1938 return new_seq;
1939}
1940
1941/* Return a new asdl_seq* with only the keywords in kwargs */
1942asdl_seq *
1943_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1944{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001945 Py_ssize_t len = asdl_seq_LEN(kwargs);
1946 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001947 if (new_len == 0) {
1948 return NULL;
1949 }
1950 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1951 if (!new_seq) {
1952 return NULL;
1953 }
1954
1955 int idx = 0;
1956 for (Py_ssize_t i = 0; i < len; i++) {
1957 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1958 if (k->is_keyword) {
1959 asdl_seq_SET(new_seq, idx++, k->element);
1960 }
1961 }
1962 return new_seq;
1963}
1964
1965expr_ty
1966_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1967{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001968 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001969 assert(len > 0);
1970
1971 Token *first = asdl_seq_GET(strings, 0);
1972 Token *last = asdl_seq_GET(strings, len - 1);
1973
1974 int bytesmode = 0;
1975 PyObject *bytes_str = NULL;
1976
1977 FstringParser state;
1978 _PyPegen_FstringParser_Init(&state);
1979
1980 for (Py_ssize_t i = 0; i < len; i++) {
1981 Token *t = asdl_seq_GET(strings, i);
1982
1983 int this_bytesmode;
1984 int this_rawmode;
1985 PyObject *s;
1986 const char *fstr;
1987 Py_ssize_t fstrlen = -1;
1988
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001989 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001990 goto error;
1991 }
1992
1993 /* Check that we are not mixing bytes with unicode. */
1994 if (i != 0 && bytesmode != this_bytesmode) {
1995 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1996 Py_XDECREF(s);
1997 goto error;
1998 }
1999 bytesmode = this_bytesmode;
2000
2001 if (fstr != NULL) {
2002 assert(s == NULL && !bytesmode);
2003
2004 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2005 this_rawmode, 0, first, t, last);
2006 if (result < 0) {
2007 goto error;
2008 }
2009 }
2010 else {
2011 /* String or byte string. */
2012 assert(s != NULL && fstr == NULL);
2013 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2014
2015 if (bytesmode) {
2016 if (i == 0) {
2017 bytes_str = s;
2018 }
2019 else {
2020 PyBytes_ConcatAndDel(&bytes_str, s);
2021 if (!bytes_str) {
2022 goto error;
2023 }
2024 }
2025 }
2026 else {
2027 /* This is a regular string. Concatenate it. */
2028 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2029 goto error;
2030 }
2031 }
2032 }
2033 }
2034
2035 if (bytesmode) {
2036 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2037 goto error;
2038 }
2039 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2040 last->end_col_offset, p->arena);
2041 }
2042
2043 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2044
2045error:
2046 Py_XDECREF(bytes_str);
2047 _PyPegen_FstringParser_Dealloc(&state);
2048 if (PyErr_Occurred()) {
2049 raise_decode_error(p);
2050 }
2051 return NULL;
2052}
Guido van Rossumc001c092020-04-30 12:12:19 -07002053
2054mod_ty
2055_PyPegen_make_module(Parser *p, asdl_seq *a) {
2056 asdl_seq *type_ignores = NULL;
2057 Py_ssize_t num = p->type_ignore_comments.num_items;
2058 if (num > 0) {
2059 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2060 type_ignores = _Py_asdl_seq_new(num, p->arena);
2061 if (type_ignores == NULL) {
2062 return NULL;
2063 }
2064 for (int i = 0; i < num; i++) {
2065 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2066 if (tag == NULL) {
2067 return NULL;
2068 }
2069 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2070 if (ti == NULL) {
2071 return NULL;
2072 }
2073 asdl_seq_SET(type_ignores, i, ti);
2074 }
2075 }
2076 return Module(a, type_ignores, p->arena);
2077}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002078
2079// Error reporting helpers
2080
2081expr_ty
2082_PyPegen_get_invalid_target(expr_ty e)
2083{
2084 if (e == NULL) {
2085 return NULL;
2086 }
2087
2088#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2089 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2090 for (Py_ssize_t i = 0; i < len; i++) {\
2091 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2092 expr_ty child = _PyPegen_get_invalid_target(other);\
2093 if (child != NULL) {\
2094 return child;\
2095 }\
2096 }\
2097 } while (0)
2098
2099 // We only need to visit List and Tuple nodes recursively as those
2100 // are the only ones that can contain valid names in targets when
2101 // they are parsed as expressions. Any other kind of expression
2102 // that is a container (like Sets or Dicts) is directly invalid and
2103 // we don't need to visit it recursively.
2104
2105 switch (e->kind) {
2106 case List_kind: {
2107 VISIT_CONTAINER(e, List);
2108 return NULL;
2109 }
2110 case Tuple_kind: {
2111 VISIT_CONTAINER(e, Tuple);
2112 return NULL;
2113 }
2114 case Starred_kind:
2115 return _PyPegen_get_invalid_target(e->v.Starred.value);
2116 case Name_kind:
2117 case Subscript_kind:
2118 case Attribute_kind:
2119 return NULL;
2120 default:
2121 return e;
2122 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002123}
2124
2125void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2126 int kwarg_unpacking = 0;
2127 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2128 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2129 if (!keyword->arg) {
2130 kwarg_unpacking = 1;
2131 }
2132 }
2133
2134 const char *msg = NULL;
2135 if (kwarg_unpacking) {
2136 msg = "positional argument follows keyword argument unpacking";
2137 } else {
2138 msg = "positional argument follows keyword argument";
2139 }
2140
2141 return RAISE_SYNTAX_ERROR(msg);
2142}
Lysandros Nikolaouae145832020-05-22 03:56:52 +03002143
2144void *
2145_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2146{
2147 /* The rule that calls this function is 'args for_if_clauses'.
2148 For the input f(L, x for x in y), L and x are in args and
2149 the for is parsed as a for_if_clause. We have to check if
2150 len <= 1, so that input like dict((a, b) for a, b in x)
2151 gets successfully parsed and then we pass the last
2152 argument (x in the above example) as the location of the
2153 error */
2154 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2155 if (len <= 1) {
2156 return NULL;
2157 }
2158
2159 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2160 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2161 "Generator expression must be parenthesized"
2162 );
2163}