blob: 76442de6502525c1cbdd8abe78708f1bf920f395 [file] [log] [blame]
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001#include <Python.h>
2#include <errcode.h>
3#include "../tokenizer.h"
4
5#include "pegen.h"
6#include "parse_string.h"
7
Guido van Rossumc001c092020-04-30 12:12:19 -07008PyObject *
9_PyPegen_new_type_comment(Parser *p, char *s)
10{
11 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
12 if (res == NULL) {
13 return NULL;
14 }
15 if (PyArena_AddPyObject(p->arena, res) < 0) {
16 Py_DECREF(res);
17 return NULL;
18 }
19 return res;
20}
21
22arg_ty
23_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
24{
25 if (tc == NULL) {
26 return a;
27 }
28 char *bytes = PyBytes_AsString(tc->bytes);
29 if (bytes == NULL) {
30 return NULL;
31 }
32 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
33 if (tco == NULL) {
34 return NULL;
35 }
36 return arg(a->arg, a->annotation, tco,
37 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
38 p->arena);
39}
40
Pablo Galindoc5fc1562020-04-22 23:29:27 +010041static int
42init_normalization(Parser *p)
43{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030044 if (p->normalize) {
45 return 1;
46 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +010047 PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
48 if (!m)
49 {
50 return 0;
51 }
52 p->normalize = PyObject_GetAttrString(m, "normalize");
53 Py_DECREF(m);
54 if (!p->normalize)
55 {
56 return 0;
57 }
58 return 1;
59}
60
Pablo Galindo2b74c832020-04-27 18:02:07 +010061/* Checks if the NOTEQUAL token is valid given the current parser flags
620 indicates success and nonzero indicates failure (an exception may be set) */
63int
64_PyPegen_check_barry_as_flufl(Parser *p) {
65 Token *t = p->tokens[p->fill - 1];
66 assert(t->bytes != NULL);
67 assert(t->type == NOTEQUAL);
68
69 char* tok_str = PyBytes_AS_STRING(t->bytes);
70 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>")){
71 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
72 return -1;
73 } else if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
74 return strcmp(tok_str, "!=");
75 }
76 return 0;
77}
78
Pablo Galindoc5fc1562020-04-22 23:29:27 +010079PyObject *
80_PyPegen_new_identifier(Parser *p, char *n)
81{
82 PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
83 if (!id) {
84 goto error;
85 }
86 /* PyUnicode_DecodeUTF8 should always return a ready string. */
87 assert(PyUnicode_IS_READY(id));
88 /* Check whether there are non-ASCII characters in the
89 identifier; if so, normalize to NFKC. */
90 if (!PyUnicode_IS_ASCII(id))
91 {
92 PyObject *id2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +030093 if (!init_normalization(p))
Pablo Galindoc5fc1562020-04-22 23:29:27 +010094 {
95 Py_DECREF(id);
96 goto error;
97 }
98 PyObject *form = PyUnicode_InternFromString("NFKC");
99 if (form == NULL)
100 {
101 Py_DECREF(id);
102 goto error;
103 }
104 PyObject *args[2] = {form, id};
105 id2 = _PyObject_FastCall(p->normalize, args, 2);
106 Py_DECREF(id);
107 Py_DECREF(form);
108 if (!id2) {
109 goto error;
110 }
111 if (!PyUnicode_Check(id2))
112 {
113 PyErr_Format(PyExc_TypeError,
114 "unicodedata.normalize() must return a string, not "
115 "%.200s",
116 _PyType_Name(Py_TYPE(id2)));
117 Py_DECREF(id2);
118 goto error;
119 }
120 id = id2;
121 }
122 PyUnicode_InternInPlace(&id);
123 if (PyArena_AddPyObject(p->arena, id) < 0)
124 {
125 Py_DECREF(id);
126 goto error;
127 }
128 return id;
129
130error:
131 p->error_indicator = 1;
132 return NULL;
133}
134
135static PyObject *
136_create_dummy_identifier(Parser *p)
137{
138 return _PyPegen_new_identifier(p, "");
139}
140
141static inline Py_ssize_t
142byte_offset_to_character_offset(PyObject *line, int col_offset)
143{
144 const char *str = PyUnicode_AsUTF8(line);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300145 if (!str) {
146 return 0;
147 }
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300148 PyObject *text = PyUnicode_DecodeUTF8(str, col_offset, "replace");
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100149 if (!text) {
150 return 0;
151 }
152 Py_ssize_t size = PyUnicode_GET_LENGTH(text);
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300153 str = PyUnicode_AsUTF8(text);
154 if (str != NULL && (int)strlen(str) == col_offset) {
155 size = strlen(str);
156 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100157 Py_DECREF(text);
158 return size;
159}
160
161const char *
162_PyPegen_get_expr_name(expr_ty e)
163{
164 switch (e->kind) {
165 case Attribute_kind:
166 return "attribute";
167 case Subscript_kind:
168 return "subscript";
169 case Starred_kind:
170 return "starred";
171 case Name_kind:
172 return "name";
173 case List_kind:
174 return "list";
175 case Tuple_kind:
176 return "tuple";
177 case Lambda_kind:
178 return "lambda";
179 case Call_kind:
180 return "function call";
181 case BoolOp_kind:
182 case BinOp_kind:
183 case UnaryOp_kind:
184 return "operator";
185 case GeneratorExp_kind:
186 return "generator expression";
187 case Yield_kind:
188 case YieldFrom_kind:
189 return "yield expression";
190 case Await_kind:
191 return "await expression";
192 case ListComp_kind:
193 return "list comprehension";
194 case SetComp_kind:
195 return "set comprehension";
196 case DictComp_kind:
197 return "dict comprehension";
198 case Dict_kind:
199 return "dict display";
200 case Set_kind:
201 return "set display";
202 case JoinedStr_kind:
203 case FormattedValue_kind:
204 return "f-string expression";
205 case Constant_kind: {
206 PyObject *value = e->v.Constant.value;
207 if (value == Py_None) {
208 return "None";
209 }
210 if (value == Py_False) {
211 return "False";
212 }
213 if (value == Py_True) {
214 return "True";
215 }
216 if (value == Py_Ellipsis) {
217 return "Ellipsis";
218 }
219 return "literal";
220 }
221 case Compare_kind:
222 return "comparison";
223 case IfExp_kind:
224 return "conditional expression";
225 case NamedExpr_kind:
226 return "named expression";
227 default:
228 PyErr_Format(PyExc_SystemError,
229 "unexpected expression in assignment %d (line %d)",
230 e->kind, e->lineno);
231 return NULL;
232 }
233}
234
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300235static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100236raise_decode_error(Parser *p)
237{
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300238 assert(PyErr_Occurred());
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100239 const char *errtype = NULL;
240 if (PyErr_ExceptionMatches(PyExc_UnicodeError)) {
241 errtype = "unicode error";
242 }
243 else if (PyErr_ExceptionMatches(PyExc_ValueError)) {
244 errtype = "value error";
245 }
246 if (errtype) {
247 PyObject *type, *value, *tback, *errstr;
248 PyErr_Fetch(&type, &value, &tback);
249 errstr = PyObject_Str(value);
250 if (errstr) {
251 RAISE_SYNTAX_ERROR("(%s) %U", errtype, errstr);
252 Py_DECREF(errstr);
253 }
254 else {
255 PyErr_Clear();
256 RAISE_SYNTAX_ERROR("(%s) unknown error", errtype);
257 }
258 Py_XDECREF(type);
259 Py_XDECREF(value);
260 Py_XDECREF(tback);
261 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300262
263 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100264}
265
266static void
267raise_tokenizer_init_error(PyObject *filename)
268{
269 if (!(PyErr_ExceptionMatches(PyExc_LookupError)
270 || PyErr_ExceptionMatches(PyExc_ValueError)
271 || PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))) {
272 return;
273 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300274 PyObject *errstr = NULL;
275 PyObject *tuple = NULL;
276 PyObject *type, *value, *tback;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100277 PyErr_Fetch(&type, &value, &tback);
278 errstr = PyObject_Str(value);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300279 if (!errstr) {
280 goto error;
281 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100282
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300283 PyObject *tmp = Py_BuildValue("(OiiO)", filename, 0, -1, Py_None);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100284 if (!tmp) {
285 goto error;
286 }
287
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300288 tuple = PyTuple_Pack(2, errstr, tmp);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100289 Py_DECREF(tmp);
290 if (!value) {
291 goto error;
292 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300293 PyErr_SetObject(PyExc_SyntaxError, tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100294
295error:
296 Py_XDECREF(type);
297 Py_XDECREF(value);
298 Py_XDECREF(tback);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300299 Py_XDECREF(errstr);
300 Py_XDECREF(tuple);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100301}
302
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100303static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100304tokenizer_error(Parser *p)
305{
306 if (PyErr_Occurred()) {
307 return -1;
308 }
309
310 const char *msg = NULL;
311 PyObject* errtype = PyExc_SyntaxError;
312 switch (p->tok->done) {
313 case E_TOKEN:
314 msg = "invalid token";
315 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100316 case E_EOFS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300317 RAISE_SYNTAX_ERROR("EOF while scanning triple-quoted string literal");
318 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100319 case E_EOLS:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300320 RAISE_SYNTAX_ERROR("EOL while scanning string literal");
321 return -1;
Lysandros Nikolaoud55133f2020-04-28 03:23:35 +0300322 case E_EOF:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300323 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
324 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100325 case E_DEDENT:
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300326 RAISE_INDENTATION_ERROR("unindent does not match any outer indentation level");
327 return -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100328 case E_INTR:
329 if (!PyErr_Occurred()) {
330 PyErr_SetNone(PyExc_KeyboardInterrupt);
331 }
332 return -1;
333 case E_NOMEM:
334 PyErr_NoMemory();
335 return -1;
336 case E_TABSPACE:
337 errtype = PyExc_TabError;
338 msg = "inconsistent use of tabs and spaces in indentation";
339 break;
340 case E_TOODEEP:
341 errtype = PyExc_IndentationError;
342 msg = "too many levels of indentation";
343 break;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100344 case E_LINECONT:
345 msg = "unexpected character after line continuation character";
346 break;
347 default:
348 msg = "unknown parsing error";
349 }
350
351 PyErr_Format(errtype, msg);
352 // There is no reliable column information for this error
353 PyErr_SyntaxLocationObject(p->tok->filename, p->tok->lineno, 0);
354
355 return -1;
356}
357
358void *
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300359_PyPegen_raise_error(Parser *p, PyObject *errtype, const char *errmsg, ...)
360{
361 Token *t = p->known_err_token != NULL ? p->known_err_token : p->tokens[p->fill - 1];
362 int col_offset;
363 if (t->col_offset == -1) {
364 col_offset = Py_SAFE_DOWNCAST(p->tok->cur - p->tok->buf,
365 intptr_t, int);
366 } else {
367 col_offset = t->col_offset + 1;
368 }
369
370 va_list va;
371 va_start(va, errmsg);
372 _PyPegen_raise_error_known_location(p, errtype, t->lineno,
373 col_offset, errmsg, va);
374 va_end(va);
375
376 return NULL;
377}
378
379
380void *
381_PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
382 int lineno, int col_offset,
383 const char *errmsg, va_list va)
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100384{
385 PyObject *value = NULL;
386 PyObject *errstr = NULL;
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300387 PyObject *error_line = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100388 PyObject *tmp = NULL;
Lysandros Nikolaou7f06af62020-05-04 03:20:09 +0300389 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100390
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100391 errstr = PyUnicode_FromFormatV(errmsg, va);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100392 if (!errstr) {
393 goto error;
394 }
395
396 if (p->start_rule == Py_file_input) {
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300397 error_line = PyErr_ProgramTextObject(p->tok->filename, lineno);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100398 }
399
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300400 if (!error_line) {
Pablo Galindobcc30362020-05-14 21:11:48 +0100401 Py_ssize_t size = p->tok->inp - p->tok->buf;
402 if (size && p->tok->buf[size-1] == '\n') {
403 size--;
404 }
405 error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300406 if (!error_line) {
407 goto error;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300408 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100409 }
410
Miss Islington (bot)11fb6052020-05-23 22:20:44 -0700411 Py_ssize_t col_number = byte_offset_to_character_offset(error_line, col_offset);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300412
413 tmp = Py_BuildValue("(OiiN)", p->tok->filename, lineno, col_number, error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100414 if (!tmp) {
415 goto error;
416 }
417 value = PyTuple_Pack(2, errstr, tmp);
418 Py_DECREF(tmp);
419 if (!value) {
420 goto error;
421 }
422 PyErr_SetObject(errtype, value);
423
424 Py_DECREF(errstr);
425 Py_DECREF(value);
426 return NULL;
427
428error:
429 Py_XDECREF(errstr);
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300430 Py_XDECREF(error_line);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100431 return NULL;
432}
433
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100434#if 0
435static const char *
436token_name(int type)
437{
438 if (0 <= type && type <= N_TOKENS) {
439 return _PyParser_TokenNames[type];
440 }
441 return "<Huh?>";
442}
443#endif
444
445// Here, mark is the start of the node, while p->mark is the end.
446// If node==NULL, they should be the same.
447int
448_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
449{
450 // Insert in front
451 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
452 if (m == NULL) {
453 return -1;
454 }
455 m->type = type;
456 m->node = node;
457 m->mark = p->mark;
458 m->next = p->tokens[mark]->memo;
459 p->tokens[mark]->memo = m;
460 return 0;
461}
462
463// Like _PyPegen_insert_memo(), but updates an existing node if found.
464int
465_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
466{
467 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
468 if (m->type == type) {
469 // Update existing node.
470 m->node = node;
471 m->mark = p->mark;
472 return 0;
473 }
474 }
475 // Insert new node.
476 return _PyPegen_insert_memo(p, mark, type, node);
477}
478
479// Return dummy NAME.
480void *
481_PyPegen_dummy_name(Parser *p, ...)
482{
483 static void *cache = NULL;
484
485 if (cache != NULL) {
486 return cache;
487 }
488
489 PyObject *id = _create_dummy_identifier(p);
490 if (!id) {
491 return NULL;
492 }
493 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
494 return cache;
495}
496
497static int
498_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
499{
500 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
501 return NAME;
502 }
503 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
504 if (strncmp(k->str, name, name_len) == 0) {
505 return k->type;
506 }
507 }
508 return NAME;
509}
510
Guido van Rossumc001c092020-04-30 12:12:19 -0700511static int
512growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
513 assert(initial_size > 0);
514 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
515 arr->size = initial_size;
516 arr->num_items = 0;
517
518 return arr->items != NULL;
519}
520
521static int
522growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
523 if (arr->num_items >= arr->size) {
524 size_t new_size = arr->size * 2;
525 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
526 if (!new_items_array) {
527 return 0;
528 }
529 arr->items = new_items_array;
530 arr->size = new_size;
531 }
532
533 arr->items[arr->num_items].lineno = lineno;
534 arr->items[arr->num_items].comment = comment; // Take ownership
535 arr->num_items++;
536 return 1;
537}
538
539static void
540growable_comment_array_deallocate(growable_comment_array *arr) {
541 for (unsigned i = 0; i < arr->num_items; i++) {
542 PyMem_Free(arr->items[i].comment);
543 }
544 PyMem_Free(arr->items);
545}
546
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100547int
548_PyPegen_fill_token(Parser *p)
549{
550 const char *start, *end;
551 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700552
553 // Record and skip '# type: ignore' comments
554 while (type == TYPE_IGNORE) {
555 Py_ssize_t len = end - start;
556 char *tag = PyMem_Malloc(len + 1);
557 if (tag == NULL) {
558 PyErr_NoMemory();
559 return -1;
560 }
561 strncpy(tag, start, len);
562 tag[len] = '\0';
563 // Ownership of tag passes to the growable array
564 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
565 PyErr_NoMemory();
566 return -1;
567 }
568 type = PyTokenizer_Get(p->tok, &start, &end);
569 }
570
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100571 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
572 type = NEWLINE; /* Add an extra newline */
573 p->parsing_started = 0;
574
Pablo Galindob94dbd72020-04-27 18:35:58 +0100575 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100576 p->tok->pendin = -p->tok->indent;
577 p->tok->indent = 0;
578 }
579 }
580 else {
581 p->parsing_started = 1;
582 }
583
584 if (p->fill == p->size) {
585 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300586 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
587 if (new_tokens == NULL) {
588 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100589 return -1;
590 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300591 else {
592 p->tokens = new_tokens;
593 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100594 for (int i = p->size; i < newsize; i++) {
595 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300596 if (p->tokens[i] == NULL) {
597 p->size = i; // Needed, in order to cleanup correctly after parser fails
598 PyErr_NoMemory();
599 return -1;
600 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100601 memset(p->tokens[i], '\0', sizeof(Token));
602 }
603 p->size = newsize;
604 }
605
606 Token *t = p->tokens[p->fill];
607 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
608 t->bytes = PyBytes_FromStringAndSize(start, end - start);
609 if (t->bytes == NULL) {
610 return -1;
611 }
612 PyArena_AddPyObject(p->arena, t->bytes);
613
614 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
615 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100616 int end_lineno = p->tok->lineno;
617 int col_offset = -1, end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100618 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100619 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100620 }
621 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100622 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100623 }
624
625 t->lineno = p->starting_lineno + lineno;
626 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
627 t->end_lineno = p->starting_lineno + end_lineno;
628 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
629
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100630 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300631
632 if (type == ERRORTOKEN) {
633 if (p->tok->done == E_DECODE) {
634 return raise_decode_error(p);
635 }
636 else {
637 return tokenizer_error(p);
638 }
639 }
640
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100641 return 0;
642}
643
644// Instrumentation to count the effectiveness of memoization.
645// The array counts the number of tokens skipped by memoization,
646// indexed by type.
647
648#define NSTATISTICS 2000
649static long memo_statistics[NSTATISTICS];
650
651void
652_PyPegen_clear_memo_statistics()
653{
654 for (int i = 0; i < NSTATISTICS; i++) {
655 memo_statistics[i] = 0;
656 }
657}
658
659PyObject *
660_PyPegen_get_memo_statistics()
661{
662 PyObject *ret = PyList_New(NSTATISTICS);
663 if (ret == NULL) {
664 return NULL;
665 }
666 for (int i = 0; i < NSTATISTICS; i++) {
667 PyObject *value = PyLong_FromLong(memo_statistics[i]);
668 if (value == NULL) {
669 Py_DECREF(ret);
670 return NULL;
671 }
672 // PyList_SetItem borrows a reference to value.
673 if (PyList_SetItem(ret, i, value) < 0) {
674 Py_DECREF(ret);
675 return NULL;
676 }
677 }
678 return ret;
679}
680
681int // bool
682_PyPegen_is_memoized(Parser *p, int type, void *pres)
683{
684 if (p->mark == p->fill) {
685 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300686 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100687 return -1;
688 }
689 }
690
691 Token *t = p->tokens[p->mark];
692
693 for (Memo *m = t->memo; m != NULL; m = m->next) {
694 if (m->type == type) {
695 if (0 <= type && type < NSTATISTICS) {
696 long count = m->mark - p->mark;
697 // A memoized negative result counts for one.
698 if (count <= 0) {
699 count = 1;
700 }
701 memo_statistics[type] += count;
702 }
703 p->mark = m->mark;
704 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100705 return 1;
706 }
707 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100708 return 0;
709}
710
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100711int
712_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
713{
714 int mark = p->mark;
715 void *res = func(p);
716 p->mark = mark;
717 return (res != NULL) == positive;
718}
719
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100720int
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300721_PyPegen_lookahead_with_string(int positive, expr_ty (func)(Parser *, const char*), Parser *p, const char* arg)
722{
723 int mark = p->mark;
724 void *res = func(p, arg);
725 p->mark = mark;
726 return (res != NULL) == positive;
727}
728
729int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100730_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
731{
732 int mark = p->mark;
733 void *res = func(p, arg);
734 p->mark = mark;
735 return (res != NULL) == positive;
736}
737
738int
739_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
740{
741 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100742 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100743 p->mark = mark;
744 return (res != NULL) == positive;
745}
746
747Token *
748_PyPegen_expect_token(Parser *p, int type)
749{
750 if (p->mark == p->fill) {
751 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300752 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100753 return NULL;
754 }
755 }
756 Token *t = p->tokens[p->mark];
757 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100758 return NULL;
759 }
760 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100761 return t;
762}
763
Lysandros Nikolaou1bfe6592020-05-27 23:20:07 +0300764expr_ty
765_PyPegen_expect_soft_keyword(Parser *p, const char *keyword)
766{
767 if (p->mark == p->fill) {
768 if (_PyPegen_fill_token(p) < 0) {
769 p->error_indicator = 1;
770 return NULL;
771 }
772 }
773 Token *t = p->tokens[p->mark];
774 if (t->type != NAME) {
775 return NULL;
776 }
777 char* s = PyBytes_AsString(t->bytes);
778 if (!s) {
779 p->error_indicator = 1;
780 return NULL;
781 }
782 if (strcmp(s, keyword) != 0) {
783 return NULL;
784 }
785 return _PyPegen_name_token(p);
786}
787
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100788Token *
789_PyPegen_get_last_nonnwhitespace_token(Parser *p)
790{
791 assert(p->mark >= 0);
792 Token *token = NULL;
793 for (int m = p->mark - 1; m >= 0; m--) {
794 token = p->tokens[m];
795 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
796 break;
797 }
798 }
799 return token;
800}
801
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100802expr_ty
803_PyPegen_name_token(Parser *p)
804{
805 Token *t = _PyPegen_expect_token(p, NAME);
806 if (t == NULL) {
807 return NULL;
808 }
809 char* s = PyBytes_AsString(t->bytes);
810 if (!s) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300811 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100812 return NULL;
813 }
814 PyObject *id = _PyPegen_new_identifier(p, s);
815 if (id == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300816 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100817 return NULL;
818 }
819 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
820 p->arena);
821}
822
823void *
824_PyPegen_string_token(Parser *p)
825{
826 return _PyPegen_expect_token(p, STRING);
827}
828
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100829static PyObject *
830parsenumber_raw(const char *s)
831{
832 const char *end;
833 long x;
834 double dx;
835 Py_complex compl;
836 int imflag;
837
838 assert(s != NULL);
839 errno = 0;
840 end = s + strlen(s) - 1;
841 imflag = *end == 'j' || *end == 'J';
842 if (s[0] == '0') {
843 x = (long)PyOS_strtoul(s, (char **)&end, 0);
844 if (x < 0 && errno == 0) {
845 return PyLong_FromString(s, (char **)0, 0);
846 }
847 }
848 else
849 x = PyOS_strtol(s, (char **)&end, 0);
850 if (*end == '\0') {
851 if (errno != 0)
852 return PyLong_FromString(s, (char **)0, 0);
853 return PyLong_FromLong(x);
854 }
855 /* XXX Huge floats may silently fail */
856 if (imflag) {
857 compl.real = 0.;
858 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
859 if (compl.imag == -1.0 && PyErr_Occurred())
860 return NULL;
861 return PyComplex_FromCComplex(compl);
862 }
863 else {
864 dx = PyOS_string_to_double(s, NULL, NULL);
865 if (dx == -1.0 && PyErr_Occurred())
866 return NULL;
867 return PyFloat_FromDouble(dx);
868 }
869}
870
871static PyObject *
872parsenumber(const char *s)
873{
874 char *dup, *end;
875 PyObject *res = NULL;
876
877 assert(s != NULL);
878
879 if (strchr(s, '_') == NULL) {
880 return parsenumber_raw(s);
881 }
882 /* Create a duplicate without underscores. */
883 dup = PyMem_Malloc(strlen(s) + 1);
884 if (dup == NULL) {
885 return PyErr_NoMemory();
886 }
887 end = dup;
888 for (; *s; s++) {
889 if (*s != '_') {
890 *end++ = *s;
891 }
892 }
893 *end = '\0';
894 res = parsenumber_raw(dup);
895 PyMem_Free(dup);
896 return res;
897}
898
899expr_ty
900_PyPegen_number_token(Parser *p)
901{
902 Token *t = _PyPegen_expect_token(p, NUMBER);
903 if (t == NULL) {
904 return NULL;
905 }
906
907 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100908 if (num_raw == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300909 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100910 return NULL;
911 }
912
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300913 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
914 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700915 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300916 "in Python 3.6 and greater");
917 }
918
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100919 PyObject *c = parsenumber(num_raw);
920
921 if (c == NULL) {
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300922 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100923 return NULL;
924 }
925
926 if (PyArena_AddPyObject(p->arena, c) < 0) {
927 Py_DECREF(c);
Lysandros Nikolaouc011d1b2020-05-27 23:20:43 +0300928 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100929 return NULL;
930 }
931
932 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
933 p->arena);
934}
935
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300936static int // bool
937newline_in_string(Parser *p, const char *cur)
938{
Miss Islington (bot)15fec562020-06-05 17:13:14 -0700939 for (const char *c = cur; c >= p->tok->buf; c--) {
940 if (*c == '\'' || *c == '"') {
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300941 return 1;
942 }
943 }
944 return 0;
945}
946
947/* Check that the source for a single input statement really is a single
948 statement by looking at what is left in the buffer after parsing.
949 Trailing whitespace and comments are OK. */
950static int // bool
951bad_single_statement(Parser *p)
952{
953 const char *cur = strchr(p->tok->buf, '\n');
954
955 /* Newlines are allowed if preceded by a line continuation character
956 or if they appear inside a string. */
957 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
958 return 0;
959 }
960 char c = *cur;
961
962 for (;;) {
963 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
964 c = *++cur;
965 }
966
967 if (!c) {
968 return 0;
969 }
970
971 if (c != '#') {
972 return 1;
973 }
974
975 /* Suck up comment. */
976 while (c && c != '\n') {
977 c = *++cur;
978 }
979 }
980}
981
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100982void
983_PyPegen_Parser_Free(Parser *p)
984{
985 Py_XDECREF(p->normalize);
986 for (int i = 0; i < p->size; i++) {
987 PyMem_Free(p->tokens[i]);
988 }
989 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700990 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100991 PyMem_Free(p);
992}
993
Pablo Galindo2b74c832020-04-27 18:02:07 +0100994static int
995compute_parser_flags(PyCompilerFlags *flags)
996{
997 int parser_flags = 0;
998 if (!flags) {
999 return 0;
1000 }
1001 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
1002 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1003 }
1004 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
1005 parser_flags |= PyPARSE_IGNORE_COOKIE;
1006 }
1007 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
1008 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1009 }
1010 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
1011 parser_flags |= PyPARSE_TYPE_COMMENTS;
1012 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001013 if (flags->cf_feature_version < 7) {
1014 parser_flags |= PyPARSE_ASYNC_HACKS;
1015 }
Pablo Galindo2b74c832020-04-27 18:02:07 +01001016 return parser_flags;
1017}
1018
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001019Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001020_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001021 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001022{
1023 Parser *p = PyMem_Malloc(sizeof(Parser));
1024 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001025 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001026 }
1027 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001028 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1029 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001030 p->tok = tok;
1031 p->keywords = NULL;
1032 p->n_keyword_lists = -1;
1033 p->tokens = PyMem_Malloc(sizeof(Token *));
1034 if (!p->tokens) {
1035 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001036 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001037 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001038 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001039 if (!p->tokens) {
1040 PyMem_Free(p->tokens);
1041 PyMem_Free(p);
1042 return (Parser *) PyErr_NoMemory();
1043 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001044 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1045 PyMem_Free(p->tokens[0]);
1046 PyMem_Free(p->tokens);
1047 PyMem_Free(p);
1048 return (Parser *) PyErr_NoMemory();
1049 }
1050
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001051 p->mark = 0;
1052 p->fill = 0;
1053 p->size = 1;
1054
1055 p->errcode = errcode;
1056 p->arena = arena;
1057 p->start_rule = start_rule;
1058 p->parsing_started = 0;
1059 p->normalize = NULL;
1060 p->error_indicator = 0;
1061
1062 p->starting_lineno = 0;
1063 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001064 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001065 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001066 p->known_err_token = NULL;
Miss Islington (bot)82da2c32020-05-25 10:58:03 -07001067 p->level = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001068
1069 return p;
1070}
1071
1072void *
1073_PyPegen_run_parser(Parser *p)
1074{
1075 void *res = _PyPegen_parse(p);
1076 if (res == NULL) {
1077 if (PyErr_Occurred()) {
1078 return NULL;
1079 }
1080 if (p->fill == 0) {
1081 RAISE_SYNTAX_ERROR("error at start before reading any input");
1082 }
1083 else if (p->tok->done == E_EOF) {
1084 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1085 }
1086 else {
1087 if (p->tokens[p->fill-1]->type == INDENT) {
1088 RAISE_INDENTATION_ERROR("unexpected indent");
1089 }
1090 else if (p->tokens[p->fill-1]->type == DEDENT) {
1091 RAISE_INDENTATION_ERROR("unexpected unindent");
1092 }
1093 else {
1094 RAISE_SYNTAX_ERROR("invalid syntax");
1095 }
1096 }
1097 return NULL;
1098 }
1099
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001100 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1101 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1102 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1103 }
1104
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001105 return res;
1106}
1107
1108mod_ty
1109_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1110 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001111 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001112{
1113 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1114 if (tok == NULL) {
1115 if (PyErr_Occurred()) {
1116 raise_tokenizer_init_error(filename_ob);
1117 return NULL;
1118 }
1119 return NULL;
1120 }
1121 // This transfers the ownership to the tokenizer
1122 tok->filename = filename_ob;
1123 Py_INCREF(filename_ob);
1124
1125 // From here on we need to clean up even if there's an error
1126 mod_ty result = NULL;
1127
Pablo Galindo2b74c832020-04-27 18:02:07 +01001128 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001129 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1130 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001131 if (p == NULL) {
1132 goto error;
1133 }
1134
1135 result = _PyPegen_run_parser(p);
1136 _PyPegen_Parser_Free(p);
1137
1138error:
1139 PyTokenizer_Free(tok);
1140 return result;
1141}
1142
1143mod_ty
1144_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001145 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001146{
1147 FILE *fp = fopen(filename, "rb");
1148 if (fp == NULL) {
1149 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1150 return NULL;
1151 }
1152
1153 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001154 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001155
1156 fclose(fp);
1157 return result;
1158}
1159
1160mod_ty
1161_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001162 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001163{
1164 int exec_input = start_rule == Py_file_input;
1165
1166 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001167 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001168 tok = PyTokenizer_FromUTF8(str, exec_input);
1169 } else {
1170 tok = PyTokenizer_FromString(str, exec_input);
1171 }
1172 if (tok == NULL) {
1173 if (PyErr_Occurred()) {
1174 raise_tokenizer_init_error(filename_ob);
1175 }
1176 return NULL;
1177 }
1178 // This transfers the ownership to the tokenizer
1179 tok->filename = filename_ob;
1180 Py_INCREF(filename_ob);
1181
1182 // We need to clear up from here on
1183 mod_ty result = NULL;
1184
Pablo Galindo2b74c832020-04-27 18:02:07 +01001185 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001186 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001187 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1188 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001189 if (p == NULL) {
1190 goto error;
1191 }
1192
1193 result = _PyPegen_run_parser(p);
1194 _PyPegen_Parser_Free(p);
1195
1196error:
1197 PyTokenizer_Free(tok);
1198 return result;
1199}
1200
1201void *
1202_PyPegen_interactive_exit(Parser *p)
1203{
1204 if (p->errcode) {
1205 *(p->errcode) = E_EOF;
1206 }
1207 return NULL;
1208}
1209
1210/* Creates a single-element asdl_seq* that contains a */
1211asdl_seq *
1212_PyPegen_singleton_seq(Parser *p, void *a)
1213{
1214 assert(a != NULL);
1215 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1216 if (!seq) {
1217 return NULL;
1218 }
1219 asdl_seq_SET(seq, 0, a);
1220 return seq;
1221}
1222
1223/* Creates a copy of seq and prepends a to it */
1224asdl_seq *
1225_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1226{
1227 assert(a != NULL);
1228 if (!seq) {
1229 return _PyPegen_singleton_seq(p, a);
1230 }
1231
1232 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1233 if (!new_seq) {
1234 return NULL;
1235 }
1236
1237 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001238 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001239 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1240 }
1241 return new_seq;
1242}
1243
Guido van Rossumc001c092020-04-30 12:12:19 -07001244/* Creates a copy of seq and appends a to it */
1245asdl_seq *
1246_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
1247{
1248 assert(a != NULL);
1249 if (!seq) {
1250 return _PyPegen_singleton_seq(p, a);
1251 }
1252
1253 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1254 if (!new_seq) {
1255 return NULL;
1256 }
1257
1258 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1259 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1260 }
1261 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1262 return new_seq;
1263}
1264
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001265static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001266_get_flattened_seq_size(asdl_seq *seqs)
1267{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001268 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001269 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1270 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1271 size += asdl_seq_LEN(inner_seq);
1272 }
1273 return size;
1274}
1275
1276/* Flattens an asdl_seq* of asdl_seq*s */
1277asdl_seq *
1278_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1279{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001280 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001281 assert(flattened_seq_size > 0);
1282
1283 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1284 if (!flattened_seq) {
1285 return NULL;
1286 }
1287
1288 int flattened_seq_idx = 0;
1289 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1290 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001291 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001292 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1293 }
1294 }
1295 assert(flattened_seq_idx == flattened_seq_size);
1296
1297 return flattened_seq;
1298}
1299
1300/* Creates a new name of the form <first_name>.<second_name> */
1301expr_ty
1302_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1303{
1304 assert(first_name != NULL && second_name != NULL);
1305 PyObject *first_identifier = first_name->v.Name.id;
1306 PyObject *second_identifier = second_name->v.Name.id;
1307
1308 if (PyUnicode_READY(first_identifier) == -1) {
1309 return NULL;
1310 }
1311 if (PyUnicode_READY(second_identifier) == -1) {
1312 return NULL;
1313 }
1314 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1315 if (!first_str) {
1316 return NULL;
1317 }
1318 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1319 if (!second_str) {
1320 return NULL;
1321 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001322 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001323
1324 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1325 if (!str) {
1326 return NULL;
1327 }
1328
1329 char *s = PyBytes_AS_STRING(str);
1330 if (!s) {
1331 return NULL;
1332 }
1333
1334 strcpy(s, first_str);
1335 s += strlen(first_str);
1336 *s++ = '.';
1337 strcpy(s, second_str);
1338 s += strlen(second_str);
1339 *s = '\0';
1340
1341 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1342 Py_DECREF(str);
1343 if (!uni) {
1344 return NULL;
1345 }
1346 PyUnicode_InternInPlace(&uni);
1347 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1348 Py_DECREF(uni);
1349 return NULL;
1350 }
1351
1352 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1353}
1354
1355/* Counts the total number of dots in seq's tokens */
1356int
1357_PyPegen_seq_count_dots(asdl_seq *seq)
1358{
1359 int number_of_dots = 0;
1360 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1361 Token *current_expr = asdl_seq_GET(seq, i);
1362 switch (current_expr->type) {
1363 case ELLIPSIS:
1364 number_of_dots += 3;
1365 break;
1366 case DOT:
1367 number_of_dots += 1;
1368 break;
1369 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001370 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001371 }
1372 }
1373
1374 return number_of_dots;
1375}
1376
1377/* Creates an alias with '*' as the identifier name */
1378alias_ty
1379_PyPegen_alias_for_star(Parser *p)
1380{
1381 PyObject *str = PyUnicode_InternFromString("*");
1382 if (!str) {
1383 return NULL;
1384 }
1385 if (PyArena_AddPyObject(p->arena, str) < 0) {
1386 Py_DECREF(str);
1387 return NULL;
1388 }
1389 return alias(str, NULL, p->arena);
1390}
1391
1392/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1393asdl_seq *
1394_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1395{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001396 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001397 assert(len > 0);
1398
1399 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1400 if (!new_seq) {
1401 return NULL;
1402 }
1403 for (Py_ssize_t i = 0; i < len; i++) {
1404 expr_ty e = asdl_seq_GET(seq, i);
1405 asdl_seq_SET(new_seq, i, e->v.Name.id);
1406 }
1407 return new_seq;
1408}
1409
1410/* Constructs a CmpopExprPair */
1411CmpopExprPair *
1412_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1413{
1414 assert(expr != NULL);
1415 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1416 if (!a) {
1417 return NULL;
1418 }
1419 a->cmpop = cmpop;
1420 a->expr = expr;
1421 return a;
1422}
1423
1424asdl_int_seq *
1425_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1426{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001427 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001428 assert(len > 0);
1429
1430 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1431 if (!new_seq) {
1432 return NULL;
1433 }
1434 for (Py_ssize_t i = 0; i < len; i++) {
1435 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1436 asdl_seq_SET(new_seq, i, pair->cmpop);
1437 }
1438 return new_seq;
1439}
1440
1441asdl_seq *
1442_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1443{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001444 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001445 assert(len > 0);
1446
1447 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1448 if (!new_seq) {
1449 return NULL;
1450 }
1451 for (Py_ssize_t i = 0; i < len; i++) {
1452 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1453 asdl_seq_SET(new_seq, i, pair->expr);
1454 }
1455 return new_seq;
1456}
1457
1458/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1459static asdl_seq *
1460_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1461{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001462 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001463 if (len == 0) {
1464 return NULL;
1465 }
1466
1467 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1468 if (!new_seq) {
1469 return NULL;
1470 }
1471 for (Py_ssize_t i = 0; i < len; i++) {
1472 expr_ty e = asdl_seq_GET(seq, i);
1473 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1474 }
1475 return new_seq;
1476}
1477
1478static expr_ty
1479_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1480{
1481 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1482}
1483
1484static expr_ty
1485_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1486{
1487 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1488}
1489
1490static expr_ty
1491_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1492{
1493 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1494}
1495
1496static expr_ty
1497_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1498{
1499 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1500}
1501
1502static expr_ty
1503_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1504{
1505 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1506}
1507
1508static expr_ty
1509_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1510{
1511 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1512}
1513
1514/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1515expr_ty
1516_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1517{
1518 assert(expr != NULL);
1519
1520 expr_ty new = NULL;
1521 switch (expr->kind) {
1522 case Name_kind:
1523 new = _set_name_context(p, expr, ctx);
1524 break;
1525 case Tuple_kind:
1526 new = _set_tuple_context(p, expr, ctx);
1527 break;
1528 case List_kind:
1529 new = _set_list_context(p, expr, ctx);
1530 break;
1531 case Subscript_kind:
1532 new = _set_subscript_context(p, expr, ctx);
1533 break;
1534 case Attribute_kind:
1535 new = _set_attribute_context(p, expr, ctx);
1536 break;
1537 case Starred_kind:
1538 new = _set_starred_context(p, expr, ctx);
1539 break;
1540 default:
1541 new = expr;
1542 }
1543 return new;
1544}
1545
1546/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1547KeyValuePair *
1548_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1549{
1550 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1551 if (!a) {
1552 return NULL;
1553 }
1554 a->key = key;
1555 a->value = value;
1556 return a;
1557}
1558
1559/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1560asdl_seq *
1561_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1562{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001563 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001564 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1565 if (!new_seq) {
1566 return NULL;
1567 }
1568 for (Py_ssize_t i = 0; i < len; i++) {
1569 KeyValuePair *pair = asdl_seq_GET(seq, i);
1570 asdl_seq_SET(new_seq, i, pair->key);
1571 }
1572 return new_seq;
1573}
1574
1575/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1576asdl_seq *
1577_PyPegen_get_values(Parser *p, asdl_seq *seq)
1578{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001579 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001580 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1581 if (!new_seq) {
1582 return NULL;
1583 }
1584 for (Py_ssize_t i = 0; i < len; i++) {
1585 KeyValuePair *pair = asdl_seq_GET(seq, i);
1586 asdl_seq_SET(new_seq, i, pair->value);
1587 }
1588 return new_seq;
1589}
1590
1591/* Constructs a NameDefaultPair */
1592NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001593_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001594{
1595 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1596 if (!a) {
1597 return NULL;
1598 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001599 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001600 a->value = value;
1601 return a;
1602}
1603
1604/* Constructs a SlashWithDefault */
1605SlashWithDefault *
1606_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1607{
1608 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1609 if (!a) {
1610 return NULL;
1611 }
1612 a->plain_names = plain_names;
1613 a->names_with_defaults = names_with_defaults;
1614 return a;
1615}
1616
1617/* Constructs a StarEtc */
1618StarEtc *
1619_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1620{
1621 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1622 if (!a) {
1623 return NULL;
1624 }
1625 a->vararg = vararg;
1626 a->kwonlyargs = kwonlyargs;
1627 a->kwarg = kwarg;
1628 return a;
1629}
1630
1631asdl_seq *
1632_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1633{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001634 Py_ssize_t first_len = asdl_seq_LEN(a);
1635 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001636 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1637 if (!new_seq) {
1638 return NULL;
1639 }
1640
1641 int k = 0;
1642 for (Py_ssize_t i = 0; i < first_len; i++) {
1643 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1644 }
1645 for (Py_ssize_t i = 0; i < second_len; i++) {
1646 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1647 }
1648
1649 return new_seq;
1650}
1651
1652static asdl_seq *
1653_get_names(Parser *p, asdl_seq *names_with_defaults)
1654{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001655 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001656 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1657 if (!seq) {
1658 return NULL;
1659 }
1660 for (Py_ssize_t i = 0; i < len; i++) {
1661 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1662 asdl_seq_SET(seq, i, pair->arg);
1663 }
1664 return seq;
1665}
1666
1667static asdl_seq *
1668_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1669{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001670 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001671 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1672 if (!seq) {
1673 return NULL;
1674 }
1675 for (Py_ssize_t i = 0; i < len; i++) {
1676 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1677 asdl_seq_SET(seq, i, pair->value);
1678 }
1679 return seq;
1680}
1681
1682/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1683arguments_ty
1684_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1685 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1686 asdl_seq *names_with_default, StarEtc *star_etc)
1687{
1688 asdl_seq *posonlyargs;
1689 if (slash_without_default != NULL) {
1690 posonlyargs = slash_without_default;
1691 }
1692 else if (slash_with_default != NULL) {
1693 asdl_seq *slash_with_default_names =
1694 _get_names(p, slash_with_default->names_with_defaults);
1695 if (!slash_with_default_names) {
1696 return NULL;
1697 }
1698 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1699 if (!posonlyargs) {
1700 return NULL;
1701 }
1702 }
1703 else {
1704 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1705 if (!posonlyargs) {
1706 return NULL;
1707 }
1708 }
1709
1710 asdl_seq *posargs;
1711 if (plain_names != NULL && names_with_default != NULL) {
1712 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1713 if (!names_with_default_names) {
1714 return NULL;
1715 }
1716 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1717 if (!posargs) {
1718 return NULL;
1719 }
1720 }
1721 else if (plain_names == NULL && names_with_default != NULL) {
1722 posargs = _get_names(p, names_with_default);
1723 if (!posargs) {
1724 return NULL;
1725 }
1726 }
1727 else if (plain_names != NULL && names_with_default == NULL) {
1728 posargs = plain_names;
1729 }
1730 else {
1731 posargs = _Py_asdl_seq_new(0, p->arena);
1732 if (!posargs) {
1733 return NULL;
1734 }
1735 }
1736
1737 asdl_seq *posdefaults;
1738 if (slash_with_default != NULL && names_with_default != NULL) {
1739 asdl_seq *slash_with_default_values =
1740 _get_defaults(p, slash_with_default->names_with_defaults);
1741 if (!slash_with_default_values) {
1742 return NULL;
1743 }
1744 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1745 if (!names_with_default_values) {
1746 return NULL;
1747 }
1748 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1749 if (!posdefaults) {
1750 return NULL;
1751 }
1752 }
1753 else if (slash_with_default == NULL && names_with_default != NULL) {
1754 posdefaults = _get_defaults(p, names_with_default);
1755 if (!posdefaults) {
1756 return NULL;
1757 }
1758 }
1759 else if (slash_with_default != NULL && names_with_default == NULL) {
1760 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1761 if (!posdefaults) {
1762 return NULL;
1763 }
1764 }
1765 else {
1766 posdefaults = _Py_asdl_seq_new(0, p->arena);
1767 if (!posdefaults) {
1768 return NULL;
1769 }
1770 }
1771
1772 arg_ty vararg = NULL;
1773 if (star_etc != NULL && star_etc->vararg != NULL) {
1774 vararg = star_etc->vararg;
1775 }
1776
1777 asdl_seq *kwonlyargs;
1778 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1779 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1780 if (!kwonlyargs) {
1781 return NULL;
1782 }
1783 }
1784 else {
1785 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1786 if (!kwonlyargs) {
1787 return NULL;
1788 }
1789 }
1790
1791 asdl_seq *kwdefaults;
1792 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1793 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1794 if (!kwdefaults) {
1795 return NULL;
1796 }
1797 }
1798 else {
1799 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1800 if (!kwdefaults) {
1801 return NULL;
1802 }
1803 }
1804
1805 arg_ty kwarg = NULL;
1806 if (star_etc != NULL && star_etc->kwarg != NULL) {
1807 kwarg = star_etc->kwarg;
1808 }
1809
1810 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1811 posdefaults, p->arena);
1812}
1813
1814/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1815 * arguments. */
1816arguments_ty
1817_PyPegen_empty_arguments(Parser *p)
1818{
1819 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1820 if (!posonlyargs) {
1821 return NULL;
1822 }
1823 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1824 if (!posargs) {
1825 return NULL;
1826 }
1827 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1828 if (!posdefaults) {
1829 return NULL;
1830 }
1831 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1832 if (!kwonlyargs) {
1833 return NULL;
1834 }
1835 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1836 if (!kwdefaults) {
1837 return NULL;
1838 }
1839
1840 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1841 p->arena);
1842}
1843
1844/* Encapsulates the value of an operator_ty into an AugOperator struct */
1845AugOperator *
1846_PyPegen_augoperator(Parser *p, operator_ty kind)
1847{
1848 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1849 if (!a) {
1850 return NULL;
1851 }
1852 a->kind = kind;
1853 return a;
1854}
1855
1856/* Construct a FunctionDef equivalent to function_def, but with decorators */
1857stmt_ty
1858_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1859{
1860 assert(function_def != NULL);
1861 if (function_def->kind == AsyncFunctionDef_kind) {
1862 return _Py_AsyncFunctionDef(
1863 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1864 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1865 function_def->v.FunctionDef.type_comment, function_def->lineno,
1866 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1867 p->arena);
1868 }
1869
1870 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1871 function_def->v.FunctionDef.body, decorators,
1872 function_def->v.FunctionDef.returns,
1873 function_def->v.FunctionDef.type_comment, function_def->lineno,
1874 function_def->col_offset, function_def->end_lineno,
1875 function_def->end_col_offset, p->arena);
1876}
1877
1878/* Construct a ClassDef equivalent to class_def, but with decorators */
1879stmt_ty
1880_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1881{
1882 assert(class_def != NULL);
1883 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1884 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1885 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1886 class_def->end_col_offset, p->arena);
1887}
1888
1889/* Construct a KeywordOrStarred */
1890KeywordOrStarred *
1891_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1892{
1893 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1894 if (!a) {
1895 return NULL;
1896 }
1897 a->element = element;
1898 a->is_keyword = is_keyword;
1899 return a;
1900}
1901
1902/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1903static int
1904_seq_number_of_starred_exprs(asdl_seq *seq)
1905{
1906 int n = 0;
1907 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1908 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1909 if (!k->is_keyword) {
1910 n++;
1911 }
1912 }
1913 return n;
1914}
1915
1916/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1917asdl_seq *
1918_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1919{
1920 int new_len = _seq_number_of_starred_exprs(kwargs);
1921 if (new_len == 0) {
1922 return NULL;
1923 }
1924 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1925 if (!new_seq) {
1926 return NULL;
1927 }
1928
1929 int idx = 0;
1930 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1931 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1932 if (!k->is_keyword) {
1933 asdl_seq_SET(new_seq, idx++, k->element);
1934 }
1935 }
1936 return new_seq;
1937}
1938
1939/* Return a new asdl_seq* with only the keywords in kwargs */
1940asdl_seq *
1941_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1942{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001943 Py_ssize_t len = asdl_seq_LEN(kwargs);
1944 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001945 if (new_len == 0) {
1946 return NULL;
1947 }
1948 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1949 if (!new_seq) {
1950 return NULL;
1951 }
1952
1953 int idx = 0;
1954 for (Py_ssize_t i = 0; i < len; i++) {
1955 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1956 if (k->is_keyword) {
1957 asdl_seq_SET(new_seq, idx++, k->element);
1958 }
1959 }
1960 return new_seq;
1961}
1962
1963expr_ty
1964_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1965{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001966 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001967 assert(len > 0);
1968
1969 Token *first = asdl_seq_GET(strings, 0);
1970 Token *last = asdl_seq_GET(strings, len - 1);
1971
1972 int bytesmode = 0;
1973 PyObject *bytes_str = NULL;
1974
1975 FstringParser state;
1976 _PyPegen_FstringParser_Init(&state);
1977
1978 for (Py_ssize_t i = 0; i < len; i++) {
1979 Token *t = asdl_seq_GET(strings, i);
1980
1981 int this_bytesmode;
1982 int this_rawmode;
1983 PyObject *s;
1984 const char *fstr;
1985 Py_ssize_t fstrlen = -1;
1986
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001987 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001988 goto error;
1989 }
1990
1991 /* Check that we are not mixing bytes with unicode. */
1992 if (i != 0 && bytesmode != this_bytesmode) {
1993 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1994 Py_XDECREF(s);
1995 goto error;
1996 }
1997 bytesmode = this_bytesmode;
1998
1999 if (fstr != NULL) {
2000 assert(s == NULL && !bytesmode);
2001
2002 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
2003 this_rawmode, 0, first, t, last);
2004 if (result < 0) {
2005 goto error;
2006 }
2007 }
2008 else {
2009 /* String or byte string. */
2010 assert(s != NULL && fstr == NULL);
2011 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
2012
2013 if (bytesmode) {
2014 if (i == 0) {
2015 bytes_str = s;
2016 }
2017 else {
2018 PyBytes_ConcatAndDel(&bytes_str, s);
2019 if (!bytes_str) {
2020 goto error;
2021 }
2022 }
2023 }
2024 else {
2025 /* This is a regular string. Concatenate it. */
2026 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2027 goto error;
2028 }
2029 }
2030 }
2031 }
2032
2033 if (bytesmode) {
2034 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2035 goto error;
2036 }
2037 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2038 last->end_col_offset, p->arena);
2039 }
2040
2041 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2042
2043error:
2044 Py_XDECREF(bytes_str);
2045 _PyPegen_FstringParser_Dealloc(&state);
2046 if (PyErr_Occurred()) {
2047 raise_decode_error(p);
2048 }
2049 return NULL;
2050}
Guido van Rossumc001c092020-04-30 12:12:19 -07002051
2052mod_ty
2053_PyPegen_make_module(Parser *p, asdl_seq *a) {
2054 asdl_seq *type_ignores = NULL;
2055 Py_ssize_t num = p->type_ignore_comments.num_items;
2056 if (num > 0) {
2057 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2058 type_ignores = _Py_asdl_seq_new(num, p->arena);
2059 if (type_ignores == NULL) {
2060 return NULL;
2061 }
2062 for (int i = 0; i < num; i++) {
2063 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2064 if (tag == NULL) {
2065 return NULL;
2066 }
2067 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2068 if (ti == NULL) {
2069 return NULL;
2070 }
2071 asdl_seq_SET(type_ignores, i, ti);
2072 }
2073 }
2074 return Module(a, type_ignores, p->arena);
2075}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002076
2077// Error reporting helpers
2078
2079expr_ty
2080_PyPegen_get_invalid_target(expr_ty e)
2081{
2082 if (e == NULL) {
2083 return NULL;
2084 }
2085
2086#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2087 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2088 for (Py_ssize_t i = 0; i < len; i++) {\
2089 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2090 expr_ty child = _PyPegen_get_invalid_target(other);\
2091 if (child != NULL) {\
2092 return child;\
2093 }\
2094 }\
2095 } while (0)
2096
2097 // We only need to visit List and Tuple nodes recursively as those
2098 // are the only ones that can contain valid names in targets when
2099 // they are parsed as expressions. Any other kind of expression
2100 // that is a container (like Sets or Dicts) is directly invalid and
2101 // we don't need to visit it recursively.
2102
2103 switch (e->kind) {
2104 case List_kind: {
2105 VISIT_CONTAINER(e, List);
2106 return NULL;
2107 }
2108 case Tuple_kind: {
2109 VISIT_CONTAINER(e, Tuple);
2110 return NULL;
2111 }
2112 case Starred_kind:
2113 return _PyPegen_get_invalid_target(e->v.Starred.value);
2114 case Name_kind:
2115 case Subscript_kind:
2116 case Attribute_kind:
2117 return NULL;
2118 default:
2119 return e;
2120 }
Lysandros Nikolaou75b863a2020-05-18 22:14:47 +03002121}
2122
2123void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
2124 int kwarg_unpacking = 0;
2125 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
2126 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
2127 if (!keyword->arg) {
2128 kwarg_unpacking = 1;
2129 }
2130 }
2131
2132 const char *msg = NULL;
2133 if (kwarg_unpacking) {
2134 msg = "positional argument follows keyword argument unpacking";
2135 } else {
2136 msg = "positional argument follows keyword argument";
2137 }
2138
2139 return RAISE_SYNTAX_ERROR(msg);
2140}
Miss Islington (bot)55c89232020-05-21 18:14:55 -07002141
2142void *
2143_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args)
2144{
2145 /* The rule that calls this function is 'args for_if_clauses'.
2146 For the input f(L, x for x in y), L and x are in args and
2147 the for is parsed as a for_if_clause. We have to check if
2148 len <= 1, so that input like dict((a, b) for a, b in x)
2149 gets successfully parsed and then we pass the last
2150 argument (x in the above example) as the location of the
2151 error */
2152 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
2153 if (len <= 1) {
2154 return NULL;
2155 }
2156
2157 return RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
2158 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
2159 "Generator expression must be parenthesized"
2160 );
2161}