blob: 7f3e4561de60557a7b6171e224f3e76b2b327412 [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
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300411 int col_number = byte_offset_to_character_offset(error_line, col_offset);
412
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
434void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
435 int kwarg_unpacking = 0;
436 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
437 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
438 if (!keyword->arg) {
439 kwarg_unpacking = 1;
440 }
441 }
442
443 const char *msg = NULL;
444 if (kwarg_unpacking) {
445 msg = "positional argument follows keyword argument unpacking";
446 } else {
447 msg = "positional argument follows keyword argument";
448 }
449
450 return RAISE_SYNTAX_ERROR(msg);
451}
452
453#if 0
454static const char *
455token_name(int type)
456{
457 if (0 <= type && type <= N_TOKENS) {
458 return _PyParser_TokenNames[type];
459 }
460 return "<Huh?>";
461}
462#endif
463
464// Here, mark is the start of the node, while p->mark is the end.
465// If node==NULL, they should be the same.
466int
467_PyPegen_insert_memo(Parser *p, int mark, int type, void *node)
468{
469 // Insert in front
470 Memo *m = PyArena_Malloc(p->arena, sizeof(Memo));
471 if (m == NULL) {
472 return -1;
473 }
474 m->type = type;
475 m->node = node;
476 m->mark = p->mark;
477 m->next = p->tokens[mark]->memo;
478 p->tokens[mark]->memo = m;
479 return 0;
480}
481
482// Like _PyPegen_insert_memo(), but updates an existing node if found.
483int
484_PyPegen_update_memo(Parser *p, int mark, int type, void *node)
485{
486 for (Memo *m = p->tokens[mark]->memo; m != NULL; m = m->next) {
487 if (m->type == type) {
488 // Update existing node.
489 m->node = node;
490 m->mark = p->mark;
491 return 0;
492 }
493 }
494 // Insert new node.
495 return _PyPegen_insert_memo(p, mark, type, node);
496}
497
498// Return dummy NAME.
499void *
500_PyPegen_dummy_name(Parser *p, ...)
501{
502 static void *cache = NULL;
503
504 if (cache != NULL) {
505 return cache;
506 }
507
508 PyObject *id = _create_dummy_identifier(p);
509 if (!id) {
510 return NULL;
511 }
512 cache = Name(id, Load, 1, 0, 1, 0, p->arena);
513 return cache;
514}
515
516static int
517_get_keyword_or_name_type(Parser *p, const char *name, int name_len)
518{
519 if (name_len >= p->n_keyword_lists || p->keywords[name_len] == NULL) {
520 return NAME;
521 }
522 for (KeywordToken *k = p->keywords[name_len]; k->type != -1; k++) {
523 if (strncmp(k->str, name, name_len) == 0) {
524 return k->type;
525 }
526 }
527 return NAME;
528}
529
Guido van Rossumc001c092020-04-30 12:12:19 -0700530static int
531growable_comment_array_init(growable_comment_array *arr, size_t initial_size) {
532 assert(initial_size > 0);
533 arr->items = PyMem_Malloc(initial_size * sizeof(*arr->items));
534 arr->size = initial_size;
535 arr->num_items = 0;
536
537 return arr->items != NULL;
538}
539
540static int
541growable_comment_array_add(growable_comment_array *arr, int lineno, char *comment) {
542 if (arr->num_items >= arr->size) {
543 size_t new_size = arr->size * 2;
544 void *new_items_array = PyMem_Realloc(arr->items, new_size * sizeof(*arr->items));
545 if (!new_items_array) {
546 return 0;
547 }
548 arr->items = new_items_array;
549 arr->size = new_size;
550 }
551
552 arr->items[arr->num_items].lineno = lineno;
553 arr->items[arr->num_items].comment = comment; // Take ownership
554 arr->num_items++;
555 return 1;
556}
557
558static void
559growable_comment_array_deallocate(growable_comment_array *arr) {
560 for (unsigned i = 0; i < arr->num_items; i++) {
561 PyMem_Free(arr->items[i].comment);
562 }
563 PyMem_Free(arr->items);
564}
565
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100566int
567_PyPegen_fill_token(Parser *p)
568{
569 const char *start, *end;
570 int type = PyTokenizer_Get(p->tok, &start, &end);
Guido van Rossumc001c092020-04-30 12:12:19 -0700571
572 // Record and skip '# type: ignore' comments
573 while (type == TYPE_IGNORE) {
574 Py_ssize_t len = end - start;
575 char *tag = PyMem_Malloc(len + 1);
576 if (tag == NULL) {
577 PyErr_NoMemory();
578 return -1;
579 }
580 strncpy(tag, start, len);
581 tag[len] = '\0';
582 // Ownership of tag passes to the growable array
583 if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
584 PyErr_NoMemory();
585 return -1;
586 }
587 type = PyTokenizer_Get(p->tok, &start, &end);
588 }
589
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100590 if (type == ENDMARKER && p->start_rule == Py_single_input && p->parsing_started) {
591 type = NEWLINE; /* Add an extra newline */
592 p->parsing_started = 0;
593
Pablo Galindob94dbd72020-04-27 18:35:58 +0100594 if (p->tok->indent && !(p->flags & PyPARSE_DONT_IMPLY_DEDENT)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100595 p->tok->pendin = -p->tok->indent;
596 p->tok->indent = 0;
597 }
598 }
599 else {
600 p->parsing_started = 1;
601 }
602
603 if (p->fill == p->size) {
604 int newsize = p->size * 2;
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300605 Token **new_tokens = PyMem_Realloc(p->tokens, newsize * sizeof(Token *));
606 if (new_tokens == NULL) {
607 PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100608 return -1;
609 }
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300610 else {
611 p->tokens = new_tokens;
612 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100613 for (int i = p->size; i < newsize; i++) {
614 p->tokens[i] = PyMem_Malloc(sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300615 if (p->tokens[i] == NULL) {
616 p->size = i; // Needed, in order to cleanup correctly after parser fails
617 PyErr_NoMemory();
618 return -1;
619 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100620 memset(p->tokens[i], '\0', sizeof(Token));
621 }
622 p->size = newsize;
623 }
624
625 Token *t = p->tokens[p->fill];
626 t->type = (type == NAME) ? _get_keyword_or_name_type(p, start, (int)(end - start)) : type;
627 t->bytes = PyBytes_FromStringAndSize(start, end - start);
628 if (t->bytes == NULL) {
629 return -1;
630 }
631 PyArena_AddPyObject(p->arena, t->bytes);
632
633 int lineno = type == STRING ? p->tok->first_lineno : p->tok->lineno;
634 const char *line_start = type == STRING ? p->tok->multi_line_start : p->tok->line_start;
Pablo Galindo22081342020-04-29 02:04:06 +0100635 int end_lineno = p->tok->lineno;
636 int col_offset = -1, end_col_offset = -1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100637 if (start != NULL && start >= line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100638 col_offset = (int)(start - line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100639 }
640 if (end != NULL && end >= p->tok->line_start) {
Pablo Galindo22081342020-04-29 02:04:06 +0100641 end_col_offset = (int)(end - p->tok->line_start);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100642 }
643
644 t->lineno = p->starting_lineno + lineno;
645 t->col_offset = p->tok->lineno == 1 ? p->starting_col_offset + col_offset : col_offset;
646 t->end_lineno = p->starting_lineno + end_lineno;
647 t->end_col_offset = p->tok->lineno == 1 ? p->starting_col_offset + end_col_offset : end_col_offset;
648
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100649 p->fill += 1;
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300650
651 if (type == ERRORTOKEN) {
652 if (p->tok->done == E_DECODE) {
653 return raise_decode_error(p);
654 }
655 else {
656 return tokenizer_error(p);
657 }
658 }
659
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100660 return 0;
661}
662
663// Instrumentation to count the effectiveness of memoization.
664// The array counts the number of tokens skipped by memoization,
665// indexed by type.
666
667#define NSTATISTICS 2000
668static long memo_statistics[NSTATISTICS];
669
670void
671_PyPegen_clear_memo_statistics()
672{
673 for (int i = 0; i < NSTATISTICS; i++) {
674 memo_statistics[i] = 0;
675 }
676}
677
678PyObject *
679_PyPegen_get_memo_statistics()
680{
681 PyObject *ret = PyList_New(NSTATISTICS);
682 if (ret == NULL) {
683 return NULL;
684 }
685 for (int i = 0; i < NSTATISTICS; i++) {
686 PyObject *value = PyLong_FromLong(memo_statistics[i]);
687 if (value == NULL) {
688 Py_DECREF(ret);
689 return NULL;
690 }
691 // PyList_SetItem borrows a reference to value.
692 if (PyList_SetItem(ret, i, value) < 0) {
693 Py_DECREF(ret);
694 return NULL;
695 }
696 }
697 return ret;
698}
699
700int // bool
701_PyPegen_is_memoized(Parser *p, int type, void *pres)
702{
703 if (p->mark == p->fill) {
704 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300705 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100706 return -1;
707 }
708 }
709
710 Token *t = p->tokens[p->mark];
711
712 for (Memo *m = t->memo; m != NULL; m = m->next) {
713 if (m->type == type) {
714 if (0 <= type && type < NSTATISTICS) {
715 long count = m->mark - p->mark;
716 // A memoized negative result counts for one.
717 if (count <= 0) {
718 count = 1;
719 }
720 memo_statistics[type] += count;
721 }
722 p->mark = m->mark;
723 *(void **)(pres) = m->node;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100724 return 1;
725 }
726 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100727 return 0;
728}
729
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100730
731int
732_PyPegen_lookahead_with_name(int positive, expr_ty (func)(Parser *), Parser *p)
733{
734 int mark = p->mark;
735 void *res = func(p);
736 p->mark = mark;
737 return (res != NULL) == positive;
738}
739
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100740int
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100741_PyPegen_lookahead_with_int(int positive, Token *(func)(Parser *, int), Parser *p, int arg)
742{
743 int mark = p->mark;
744 void *res = func(p, arg);
745 p->mark = mark;
746 return (res != NULL) == positive;
747}
748
749int
750_PyPegen_lookahead(int positive, void *(func)(Parser *), Parser *p)
751{
752 int mark = p->mark;
Pablo Galindo1df5a9e2020-04-23 12:42:13 +0100753 void *res = (void*)func(p);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100754 p->mark = mark;
755 return (res != NULL) == positive;
756}
757
758Token *
759_PyPegen_expect_token(Parser *p, int type)
760{
761 if (p->mark == p->fill) {
762 if (_PyPegen_fill_token(p) < 0) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +0300763 p->error_indicator = 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100764 return NULL;
765 }
766 }
767 Token *t = p->tokens[p->mark];
768 if (t->type != type) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100769 return NULL;
770 }
771 p->mark += 1;
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100772 return t;
773}
774
775Token *
776_PyPegen_get_last_nonnwhitespace_token(Parser *p)
777{
778 assert(p->mark >= 0);
779 Token *token = NULL;
780 for (int m = p->mark - 1; m >= 0; m--) {
781 token = p->tokens[m];
782 if (token->type != ENDMARKER && (token->type < NEWLINE || token->type > DEDENT)) {
783 break;
784 }
785 }
786 return token;
787}
788
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100789expr_ty
790_PyPegen_name_token(Parser *p)
791{
792 Token *t = _PyPegen_expect_token(p, NAME);
793 if (t == NULL) {
794 return NULL;
795 }
796 char* s = PyBytes_AsString(t->bytes);
797 if (!s) {
798 return NULL;
799 }
800 PyObject *id = _PyPegen_new_identifier(p, s);
801 if (id == NULL) {
802 return NULL;
803 }
804 return Name(id, Load, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
805 p->arena);
806}
807
808void *
809_PyPegen_string_token(Parser *p)
810{
811 return _PyPegen_expect_token(p, STRING);
812}
813
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100814static PyObject *
815parsenumber_raw(const char *s)
816{
817 const char *end;
818 long x;
819 double dx;
820 Py_complex compl;
821 int imflag;
822
823 assert(s != NULL);
824 errno = 0;
825 end = s + strlen(s) - 1;
826 imflag = *end == 'j' || *end == 'J';
827 if (s[0] == '0') {
828 x = (long)PyOS_strtoul(s, (char **)&end, 0);
829 if (x < 0 && errno == 0) {
830 return PyLong_FromString(s, (char **)0, 0);
831 }
832 }
833 else
834 x = PyOS_strtol(s, (char **)&end, 0);
835 if (*end == '\0') {
836 if (errno != 0)
837 return PyLong_FromString(s, (char **)0, 0);
838 return PyLong_FromLong(x);
839 }
840 /* XXX Huge floats may silently fail */
841 if (imflag) {
842 compl.real = 0.;
843 compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
844 if (compl.imag == -1.0 && PyErr_Occurred())
845 return NULL;
846 return PyComplex_FromCComplex(compl);
847 }
848 else {
849 dx = PyOS_string_to_double(s, NULL, NULL);
850 if (dx == -1.0 && PyErr_Occurred())
851 return NULL;
852 return PyFloat_FromDouble(dx);
853 }
854}
855
856static PyObject *
857parsenumber(const char *s)
858{
859 char *dup, *end;
860 PyObject *res = NULL;
861
862 assert(s != NULL);
863
864 if (strchr(s, '_') == NULL) {
865 return parsenumber_raw(s);
866 }
867 /* Create a duplicate without underscores. */
868 dup = PyMem_Malloc(strlen(s) + 1);
869 if (dup == NULL) {
870 return PyErr_NoMemory();
871 }
872 end = dup;
873 for (; *s; s++) {
874 if (*s != '_') {
875 *end++ = *s;
876 }
877 }
878 *end = '\0';
879 res = parsenumber_raw(dup);
880 PyMem_Free(dup);
881 return res;
882}
883
884expr_ty
885_PyPegen_number_token(Parser *p)
886{
887 Token *t = _PyPegen_expect_token(p, NUMBER);
888 if (t == NULL) {
889 return NULL;
890 }
891
892 char *num_raw = PyBytes_AsString(t->bytes);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100893 if (num_raw == NULL) {
894 return NULL;
895 }
896
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300897 if (p->feature_version < 6 && strchr(num_raw, '_') != NULL) {
898 p->error_indicator = 1;
Shantanuc3f00142020-05-04 01:13:30 -0700899 return RAISE_SYNTAX_ERROR("Underscores in numeric literals are only supported "
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300900 "in Python 3.6 and greater");
901 }
902
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100903 PyObject *c = parsenumber(num_raw);
904
905 if (c == NULL) {
906 return NULL;
907 }
908
909 if (PyArena_AddPyObject(p->arena, c) < 0) {
910 Py_DECREF(c);
911 return NULL;
912 }
913
914 return Constant(c, NULL, t->lineno, t->col_offset, t->end_lineno, t->end_col_offset,
915 p->arena);
916}
917
Lysandros Nikolaou6d650872020-04-29 04:42:27 +0300918static int // bool
919newline_in_string(Parser *p, const char *cur)
920{
921 for (char c = *cur; cur >= p->tok->buf; c = *--cur) {
922 if (c == '\'' || c == '"') {
923 return 1;
924 }
925 }
926 return 0;
927}
928
929/* Check that the source for a single input statement really is a single
930 statement by looking at what is left in the buffer after parsing.
931 Trailing whitespace and comments are OK. */
932static int // bool
933bad_single_statement(Parser *p)
934{
935 const char *cur = strchr(p->tok->buf, '\n');
936
937 /* Newlines are allowed if preceded by a line continuation character
938 or if they appear inside a string. */
939 if (!cur || *(cur - 1) == '\\' || newline_in_string(p, cur)) {
940 return 0;
941 }
942 char c = *cur;
943
944 for (;;) {
945 while (c == ' ' || c == '\t' || c == '\n' || c == '\014') {
946 c = *++cur;
947 }
948
949 if (!c) {
950 return 0;
951 }
952
953 if (c != '#') {
954 return 1;
955 }
956
957 /* Suck up comment. */
958 while (c && c != '\n') {
959 c = *++cur;
960 }
961 }
962}
963
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100964void
965_PyPegen_Parser_Free(Parser *p)
966{
967 Py_XDECREF(p->normalize);
968 for (int i = 0; i < p->size; i++) {
969 PyMem_Free(p->tokens[i]);
970 }
971 PyMem_Free(p->tokens);
Guido van Rossumc001c092020-04-30 12:12:19 -0700972 growable_comment_array_deallocate(&p->type_ignore_comments);
Pablo Galindoc5fc1562020-04-22 23:29:27 +0100973 PyMem_Free(p);
974}
975
Pablo Galindo2b74c832020-04-27 18:02:07 +0100976static int
977compute_parser_flags(PyCompilerFlags *flags)
978{
979 int parser_flags = 0;
980 if (!flags) {
981 return 0;
982 }
983 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) {
984 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
985 }
986 if (flags->cf_flags & PyCF_IGNORE_COOKIE) {
987 parser_flags |= PyPARSE_IGNORE_COOKIE;
988 }
989 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) {
990 parser_flags |= PyPARSE_BARRY_AS_BDFL;
991 }
992 if (flags->cf_flags & PyCF_TYPE_COMMENTS) {
993 parser_flags |= PyPARSE_TYPE_COMMENTS;
994 }
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +0300995 if (flags->cf_feature_version < 7) {
996 parser_flags |= PyPARSE_ASYNC_HACKS;
997 }
Pablo Galindo2b74c832020-04-27 18:02:07 +0100998 return parser_flags;
999}
1000
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001001Parser *
Pablo Galindo2b74c832020-04-27 18:02:07 +01001002_PyPegen_Parser_New(struct tok_state *tok, int start_rule, int flags,
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001003 int feature_version, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001004{
1005 Parser *p = PyMem_Malloc(sizeof(Parser));
1006 if (p == NULL) {
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001007 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001008 }
1009 assert(tok != NULL);
Guido van Rossumd9d6ead2020-05-01 09:42:32 -07001010 tok->type_comments = (flags & PyPARSE_TYPE_COMMENTS) > 0;
1011 tok->async_hacks = (flags & PyPARSE_ASYNC_HACKS) > 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001012 p->tok = tok;
1013 p->keywords = NULL;
1014 p->n_keyword_lists = -1;
1015 p->tokens = PyMem_Malloc(sizeof(Token *));
1016 if (!p->tokens) {
1017 PyMem_Free(p);
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001018 return (Parser *) PyErr_NoMemory();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001019 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001020 p->tokens[0] = PyMem_Calloc(1, sizeof(Token));
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001021 if (!p->tokens) {
1022 PyMem_Free(p->tokens);
1023 PyMem_Free(p);
1024 return (Parser *) PyErr_NoMemory();
1025 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001026 if (!growable_comment_array_init(&p->type_ignore_comments, 10)) {
1027 PyMem_Free(p->tokens[0]);
1028 PyMem_Free(p->tokens);
1029 PyMem_Free(p);
1030 return (Parser *) PyErr_NoMemory();
1031 }
1032
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001033 p->mark = 0;
1034 p->fill = 0;
1035 p->size = 1;
1036
1037 p->errcode = errcode;
1038 p->arena = arena;
1039 p->start_rule = start_rule;
1040 p->parsing_started = 0;
1041 p->normalize = NULL;
1042 p->error_indicator = 0;
1043
1044 p->starting_lineno = 0;
1045 p->starting_col_offset = 0;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001046 p->flags = flags;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001047 p->feature_version = feature_version;
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001048 p->known_err_token = NULL;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001049
1050 return p;
1051}
1052
1053void *
1054_PyPegen_run_parser(Parser *p)
1055{
1056 void *res = _PyPegen_parse(p);
1057 if (res == NULL) {
1058 if (PyErr_Occurred()) {
1059 return NULL;
1060 }
1061 if (p->fill == 0) {
1062 RAISE_SYNTAX_ERROR("error at start before reading any input");
1063 }
1064 else if (p->tok->done == E_EOF) {
1065 RAISE_SYNTAX_ERROR("unexpected EOF while parsing");
1066 }
1067 else {
1068 if (p->tokens[p->fill-1]->type == INDENT) {
1069 RAISE_INDENTATION_ERROR("unexpected indent");
1070 }
1071 else if (p->tokens[p->fill-1]->type == DEDENT) {
1072 RAISE_INDENTATION_ERROR("unexpected unindent");
1073 }
1074 else {
1075 RAISE_SYNTAX_ERROR("invalid syntax");
1076 }
1077 }
1078 return NULL;
1079 }
1080
Lysandros Nikolaou6d650872020-04-29 04:42:27 +03001081 if (p->start_rule == Py_single_input && bad_single_statement(p)) {
1082 p->tok->done = E_BADSINGLE; // This is not necessary for now, but might be in the future
1083 return RAISE_SYNTAX_ERROR("multiple statements found while compiling a single statement");
1084 }
1085
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001086 return res;
1087}
1088
1089mod_ty
1090_PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filename_ob,
1091 const char *enc, const char *ps1, const char *ps2,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001092 PyCompilerFlags *flags, int *errcode, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001093{
1094 struct tok_state *tok = PyTokenizer_FromFile(fp, enc, ps1, ps2);
1095 if (tok == NULL) {
1096 if (PyErr_Occurred()) {
1097 raise_tokenizer_init_error(filename_ob);
1098 return NULL;
1099 }
1100 return NULL;
1101 }
1102 // This transfers the ownership to the tokenizer
1103 tok->filename = filename_ob;
1104 Py_INCREF(filename_ob);
1105
1106 // From here on we need to clean up even if there's an error
1107 mod_ty result = NULL;
1108
Pablo Galindo2b74c832020-04-27 18:02:07 +01001109 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001110 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, PY_MINOR_VERSION,
1111 errcode, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001112 if (p == NULL) {
1113 goto error;
1114 }
1115
1116 result = _PyPegen_run_parser(p);
1117 _PyPegen_Parser_Free(p);
1118
1119error:
1120 PyTokenizer_Free(tok);
1121 return result;
1122}
1123
1124mod_ty
1125_PyPegen_run_parser_from_file(const char *filename, int start_rule,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001126 PyObject *filename_ob, PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001127{
1128 FILE *fp = fopen(filename, "rb");
1129 if (fp == NULL) {
1130 PyErr_SetFromErrnoWithFilename(PyExc_OSError, filename);
1131 return NULL;
1132 }
1133
1134 mod_ty result = _PyPegen_run_parser_from_file_pointer(fp, start_rule, filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001135 NULL, NULL, NULL, flags, NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001136
1137 fclose(fp);
1138 return result;
1139}
1140
1141mod_ty
1142_PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filename_ob,
Pablo Galindo2b74c832020-04-27 18:02:07 +01001143 PyCompilerFlags *flags, PyArena *arena)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001144{
1145 int exec_input = start_rule == Py_file_input;
1146
1147 struct tok_state *tok;
Pablo Galindo2b74c832020-04-27 18:02:07 +01001148 if (flags == NULL || flags->cf_flags & PyCF_IGNORE_COOKIE) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001149 tok = PyTokenizer_FromUTF8(str, exec_input);
1150 } else {
1151 tok = PyTokenizer_FromString(str, exec_input);
1152 }
1153 if (tok == NULL) {
1154 if (PyErr_Occurred()) {
1155 raise_tokenizer_init_error(filename_ob);
1156 }
1157 return NULL;
1158 }
1159 // This transfers the ownership to the tokenizer
1160 tok->filename = filename_ob;
1161 Py_INCREF(filename_ob);
1162
1163 // We need to clear up from here on
1164 mod_ty result = NULL;
1165
Pablo Galindo2b74c832020-04-27 18:02:07 +01001166 int parser_flags = compute_parser_flags(flags);
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001167 int feature_version = flags ? flags->cf_feature_version : PY_MINOR_VERSION;
Lysandros Nikolaou3e0a6f32020-05-01 06:27:52 +03001168 Parser *p = _PyPegen_Parser_New(tok, start_rule, parser_flags, feature_version,
1169 NULL, arena);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001170 if (p == NULL) {
1171 goto error;
1172 }
1173
1174 result = _PyPegen_run_parser(p);
1175 _PyPegen_Parser_Free(p);
1176
1177error:
1178 PyTokenizer_Free(tok);
1179 return result;
1180}
1181
1182void *
1183_PyPegen_interactive_exit(Parser *p)
1184{
1185 if (p->errcode) {
1186 *(p->errcode) = E_EOF;
1187 }
1188 return NULL;
1189}
1190
1191/* Creates a single-element asdl_seq* that contains a */
1192asdl_seq *
1193_PyPegen_singleton_seq(Parser *p, void *a)
1194{
1195 assert(a != NULL);
1196 asdl_seq *seq = _Py_asdl_seq_new(1, p->arena);
1197 if (!seq) {
1198 return NULL;
1199 }
1200 asdl_seq_SET(seq, 0, a);
1201 return seq;
1202}
1203
1204/* Creates a copy of seq and prepends a to it */
1205asdl_seq *
1206_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
1207{
1208 assert(a != NULL);
1209 if (!seq) {
1210 return _PyPegen_singleton_seq(p, a);
1211 }
1212
1213 asdl_seq *new_seq = _Py_asdl_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
1214 if (!new_seq) {
1215 return NULL;
1216 }
1217
1218 asdl_seq_SET(new_seq, 0, a);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001219 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001220 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i - 1));
1221 }
1222 return new_seq;
1223}
1224
Guido van Rossumc001c092020-04-30 12:12:19 -07001225/* Creates a copy of seq and appends a to it */
1226asdl_seq *
1227_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
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 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
1240 asdl_seq_SET(new_seq, i, asdl_seq_GET(seq, i));
1241 }
1242 asdl_seq_SET(new_seq, asdl_seq_LEN(new_seq) - 1, a);
1243 return new_seq;
1244}
1245
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001246static Py_ssize_t
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001247_get_flattened_seq_size(asdl_seq *seqs)
1248{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001249 Py_ssize_t size = 0;
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001250 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1251 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
1252 size += asdl_seq_LEN(inner_seq);
1253 }
1254 return size;
1255}
1256
1257/* Flattens an asdl_seq* of asdl_seq*s */
1258asdl_seq *
1259_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
1260{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001261 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001262 assert(flattened_seq_size > 0);
1263
1264 asdl_seq *flattened_seq = _Py_asdl_seq_new(flattened_seq_size, p->arena);
1265 if (!flattened_seq) {
1266 return NULL;
1267 }
1268
1269 int flattened_seq_idx = 0;
1270 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
1271 asdl_seq *inner_seq = asdl_seq_GET(seqs, i);
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001272 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001273 asdl_seq_SET(flattened_seq, flattened_seq_idx++, asdl_seq_GET(inner_seq, j));
1274 }
1275 }
1276 assert(flattened_seq_idx == flattened_seq_size);
1277
1278 return flattened_seq;
1279}
1280
1281/* Creates a new name of the form <first_name>.<second_name> */
1282expr_ty
1283_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
1284{
1285 assert(first_name != NULL && second_name != NULL);
1286 PyObject *first_identifier = first_name->v.Name.id;
1287 PyObject *second_identifier = second_name->v.Name.id;
1288
1289 if (PyUnicode_READY(first_identifier) == -1) {
1290 return NULL;
1291 }
1292 if (PyUnicode_READY(second_identifier) == -1) {
1293 return NULL;
1294 }
1295 const char *first_str = PyUnicode_AsUTF8(first_identifier);
1296 if (!first_str) {
1297 return NULL;
1298 }
1299 const char *second_str = PyUnicode_AsUTF8(second_identifier);
1300 if (!second_str) {
1301 return NULL;
1302 }
Pablo Galindo9f27dd32020-04-24 01:13:33 +01001303 Py_ssize_t len = strlen(first_str) + strlen(second_str) + 1; // +1 for the dot
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001304
1305 PyObject *str = PyBytes_FromStringAndSize(NULL, len);
1306 if (!str) {
1307 return NULL;
1308 }
1309
1310 char *s = PyBytes_AS_STRING(str);
1311 if (!s) {
1312 return NULL;
1313 }
1314
1315 strcpy(s, first_str);
1316 s += strlen(first_str);
1317 *s++ = '.';
1318 strcpy(s, second_str);
1319 s += strlen(second_str);
1320 *s = '\0';
1321
1322 PyObject *uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL);
1323 Py_DECREF(str);
1324 if (!uni) {
1325 return NULL;
1326 }
1327 PyUnicode_InternInPlace(&uni);
1328 if (PyArena_AddPyObject(p->arena, uni) < 0) {
1329 Py_DECREF(uni);
1330 return NULL;
1331 }
1332
1333 return _Py_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
1334}
1335
1336/* Counts the total number of dots in seq's tokens */
1337int
1338_PyPegen_seq_count_dots(asdl_seq *seq)
1339{
1340 int number_of_dots = 0;
1341 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1342 Token *current_expr = asdl_seq_GET(seq, i);
1343 switch (current_expr->type) {
1344 case ELLIPSIS:
1345 number_of_dots += 3;
1346 break;
1347 case DOT:
1348 number_of_dots += 1;
1349 break;
1350 default:
Lysandros Nikolaouebebb642020-04-23 18:36:06 +03001351 Py_UNREACHABLE();
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001352 }
1353 }
1354
1355 return number_of_dots;
1356}
1357
1358/* Creates an alias with '*' as the identifier name */
1359alias_ty
1360_PyPegen_alias_for_star(Parser *p)
1361{
1362 PyObject *str = PyUnicode_InternFromString("*");
1363 if (!str) {
1364 return NULL;
1365 }
1366 if (PyArena_AddPyObject(p->arena, str) < 0) {
1367 Py_DECREF(str);
1368 return NULL;
1369 }
1370 return alias(str, NULL, p->arena);
1371}
1372
1373/* Creates a new asdl_seq* with the identifiers of all the names in seq */
1374asdl_seq *
1375_PyPegen_map_names_to_ids(Parser *p, asdl_seq *seq)
1376{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001377 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001378 assert(len > 0);
1379
1380 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1381 if (!new_seq) {
1382 return NULL;
1383 }
1384 for (Py_ssize_t i = 0; i < len; i++) {
1385 expr_ty e = asdl_seq_GET(seq, i);
1386 asdl_seq_SET(new_seq, i, e->v.Name.id);
1387 }
1388 return new_seq;
1389}
1390
1391/* Constructs a CmpopExprPair */
1392CmpopExprPair *
1393_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
1394{
1395 assert(expr != NULL);
1396 CmpopExprPair *a = PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
1397 if (!a) {
1398 return NULL;
1399 }
1400 a->cmpop = cmpop;
1401 a->expr = expr;
1402 return a;
1403}
1404
1405asdl_int_seq *
1406_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
1407{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001408 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001409 assert(len > 0);
1410
1411 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
1412 if (!new_seq) {
1413 return NULL;
1414 }
1415 for (Py_ssize_t i = 0; i < len; i++) {
1416 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1417 asdl_seq_SET(new_seq, i, pair->cmpop);
1418 }
1419 return new_seq;
1420}
1421
1422asdl_seq *
1423_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
1424{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001425 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001426 assert(len > 0);
1427
1428 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1429 if (!new_seq) {
1430 return NULL;
1431 }
1432 for (Py_ssize_t i = 0; i < len; i++) {
1433 CmpopExprPair *pair = asdl_seq_GET(seq, i);
1434 asdl_seq_SET(new_seq, i, pair->expr);
1435 }
1436 return new_seq;
1437}
1438
1439/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
1440static asdl_seq *
1441_set_seq_context(Parser *p, asdl_seq *seq, expr_context_ty ctx)
1442{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001443 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001444 if (len == 0) {
1445 return NULL;
1446 }
1447
1448 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1449 if (!new_seq) {
1450 return NULL;
1451 }
1452 for (Py_ssize_t i = 0; i < len; i++) {
1453 expr_ty e = asdl_seq_GET(seq, i);
1454 asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
1455 }
1456 return new_seq;
1457}
1458
1459static expr_ty
1460_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
1461{
1462 return _Py_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
1463}
1464
1465static expr_ty
1466_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
1467{
1468 return _Py_Tuple(_set_seq_context(p, e->v.Tuple.elts, ctx), ctx, EXTRA_EXPR(e, e));
1469}
1470
1471static expr_ty
1472_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
1473{
1474 return _Py_List(_set_seq_context(p, e->v.List.elts, ctx), ctx, EXTRA_EXPR(e, e));
1475}
1476
1477static expr_ty
1478_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
1479{
1480 return _Py_Subscript(e->v.Subscript.value, e->v.Subscript.slice, ctx, EXTRA_EXPR(e, e));
1481}
1482
1483static expr_ty
1484_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
1485{
1486 return _Py_Attribute(e->v.Attribute.value, e->v.Attribute.attr, ctx, EXTRA_EXPR(e, e));
1487}
1488
1489static expr_ty
1490_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
1491{
1492 return _Py_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx), ctx, EXTRA_EXPR(e, e));
1493}
1494
1495/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
1496expr_ty
1497_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
1498{
1499 assert(expr != NULL);
1500
1501 expr_ty new = NULL;
1502 switch (expr->kind) {
1503 case Name_kind:
1504 new = _set_name_context(p, expr, ctx);
1505 break;
1506 case Tuple_kind:
1507 new = _set_tuple_context(p, expr, ctx);
1508 break;
1509 case List_kind:
1510 new = _set_list_context(p, expr, ctx);
1511 break;
1512 case Subscript_kind:
1513 new = _set_subscript_context(p, expr, ctx);
1514 break;
1515 case Attribute_kind:
1516 new = _set_attribute_context(p, expr, ctx);
1517 break;
1518 case Starred_kind:
1519 new = _set_starred_context(p, expr, ctx);
1520 break;
1521 default:
1522 new = expr;
1523 }
1524 return new;
1525}
1526
1527/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
1528KeyValuePair *
1529_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
1530{
1531 KeyValuePair *a = PyArena_Malloc(p->arena, sizeof(KeyValuePair));
1532 if (!a) {
1533 return NULL;
1534 }
1535 a->key = key;
1536 a->value = value;
1537 return a;
1538}
1539
1540/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
1541asdl_seq *
1542_PyPegen_get_keys(Parser *p, asdl_seq *seq)
1543{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001544 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001545 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1546 if (!new_seq) {
1547 return NULL;
1548 }
1549 for (Py_ssize_t i = 0; i < len; i++) {
1550 KeyValuePair *pair = asdl_seq_GET(seq, i);
1551 asdl_seq_SET(new_seq, i, pair->key);
1552 }
1553 return new_seq;
1554}
1555
1556/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
1557asdl_seq *
1558_PyPegen_get_values(Parser *p, asdl_seq *seq)
1559{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001560 Py_ssize_t len = asdl_seq_LEN(seq);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001561 asdl_seq *new_seq = _Py_asdl_seq_new(len, p->arena);
1562 if (!new_seq) {
1563 return NULL;
1564 }
1565 for (Py_ssize_t i = 0; i < len; i++) {
1566 KeyValuePair *pair = asdl_seq_GET(seq, i);
1567 asdl_seq_SET(new_seq, i, pair->value);
1568 }
1569 return new_seq;
1570}
1571
1572/* Constructs a NameDefaultPair */
1573NameDefaultPair *
Guido van Rossumc001c092020-04-30 12:12:19 -07001574_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001575{
1576 NameDefaultPair *a = PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
1577 if (!a) {
1578 return NULL;
1579 }
Guido van Rossumc001c092020-04-30 12:12:19 -07001580 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001581 a->value = value;
1582 return a;
1583}
1584
1585/* Constructs a SlashWithDefault */
1586SlashWithDefault *
1587_PyPegen_slash_with_default(Parser *p, asdl_seq *plain_names, asdl_seq *names_with_defaults)
1588{
1589 SlashWithDefault *a = PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
1590 if (!a) {
1591 return NULL;
1592 }
1593 a->plain_names = plain_names;
1594 a->names_with_defaults = names_with_defaults;
1595 return a;
1596}
1597
1598/* Constructs a StarEtc */
1599StarEtc *
1600_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
1601{
1602 StarEtc *a = PyArena_Malloc(p->arena, sizeof(StarEtc));
1603 if (!a) {
1604 return NULL;
1605 }
1606 a->vararg = vararg;
1607 a->kwonlyargs = kwonlyargs;
1608 a->kwarg = kwarg;
1609 return a;
1610}
1611
1612asdl_seq *
1613_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
1614{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001615 Py_ssize_t first_len = asdl_seq_LEN(a);
1616 Py_ssize_t second_len = asdl_seq_LEN(b);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001617 asdl_seq *new_seq = _Py_asdl_seq_new(first_len + second_len, p->arena);
1618 if (!new_seq) {
1619 return NULL;
1620 }
1621
1622 int k = 0;
1623 for (Py_ssize_t i = 0; i < first_len; i++) {
1624 asdl_seq_SET(new_seq, k++, asdl_seq_GET(a, i));
1625 }
1626 for (Py_ssize_t i = 0; i < second_len; i++) {
1627 asdl_seq_SET(new_seq, k++, asdl_seq_GET(b, i));
1628 }
1629
1630 return new_seq;
1631}
1632
1633static asdl_seq *
1634_get_names(Parser *p, asdl_seq *names_with_defaults)
1635{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001636 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001637 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1638 if (!seq) {
1639 return NULL;
1640 }
1641 for (Py_ssize_t i = 0; i < len; i++) {
1642 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1643 asdl_seq_SET(seq, i, pair->arg);
1644 }
1645 return seq;
1646}
1647
1648static asdl_seq *
1649_get_defaults(Parser *p, asdl_seq *names_with_defaults)
1650{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001651 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001652 asdl_seq *seq = _Py_asdl_seq_new(len, p->arena);
1653 if (!seq) {
1654 return NULL;
1655 }
1656 for (Py_ssize_t i = 0; i < len; i++) {
1657 NameDefaultPair *pair = asdl_seq_GET(names_with_defaults, i);
1658 asdl_seq_SET(seq, i, pair->value);
1659 }
1660 return seq;
1661}
1662
1663/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
1664arguments_ty
1665_PyPegen_make_arguments(Parser *p, asdl_seq *slash_without_default,
1666 SlashWithDefault *slash_with_default, asdl_seq *plain_names,
1667 asdl_seq *names_with_default, StarEtc *star_etc)
1668{
1669 asdl_seq *posonlyargs;
1670 if (slash_without_default != NULL) {
1671 posonlyargs = slash_without_default;
1672 }
1673 else if (slash_with_default != NULL) {
1674 asdl_seq *slash_with_default_names =
1675 _get_names(p, slash_with_default->names_with_defaults);
1676 if (!slash_with_default_names) {
1677 return NULL;
1678 }
1679 posonlyargs = _PyPegen_join_sequences(p, slash_with_default->plain_names, slash_with_default_names);
1680 if (!posonlyargs) {
1681 return NULL;
1682 }
1683 }
1684 else {
1685 posonlyargs = _Py_asdl_seq_new(0, p->arena);
1686 if (!posonlyargs) {
1687 return NULL;
1688 }
1689 }
1690
1691 asdl_seq *posargs;
1692 if (plain_names != NULL && names_with_default != NULL) {
1693 asdl_seq *names_with_default_names = _get_names(p, names_with_default);
1694 if (!names_with_default_names) {
1695 return NULL;
1696 }
1697 posargs = _PyPegen_join_sequences(p, plain_names, names_with_default_names);
1698 if (!posargs) {
1699 return NULL;
1700 }
1701 }
1702 else if (plain_names == NULL && names_with_default != NULL) {
1703 posargs = _get_names(p, names_with_default);
1704 if (!posargs) {
1705 return NULL;
1706 }
1707 }
1708 else if (plain_names != NULL && names_with_default == NULL) {
1709 posargs = plain_names;
1710 }
1711 else {
1712 posargs = _Py_asdl_seq_new(0, p->arena);
1713 if (!posargs) {
1714 return NULL;
1715 }
1716 }
1717
1718 asdl_seq *posdefaults;
1719 if (slash_with_default != NULL && names_with_default != NULL) {
1720 asdl_seq *slash_with_default_values =
1721 _get_defaults(p, slash_with_default->names_with_defaults);
1722 if (!slash_with_default_values) {
1723 return NULL;
1724 }
1725 asdl_seq *names_with_default_values = _get_defaults(p, names_with_default);
1726 if (!names_with_default_values) {
1727 return NULL;
1728 }
1729 posdefaults = _PyPegen_join_sequences(p, slash_with_default_values, names_with_default_values);
1730 if (!posdefaults) {
1731 return NULL;
1732 }
1733 }
1734 else if (slash_with_default == NULL && names_with_default != NULL) {
1735 posdefaults = _get_defaults(p, names_with_default);
1736 if (!posdefaults) {
1737 return NULL;
1738 }
1739 }
1740 else if (slash_with_default != NULL && names_with_default == NULL) {
1741 posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
1742 if (!posdefaults) {
1743 return NULL;
1744 }
1745 }
1746 else {
1747 posdefaults = _Py_asdl_seq_new(0, p->arena);
1748 if (!posdefaults) {
1749 return NULL;
1750 }
1751 }
1752
1753 arg_ty vararg = NULL;
1754 if (star_etc != NULL && star_etc->vararg != NULL) {
1755 vararg = star_etc->vararg;
1756 }
1757
1758 asdl_seq *kwonlyargs;
1759 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1760 kwonlyargs = _get_names(p, star_etc->kwonlyargs);
1761 if (!kwonlyargs) {
1762 return NULL;
1763 }
1764 }
1765 else {
1766 kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1767 if (!kwonlyargs) {
1768 return NULL;
1769 }
1770 }
1771
1772 asdl_seq *kwdefaults;
1773 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
1774 kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
1775 if (!kwdefaults) {
1776 return NULL;
1777 }
1778 }
1779 else {
1780 kwdefaults = _Py_asdl_seq_new(0, p->arena);
1781 if (!kwdefaults) {
1782 return NULL;
1783 }
1784 }
1785
1786 arg_ty kwarg = NULL;
1787 if (star_etc != NULL && star_etc->kwarg != NULL) {
1788 kwarg = star_etc->kwarg;
1789 }
1790
1791 return _Py_arguments(posonlyargs, posargs, vararg, kwonlyargs, kwdefaults, kwarg,
1792 posdefaults, p->arena);
1793}
1794
1795/* Constructs an empty arguments_ty object, that gets used when a function accepts no
1796 * arguments. */
1797arguments_ty
1798_PyPegen_empty_arguments(Parser *p)
1799{
1800 asdl_seq *posonlyargs = _Py_asdl_seq_new(0, p->arena);
1801 if (!posonlyargs) {
1802 return NULL;
1803 }
1804 asdl_seq *posargs = _Py_asdl_seq_new(0, p->arena);
1805 if (!posargs) {
1806 return NULL;
1807 }
1808 asdl_seq *posdefaults = _Py_asdl_seq_new(0, p->arena);
1809 if (!posdefaults) {
1810 return NULL;
1811 }
1812 asdl_seq *kwonlyargs = _Py_asdl_seq_new(0, p->arena);
1813 if (!kwonlyargs) {
1814 return NULL;
1815 }
1816 asdl_seq *kwdefaults = _Py_asdl_seq_new(0, p->arena);
1817 if (!kwdefaults) {
1818 return NULL;
1819 }
1820
1821 return _Py_arguments(posonlyargs, posargs, NULL, kwonlyargs, kwdefaults, NULL, kwdefaults,
1822 p->arena);
1823}
1824
1825/* Encapsulates the value of an operator_ty into an AugOperator struct */
1826AugOperator *
1827_PyPegen_augoperator(Parser *p, operator_ty kind)
1828{
1829 AugOperator *a = PyArena_Malloc(p->arena, sizeof(AugOperator));
1830 if (!a) {
1831 return NULL;
1832 }
1833 a->kind = kind;
1834 return a;
1835}
1836
1837/* Construct a FunctionDef equivalent to function_def, but with decorators */
1838stmt_ty
1839_PyPegen_function_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty function_def)
1840{
1841 assert(function_def != NULL);
1842 if (function_def->kind == AsyncFunctionDef_kind) {
1843 return _Py_AsyncFunctionDef(
1844 function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1845 function_def->v.FunctionDef.body, decorators, function_def->v.FunctionDef.returns,
1846 function_def->v.FunctionDef.type_comment, function_def->lineno,
1847 function_def->col_offset, function_def->end_lineno, function_def->end_col_offset,
1848 p->arena);
1849 }
1850
1851 return _Py_FunctionDef(function_def->v.FunctionDef.name, function_def->v.FunctionDef.args,
1852 function_def->v.FunctionDef.body, decorators,
1853 function_def->v.FunctionDef.returns,
1854 function_def->v.FunctionDef.type_comment, function_def->lineno,
1855 function_def->col_offset, function_def->end_lineno,
1856 function_def->end_col_offset, p->arena);
1857}
1858
1859/* Construct a ClassDef equivalent to class_def, but with decorators */
1860stmt_ty
1861_PyPegen_class_def_decorators(Parser *p, asdl_seq *decorators, stmt_ty class_def)
1862{
1863 assert(class_def != NULL);
1864 return _Py_ClassDef(class_def->v.ClassDef.name, class_def->v.ClassDef.bases,
1865 class_def->v.ClassDef.keywords, class_def->v.ClassDef.body, decorators,
1866 class_def->lineno, class_def->col_offset, class_def->end_lineno,
1867 class_def->end_col_offset, p->arena);
1868}
1869
1870/* Construct a KeywordOrStarred */
1871KeywordOrStarred *
1872_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
1873{
1874 KeywordOrStarred *a = PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
1875 if (!a) {
1876 return NULL;
1877 }
1878 a->element = element;
1879 a->is_keyword = is_keyword;
1880 return a;
1881}
1882
1883/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
1884static int
1885_seq_number_of_starred_exprs(asdl_seq *seq)
1886{
1887 int n = 0;
1888 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
1889 KeywordOrStarred *k = asdl_seq_GET(seq, i);
1890 if (!k->is_keyword) {
1891 n++;
1892 }
1893 }
1894 return n;
1895}
1896
1897/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
1898asdl_seq *
1899_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
1900{
1901 int new_len = _seq_number_of_starred_exprs(kwargs);
1902 if (new_len == 0) {
1903 return NULL;
1904 }
1905 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1906 if (!new_seq) {
1907 return NULL;
1908 }
1909
1910 int idx = 0;
1911 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
1912 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1913 if (!k->is_keyword) {
1914 asdl_seq_SET(new_seq, idx++, k->element);
1915 }
1916 }
1917 return new_seq;
1918}
1919
1920/* Return a new asdl_seq* with only the keywords in kwargs */
1921asdl_seq *
1922_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
1923{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001924 Py_ssize_t len = asdl_seq_LEN(kwargs);
1925 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001926 if (new_len == 0) {
1927 return NULL;
1928 }
1929 asdl_seq *new_seq = _Py_asdl_seq_new(new_len, p->arena);
1930 if (!new_seq) {
1931 return NULL;
1932 }
1933
1934 int idx = 0;
1935 for (Py_ssize_t i = 0; i < len; i++) {
1936 KeywordOrStarred *k = asdl_seq_GET(kwargs, i);
1937 if (k->is_keyword) {
1938 asdl_seq_SET(new_seq, idx++, k->element);
1939 }
1940 }
1941 return new_seq;
1942}
1943
1944expr_ty
1945_PyPegen_concatenate_strings(Parser *p, asdl_seq *strings)
1946{
Pablo Galindoee40e4b2020-04-23 03:43:08 +01001947 Py_ssize_t len = asdl_seq_LEN(strings);
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001948 assert(len > 0);
1949
1950 Token *first = asdl_seq_GET(strings, 0);
1951 Token *last = asdl_seq_GET(strings, len - 1);
1952
1953 int bytesmode = 0;
1954 PyObject *bytes_str = NULL;
1955
1956 FstringParser state;
1957 _PyPegen_FstringParser_Init(&state);
1958
1959 for (Py_ssize_t i = 0; i < len; i++) {
1960 Token *t = asdl_seq_GET(strings, i);
1961
1962 int this_bytesmode;
1963 int this_rawmode;
1964 PyObject *s;
1965 const char *fstr;
1966 Py_ssize_t fstrlen = -1;
1967
Lysandros Nikolaou2f37c352020-05-07 13:37:51 +03001968 if (_PyPegen_parsestr(p, &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen, t) != 0) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01001969 goto error;
1970 }
1971
1972 /* Check that we are not mixing bytes with unicode. */
1973 if (i != 0 && bytesmode != this_bytesmode) {
1974 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1975 Py_XDECREF(s);
1976 goto error;
1977 }
1978 bytesmode = this_bytesmode;
1979
1980 if (fstr != NULL) {
1981 assert(s == NULL && !bytesmode);
1982
1983 int result = _PyPegen_FstringParser_ConcatFstring(p, &state, &fstr, fstr + fstrlen,
1984 this_rawmode, 0, first, t, last);
1985 if (result < 0) {
1986 goto error;
1987 }
1988 }
1989 else {
1990 /* String or byte string. */
1991 assert(s != NULL && fstr == NULL);
1992 assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s));
1993
1994 if (bytesmode) {
1995 if (i == 0) {
1996 bytes_str = s;
1997 }
1998 else {
1999 PyBytes_ConcatAndDel(&bytes_str, s);
2000 if (!bytes_str) {
2001 goto error;
2002 }
2003 }
2004 }
2005 else {
2006 /* This is a regular string. Concatenate it. */
2007 if (_PyPegen_FstringParser_ConcatAndDel(&state, s) < 0) {
2008 goto error;
2009 }
2010 }
2011 }
2012 }
2013
2014 if (bytesmode) {
2015 if (PyArena_AddPyObject(p->arena, bytes_str) < 0) {
2016 goto error;
2017 }
2018 return Constant(bytes_str, NULL, first->lineno, first->col_offset, last->end_lineno,
2019 last->end_col_offset, p->arena);
2020 }
2021
2022 return _PyPegen_FstringParser_Finish(p, &state, first, last);
2023
2024error:
2025 Py_XDECREF(bytes_str);
2026 _PyPegen_FstringParser_Dealloc(&state);
2027 if (PyErr_Occurred()) {
2028 raise_decode_error(p);
2029 }
2030 return NULL;
2031}
Guido van Rossumc001c092020-04-30 12:12:19 -07002032
2033mod_ty
2034_PyPegen_make_module(Parser *p, asdl_seq *a) {
2035 asdl_seq *type_ignores = NULL;
2036 Py_ssize_t num = p->type_ignore_comments.num_items;
2037 if (num > 0) {
2038 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
2039 type_ignores = _Py_asdl_seq_new(num, p->arena);
2040 if (type_ignores == NULL) {
2041 return NULL;
2042 }
2043 for (int i = 0; i < num; i++) {
2044 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
2045 if (tag == NULL) {
2046 return NULL;
2047 }
2048 type_ignore_ty ti = TypeIgnore(p->type_ignore_comments.items[i].lineno, tag, p->arena);
2049 if (ti == NULL) {
2050 return NULL;
2051 }
2052 asdl_seq_SET(type_ignores, i, ti);
2053 }
2054 }
2055 return Module(a, type_ignores, p->arena);
2056}
Pablo Galindo16ab0702020-05-15 02:04:52 +01002057
2058// Error reporting helpers
2059
2060expr_ty
2061_PyPegen_get_invalid_target(expr_ty e)
2062{
2063 if (e == NULL) {
2064 return NULL;
2065 }
2066
2067#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
2068 Py_ssize_t len = asdl_seq_LEN(CONTAINER->v.TYPE.elts);\
2069 for (Py_ssize_t i = 0; i < len; i++) {\
2070 expr_ty other = asdl_seq_GET(CONTAINER->v.TYPE.elts, i);\
2071 expr_ty child = _PyPegen_get_invalid_target(other);\
2072 if (child != NULL) {\
2073 return child;\
2074 }\
2075 }\
2076 } while (0)
2077
2078 // We only need to visit List and Tuple nodes recursively as those
2079 // are the only ones that can contain valid names in targets when
2080 // they are parsed as expressions. Any other kind of expression
2081 // that is a container (like Sets or Dicts) is directly invalid and
2082 // we don't need to visit it recursively.
2083
2084 switch (e->kind) {
2085 case List_kind: {
2086 VISIT_CONTAINER(e, List);
2087 return NULL;
2088 }
2089 case Tuple_kind: {
2090 VISIT_CONTAINER(e, Tuple);
2091 return NULL;
2092 }
2093 case Starred_kind:
2094 return _PyPegen_get_invalid_target(e->v.Starred.value);
2095 case Name_kind:
2096 case Subscript_kind:
2097 case Attribute_kind:
2098 return NULL;
2099 default:
2100 return e;
2101 }
2102}