Debian Codegraph @

Parser/action_helpers.c

raw
1 #include <Python.h>
2
3 #include "pegen.h"
4 #include "lexer/state.h"
5 #include "string_parser.h"
6 #include "pycore_runtime.h" // _PyRuntime
7 #include "pycore_pystate.h" // _PyInterpreterState_GET()
8
9 void *
10 _PyPegen_dummy_name(Parser *p, ...)
11 {
12 return &_PyRuntime.parser.dummy_name;
13 }
14
15 /* Creates a single-element asdl_seq* that contains a */
16 asdl_seq *
17 _PyPegen_singleton_seq(Parser *p, void *a)
18 {
19 assert(a != NULL);
20 asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
21 if (!seq) {
22 return NULL;
23 }
24 asdl_seq_SET_UNTYPED(seq, 0, a);
25 return seq;
26 }
27
28 /* Creates a copy of seq and prepends a to it */
29 asdl_seq *
30 _PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
31 {
32 assert(a != NULL);
33 if (!seq) {
34 return _PyPegen_singleton_seq(p, a);
35 }
36
37 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
38 if (!new_seq) {
39 return NULL;
40 }
41
42 asdl_seq_SET_UNTYPED(new_seq, 0, a);
43 for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
44 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
45 }
46 return new_seq;
47 }
48
49 /* Creates a copy of seq and appends a to it */
50 asdl_seq *
51 _PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
52 {
53 assert(a != NULL);
54 if (!seq) {
55 return _PyPegen_singleton_seq(p, a);
56 }
57
58 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
59 if (!new_seq) {
60 return NULL;
61 }
62
63 for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
64 asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
65 }
66 asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
67 return new_seq;
68 }
69
70 static Py_ssize_t
71 _get_flattened_seq_size(asdl_seq *seqs)
72 {
73 Py_ssize_t size = 0;
74 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
75 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
76 size += asdl_seq_LEN(inner_seq);
77 }
78 return size;
79 }
80
81 /* Flattens an asdl_seq* of asdl_seq*s */
82 asdl_seq *
83 _PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
84 {
85 Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
86 assert(flattened_seq_size > 0);
87
88 asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
89 if (!flattened_seq) {
90 return NULL;
91 }
92
93 int flattened_seq_idx = 0;
94 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
95 asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
96 for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
97 asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
98 }
99 }
100 assert(flattened_seq_idx == flattened_seq_size);
101
102 return flattened_seq;
103 }
104
105 void *
106 _PyPegen_seq_last_item(asdl_seq *seq)
107 {
108 Py_ssize_t len = asdl_seq_LEN(seq);
109 return asdl_seq_GET_UNTYPED(seq, len - 1);
110 }
111
112 void *
113 _PyPegen_seq_first_item(asdl_seq *seq)
114 {
115 return asdl_seq_GET_UNTYPED(seq, 0);
116 }
117
118 /* Creates a new name of the form <first_name>.<second_name> */
119 expr_ty
120 _PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
121 {
122 assert(first_name != NULL && second_name != NULL);
123 PyObject *uni = PyUnicode_FromFormat("%U.%U",
124 first_name->v.Name.id, second_name->v.Name.id);
125 if (!uni) {
126 return NULL;
127 }
128 PyInterpreterState *interp = _PyInterpreterState_GET();
129 _PyUnicode_InternImmortal(interp, &uni);
130 if (_PyArena_AddPyObject(p->arena, uni) < 0) {
131 Py_DECREF(uni);
132 return NULL;
133 }
134
135 return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
136 }
137
138 /* Counts the total number of dots in seq's tokens */
139 int
140 _PyPegen_seq_count_dots(asdl_seq *seq)
141 {
142 int number_of_dots = 0;
143 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
144 Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
145 switch (current_expr->type) {
146 case ELLIPSIS:
147 number_of_dots += 3;
148 break;
149 case DOT:
150 number_of_dots += 1;
151 break;
152 default:
153 Py_UNREACHABLE();
154 }
155 }
156
157 return number_of_dots;
158 }
159
160 /* Creates an alias with '*' as the identifier name */
161 alias_ty
162 _PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
163 int end_col_offset, PyArena *arena) {
164 PyObject *str = PyUnicode_InternFromString("*");
165 if (!str) {
166 return NULL;
167 }
168 if (_PyArena_AddPyObject(p->arena, str) < 0) {
169 Py_DECREF(str);
170 return NULL;
171 }
172 return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
173 }
174
175 /* Creates a new asdl_seq* with the identifiers of all the names in seq */
176 asdl_identifier_seq *
177 _PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
178 {
179 Py_ssize_t len = asdl_seq_LEN(seq);
180 assert(len > 0);
181
182 asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
183 if (!new_seq) {
184 return NULL;
185 }
186 for (Py_ssize_t i = 0; i < len; i++) {
187 expr_ty e = asdl_seq_GET(seq, i);
188 asdl_seq_SET(new_seq, i, e->v.Name.id);
189 }
190 return new_seq;
191 }
192
193 /* Constructs a CmpopExprPair */
194 CmpopExprPair *
195 _PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
196 {
197 assert(expr != NULL);
198 CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
199 if (!a) {
200 return NULL;
201 }
202 a->cmpop = cmpop;
203 a->expr = expr;
204 return a;
205 }
206
207 asdl_int_seq *
208 _PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
209 {
210 Py_ssize_t len = asdl_seq_LEN(seq);
211 assert(len > 0);
212
213 asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
214 if (!new_seq) {
215 return NULL;
216 }
217 for (Py_ssize_t i = 0; i < len; i++) {
218 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
219 asdl_seq_SET(new_seq, i, pair->cmpop);
220 }
221 return new_seq;
222 }
223
224 asdl_expr_seq *
225 _PyPegen_get_exprs(Parser *p, asdl_seq *seq)
226 {
227 Py_ssize_t len = asdl_seq_LEN(seq);
228 assert(len > 0);
229
230 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
231 if (!new_seq) {
232 return NULL;
233 }
234 for (Py_ssize_t i = 0; i < len; i++) {
235 CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
236 asdl_seq_SET(new_seq, i, pair->expr);
237 }
238 return new_seq;
239 }
240
241 /* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
242 static asdl_expr_seq *
243 _set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
244 {
245 Py_ssize_t len = asdl_seq_LEN(seq);
246 if (len == 0) {
247 return NULL;
248 }
249
250 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
251 if (!new_seq) {
252 return NULL;
253 }
254 for (Py_ssize_t i = 0; i < len; i++) {
255 expr_ty e = asdl_seq_GET(seq, i);
256 expr_ty new_e = _PyPegen_set_expr_context(p, e, ctx);
257 if (!new_e) {
258 return NULL;
259 }
260 asdl_seq_SET(new_seq, i, new_e);
261 }
262 return new_seq;
263 }
264
265 static expr_ty
266 _set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
267 {
268 return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
269 }
270
271 static expr_ty
272 _set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
273 {
274 asdl_expr_seq *seq = _set_seq_context(p, e->v.Tuple.elts, ctx);
275 if (!seq && PyErr_Occurred()) {
276 return NULL;
277 }
278 return _PyAST_Tuple(seq, ctx, EXTRA_EXPR(e, e));
279 }
280
281 static expr_ty
282 _set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
283 {
284 asdl_expr_seq *seq = _set_seq_context(p, e->v.List.elts, ctx);
285 if (!seq && PyErr_Occurred()) {
286 return NULL;
287 }
288 return _PyAST_List(seq, ctx, EXTRA_EXPR(e, e));
289 }
290
291 static expr_ty
292 _set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
293 {
294 return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
295 ctx, EXTRA_EXPR(e, e));
296 }
297
298 static expr_ty
299 _set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
300 {
301 return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
302 ctx, EXTRA_EXPR(e, e));
303 }
304
305 static expr_ty
306 _set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
307 {
308 expr_ty inner = _PyPegen_set_expr_context(p, e->v.Starred.value, ctx);
309 if (!inner) {
310 return NULL;
311 }
312 return _PyAST_Starred(inner, ctx, EXTRA_EXPR(e, e));
313 }
314
315 /* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
316 expr_ty
317 _PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
318 {
319 assert(expr != NULL);
320
321 expr_ty new = NULL;
322 switch (expr->kind) {
323 case Name_kind:
324 new = _set_name_context(p, expr, ctx);
325 break;
326 case Tuple_kind:
327 new = _set_tuple_context(p, expr, ctx);
328 break;
329 case List_kind:
330 new = _set_list_context(p, expr, ctx);
331 break;
332 case Subscript_kind:
333 new = _set_subscript_context(p, expr, ctx);
334 break;
335 case Attribute_kind:
336 new = _set_attribute_context(p, expr, ctx);
337 break;
338 case Starred_kind:
339 new = _set_starred_context(p, expr, ctx);
340 break;
341 default:
342 new = expr;
343 }
344 return new;
345 }
346
347 /* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
348 KeyValuePair *
349 _PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
350 {
351 KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
352 if (!a) {
353 return NULL;
354 }
355 a->key = key;
356 a->value = value;
357 return a;
358 }
359
360 /* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
361 asdl_expr_seq *
362 _PyPegen_get_keys(Parser *p, asdl_seq *seq)
363 {
364 Py_ssize_t len = asdl_seq_LEN(seq);
365 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
366 if (!new_seq) {
367 return NULL;
368 }
369 for (Py_ssize_t i = 0; i < len; i++) {
370 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
371 asdl_seq_SET(new_seq, i, pair->key);
372 }
373 return new_seq;
374 }
375
376 /* Extracts all values from an asdl_seq* of KeyValuePair*'s */
377 asdl_expr_seq *
378 _PyPegen_get_values(Parser *p, asdl_seq *seq)
379 {
380 Py_ssize_t len = asdl_seq_LEN(seq);
381 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
382 if (!new_seq) {
383 return NULL;
384 }
385 for (Py_ssize_t i = 0; i < len; i++) {
386 KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
387 asdl_seq_SET(new_seq, i, pair->value);
388 }
389 return new_seq;
390 }
391
392 /* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
393 KeyPatternPair *
394 _PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
395 {
396 KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
397 if (!a) {
398 return NULL;
399 }
400 a->key = key;
401 a->pattern = pattern;
402 return a;
403 }
404
405 /* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
406 asdl_expr_seq *
407 _PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
408 {
409 Py_ssize_t len = asdl_seq_LEN(seq);
410 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
411 if (!new_seq) {
412 return NULL;
413 }
414 for (Py_ssize_t i = 0; i < len; i++) {
415 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
416 asdl_seq_SET(new_seq, i, pair->key);
417 }
418 return new_seq;
419 }
420
421 /* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
422 asdl_pattern_seq *
423 _PyPegen_get_patterns(Parser *p, asdl_seq *seq)
424 {
425 Py_ssize_t len = asdl_seq_LEN(seq);
426 asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
427 if (!new_seq) {
428 return NULL;
429 }
430 for (Py_ssize_t i = 0; i < len; i++) {
431 KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
432 asdl_seq_SET(new_seq, i, pair->pattern);
433 }
434 return new_seq;
435 }
436
437 /* Constructs a NameDefaultPair */
438 NameDefaultPair *
439 _PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
440 {
441 NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
442 if (!a) {
443 return NULL;
444 }
445 a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
446 if (!a->arg) {
447 return NULL;
448 }
449 a->value = value;
450 return a;
451 }
452
453 /* Constructs a SlashWithDefault */
454 SlashWithDefault *
455 _PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
456 {
457 SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
458 if (!a) {
459 return NULL;
460 }
461 a->plain_names = plain_names;
462 a->names_with_defaults = names_with_defaults;
463 return a;
464 }
465
466 /* Constructs a StarEtc */
467 StarEtc *
468 _PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
469 {
470 StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
471 if (!a) {
472 return NULL;
473 }
474 a->vararg = vararg;
475 a->kwonlyargs = kwonlyargs;
476 a->kwarg = kwarg;
477 return a;
478 }
479
480 asdl_seq *
481 _PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
482 {
483 Py_ssize_t first_len = asdl_seq_LEN(a);
484 Py_ssize_t second_len = asdl_seq_LEN(b);
485 asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
486 if (!new_seq) {
487 return NULL;
488 }
489
490 int k = 0;
491 for (Py_ssize_t i = 0; i < first_len; i++) {
492 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
493 }
494 for (Py_ssize_t i = 0; i < second_len; i++) {
495 asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
496 }
497
498 return new_seq;
499 }
500
501 static asdl_arg_seq*
502 _get_names(Parser *p, asdl_seq *names_with_defaults)
503 {
504 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
505 asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
506 if (!seq) {
507 return NULL;
508 }
509 for (Py_ssize_t i = 0; i < len; i++) {
510 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
511 asdl_seq_SET(seq, i, pair->arg);
512 }
513 return seq;
514 }
515
516 static asdl_expr_seq *
517 _get_defaults(Parser *p, asdl_seq *names_with_defaults)
518 {
519 Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
520 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
521 if (!seq) {
522 return NULL;
523 }
524 for (Py_ssize_t i = 0; i < len; i++) {
525 NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
526 asdl_seq_SET(seq, i, pair->value);
527 }
528 return seq;
529 }
530
531 static int
532 _make_posonlyargs(Parser *p,
533 asdl_arg_seq *slash_without_default,
534 SlashWithDefault *slash_with_default,
535 asdl_arg_seq **posonlyargs) {
536 if (slash_without_default != NULL) {
537 *posonlyargs = slash_without_default;
538 }
539 else if (slash_with_default != NULL) {
540 asdl_arg_seq *slash_with_default_names =
541 _get_names(p, slash_with_default->names_with_defaults);
542 if (!slash_with_default_names) {
543 return -1;
544 }
545 *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
546 p,
547 (asdl_seq*)slash_with_default->plain_names,
548 (asdl_seq*)slash_with_default_names);
549 }
550 else {
551 *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
552 }
553 return *posonlyargs == NULL ? -1 : 0;
554 }
555
556 static int
557 _make_posargs(Parser *p,
558 asdl_arg_seq *plain_names,
559 asdl_seq *names_with_default,
560 asdl_arg_seq **posargs) {
561 if (plain_names != NULL && names_with_default != NULL) {
562 asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
563 if (!names_with_default_names) {
564 return -1;
565 }
566 *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
567 p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
568 }
569 else if (plain_names == NULL && names_with_default != NULL) {
570 *posargs = _get_names(p, names_with_default);
571 }
572 else if (plain_names != NULL && names_with_default == NULL) {
573 *posargs = plain_names;
574 }
575 else {
576 *posargs = _Py_asdl_arg_seq_new(0, p->arena);
577 }
578 return *posargs == NULL ? -1 : 0;
579 }
580
581 static int
582 _make_posdefaults(Parser *p,
583 SlashWithDefault *slash_with_default,
584 asdl_seq *names_with_default,
585 asdl_expr_seq **posdefaults) {
586 if (slash_with_default != NULL && names_with_default != NULL) {
587 asdl_expr_seq *slash_with_default_values =
588 _get_defaults(p, slash_with_default->names_with_defaults);
589 if (!slash_with_default_values) {
590 return -1;
591 }
592 asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
593 if (!names_with_default_values) {
594 return -1;
595 }
596 *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
597 p,
598 (asdl_seq*)slash_with_default_values,
599 (asdl_seq*)names_with_default_values);
600 }
601 else if (slash_with_default == NULL && names_with_default != NULL) {
602 *posdefaults = _get_defaults(p, names_with_default);
603 }
604 else if (slash_with_default != NULL && names_with_default == NULL) {
605 *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
606 }
607 else {
608 *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
609 }
610 return *posdefaults == NULL ? -1 : 0;
611 }
612
613 static int
614 _make_kwargs(Parser *p, StarEtc *star_etc,
615 asdl_arg_seq **kwonlyargs,
616 asdl_expr_seq **kwdefaults) {
617 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
618 *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
619 }
620 else {
621 *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
622 }
623
624 if (*kwonlyargs == NULL) {
625 return -1;
626 }
627
628 if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
629 *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
630 }
631 else {
632 *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
633 }
634
635 if (*kwdefaults == NULL) {
636 return -1;
637 }
638
639 return 0;
640 }
641
642 /* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
643 arguments_ty
644 _PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
645 SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
646 asdl_seq *names_with_default, StarEtc *star_etc)
647 {
648 asdl_arg_seq *posonlyargs;
649 if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
650 return NULL;
651 }
652
653 asdl_arg_seq *posargs;
654 if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
655 return NULL;
656 }
657
658 asdl_expr_seq *posdefaults;
659 if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
660 return NULL;
661 }
662
663 arg_ty vararg = NULL;
664 if (star_etc != NULL && star_etc->vararg != NULL) {
665 vararg = star_etc->vararg;
666 }
667
668 asdl_arg_seq *kwonlyargs;
669 asdl_expr_seq *kwdefaults;
670 if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
671 return NULL;
672 }
673
674 arg_ty kwarg = NULL;
675 if (star_etc != NULL && star_etc->kwarg != NULL) {
676 kwarg = star_etc->kwarg;
677 }
678
679 return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
680 kwdefaults, kwarg, posdefaults, p->arena);
681 }
682
683
684 /* Constructs an empty arguments_ty object, that gets used when a function accepts no
685 * arguments. */
686 arguments_ty
687 _PyPegen_empty_arguments(Parser *p)
688 {
689 asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
690 if (!posonlyargs) {
691 return NULL;
692 }
693 asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
694 if (!posargs) {
695 return NULL;
696 }
697 asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
698 if (!posdefaults) {
699 return NULL;
700 }
701 asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
702 if (!kwonlyargs) {
703 return NULL;
704 }
705 asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
706 if (!kwdefaults) {
707 return NULL;
708 }
709
710 return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
711 kwdefaults, NULL, posdefaults, p->arena);
712 }
713
714 /* Encapsulates the value of an operator_ty into an AugOperator struct */
715 AugOperator *
716 _PyPegen_augoperator(Parser *p, operator_ty kind)
717 {
718 AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
719 if (!a) {
720 return NULL;
721 }
722 a->kind = kind;
723 return a;
724 }
725
726 /* Construct a FunctionDef equivalent to function_def, but with decorators */
727 stmt_ty
728 _PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
729 {
730 assert(function_def != NULL);
731 if (function_def->kind == AsyncFunctionDef_kind) {
732 return _PyAST_AsyncFunctionDef(
733 function_def->v.AsyncFunctionDef.name,
734 function_def->v.AsyncFunctionDef.args,
735 function_def->v.AsyncFunctionDef.body, decorators,
736 function_def->v.AsyncFunctionDef.returns,
737 function_def->v.AsyncFunctionDef.type_comment,
738 function_def->v.AsyncFunctionDef.type_params,
739 function_def->lineno, function_def->col_offset,
740 function_def->end_lineno, function_def->end_col_offset, p->arena);
741 }
742
743 return _PyAST_FunctionDef(
744 function_def->v.FunctionDef.name,
745 function_def->v.FunctionDef.args,
746 function_def->v.FunctionDef.body, decorators,
747 function_def->v.FunctionDef.returns,
748 function_def->v.FunctionDef.type_comment,
749 function_def->v.FunctionDef.type_params,
750 function_def->lineno, function_def->col_offset,
751 function_def->end_lineno, function_def->end_col_offset, p->arena);
752 }
753
754 /* Construct a ClassDef equivalent to class_def, but with decorators */
755 stmt_ty
756 _PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
757 {
758 assert(class_def != NULL);
759 return _PyAST_ClassDef(
760 class_def->v.ClassDef.name,
761 class_def->v.ClassDef.bases, class_def->v.ClassDef.keywords,
762 class_def->v.ClassDef.body, decorators,
763 class_def->v.ClassDef.type_params,
764 class_def->lineno, class_def->col_offset, class_def->end_lineno,
765 class_def->end_col_offset, p->arena);
766 }
767
768 /* Construct a KeywordOrStarred */
769 KeywordOrStarred *
770 _PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
771 {
772 KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
773 if (!a) {
774 return NULL;
775 }
776 a->element = element;
777 a->is_keyword = is_keyword;
778 return a;
779 }
780
781 /* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
782 static int
783 _seq_number_of_starred_exprs(asdl_seq *seq)
784 {
785 int n = 0;
786 for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
787 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
788 if (!k->is_keyword) {
789 n++;
790 }
791 }
792 return n;
793 }
794
795 /* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
796 asdl_expr_seq *
797 _PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
798 {
799 int new_len = _seq_number_of_starred_exprs(kwargs);
800 if (new_len == 0) {
801 return NULL;
802 }
803 asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
804 if (!new_seq) {
805 return NULL;
806 }
807
808 int idx = 0;
809 for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
810 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
811 if (!k->is_keyword) {
812 asdl_seq_SET(new_seq, idx++, k->element);
813 }
814 }
815 return new_seq;
816 }
817
818 /* Return a new asdl_seq* with only the keywords in kwargs */
819 asdl_keyword_seq*
820 _PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
821 {
822 Py_ssize_t len = asdl_seq_LEN(kwargs);
823 Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
824 if (new_len == 0) {
825 return NULL;
826 }
827 asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
828 if (!new_seq) {
829 return NULL;
830 }
831
832 int idx = 0;
833 for (Py_ssize_t i = 0; i < len; i++) {
834 KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
835 if (k->is_keyword) {
836 asdl_seq_SET(new_seq, idx++, k->element);
837 }
838 }
839 return new_seq;
840 }
841
842 expr_ty
843 _PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
844 {
845 if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
846 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
847 return NULL;
848 }
849 return exp;
850 }
851
852 expr_ty
853 _PyPegen_ensure_real(Parser *p, expr_ty exp)
854 {
855 if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
856 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
857 return NULL;
858 }
859 return exp;
860 }
861
862 mod_ty
863 _PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
864 asdl_type_ignore_seq *type_ignores = NULL;
865 Py_ssize_t num = p->type_ignore_comments.num_items;
866 if (num > 0) {
867 // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
868 type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
869 if (type_ignores == NULL) {
870 return NULL;
871 }
872 for (int i = 0; i < num; i++) {
873 PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
874 if (tag == NULL) {
875 return NULL;
876 }
877 type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
878 tag, p->arena);
879 if (ti == NULL) {
880 return NULL;
881 }
882 asdl_seq_SET(type_ignores, i, ti);
883 }
884 }
885 return _PyAST_Module(a, type_ignores, p->arena);
886 }
887
888 PyObject *
889 _PyPegen_new_type_comment(Parser *p, const char *s)
890 {
891 PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
892 if (res == NULL) {
893 return NULL;
894 }
895 if (_PyArena_AddPyObject(p->arena, res) < 0) {
896 Py_DECREF(res);
897 return NULL;
898 }
899 return res;
900 }
901
902 arg_ty
903 _PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
904 {
905 if (tc == NULL) {
906 return a;
907 }
908 const char *bytes = PyBytes_AsString(tc->bytes);
909 if (bytes == NULL) {
910 return NULL;
911 }
912 PyObject *tco = _PyPegen_new_type_comment(p, bytes);
913 if (tco == NULL) {
914 return NULL;
915 }
916 return _PyAST_arg(a->arg, a->annotation, tco,
917 a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
918 p->arena);
919 }
920
921 /* Checks if the NOTEQUAL token is valid given the current parser flags
922 0 indicates success and nonzero indicates failure (an exception may be set) */
923 int
924 _PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
925 assert(t->bytes != NULL);
926 assert(t->type == NOTEQUAL);
927
928 const char* tok_str = PyBytes_AS_STRING(t->bytes);
929 if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
930 RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
931 return -1;
932 }
933 if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
934 return strcmp(tok_str, "!=");
935 }
936 return 0;
937 }
938
939 int
940 _PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
941 if (name->kind != Name_kind) {
942 return 0;
943 }
944 const char* candidates[2] = {"print", "exec"};
945 for (int i=0; i<2; i++) {
946 if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
947 return 1;
948 }
949 }
950 return 0;
951 }
952
953 static ResultTokenWithMetadata *
954 result_token_with_metadata(Parser *p, void *result, PyObject *metadata)
955 {
956 ResultTokenWithMetadata *res = _PyArena_Malloc(p->arena, sizeof(ResultTokenWithMetadata));
957 if (res == NULL) {
958 return NULL;
959 }
960 res->metadata = metadata;
961 res->result = result;
962 return res;
963 }
964
965 ResultTokenWithMetadata *
966 _PyPegen_check_fstring_conversion(Parser *p, Token* conv_token, expr_ty conv)
967 {
968 if (conv_token->lineno != conv->lineno || conv_token->end_col_offset != conv->col_offset) {
969 return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
970 conv_token, conv,
971 "f-string: conversion type must come right after the exclamation mark"
972 );
973 }
974 return result_token_with_metadata(p, conv, conv_token->metadata);
975 }
976
977 ResultTokenWithMetadata *
978 _PyPegen_setup_full_format_spec(Parser *p, Token *colon, asdl_expr_seq *spec, int lineno, int col_offset,
979 int end_lineno, int end_col_offset, PyArena *arena)
980 {
981 if (!spec) {
982 return NULL;
983 }
984
985 // This is needed to keep compatibility with 3.11, where an empty format
986 // spec is parsed as an *empty* JoinedStr node, instead of having an empty
987 // constant in it.
988 Py_ssize_t n_items = asdl_seq_LEN(spec);
989 Py_ssize_t non_empty_count = 0;
990 for (Py_ssize_t i = 0; i < n_items; i++) {
991 expr_ty item = asdl_seq_GET(spec, i);
992 non_empty_count += !(item->kind == Constant_kind &&
993 PyUnicode_CheckExact(item->v.Constant.value) &&
994 PyUnicode_GET_LENGTH(item->v.Constant.value) == 0);
995 }
996 if (non_empty_count != n_items) {
997 asdl_expr_seq *resized_spec =
998 _Py_asdl_expr_seq_new(non_empty_count, p->arena);
999 if (resized_spec == NULL) {
1000 return NULL;
1001 }
1002 Py_ssize_t j = 0;
1003 for (Py_ssize_t i = 0; i < n_items; i++) {
1004 expr_ty item = asdl_seq_GET(spec, i);
1005 if (item->kind == Constant_kind &&
1006 PyUnicode_CheckExact(item->v.Constant.value) &&
1007 PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1008 continue;
1009 }
1010 asdl_seq_SET(resized_spec, j++, item);
1011 }
1012 assert(j == non_empty_count);
1013 spec = resized_spec;
1014 }
1015 expr_ty res;
1016 Py_ssize_t n = asdl_seq_LEN(spec);
1017 if (n == 0 || (n == 1 && asdl_seq_GET(spec, 0)->kind == Constant_kind)) {
1018 res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno,
1019 end_col_offset, p->arena);
1020 } else {
1021 res = _PyPegen_concatenate_strings(p, spec,
1022 lineno, col_offset, end_lineno,
1023 end_col_offset, arena);
1024 }
1025 if (!res) {
1026 return NULL;
1027 }
1028 return result_token_with_metadata(p, res, colon->metadata);
1029 }
1030
1031 const char *
1032 _PyPegen_get_expr_name(expr_ty e)
1033 {
1034 assert(e != NULL);
1035 switch (e->kind) {
1036 case Attribute_kind:
1037 return "attribute";
1038 case Subscript_kind:
1039 return "subscript";
1040 case Starred_kind:
1041 return "starred";
1042 case Name_kind:
1043 return "name";
1044 case List_kind:
1045 return "list";
1046 case Tuple_kind:
1047 return "tuple";
1048 case Lambda_kind:
1049 return "lambda";
1050 case Call_kind:
1051 return "function call";
1052 case BoolOp_kind:
1053 case BinOp_kind:
1054 case UnaryOp_kind:
1055 return "expression";
1056 case GeneratorExp_kind:
1057 return "generator expression";
1058 case Yield_kind:
1059 case YieldFrom_kind:
1060 return "yield expression";
1061 case Await_kind:
1062 return "await expression";
1063 case ListComp_kind:
1064 return "list comprehension";
1065 case SetComp_kind:
1066 return "set comprehension";
1067 case DictComp_kind:
1068 return "dict comprehension";
1069 case Dict_kind:
1070 return "dict literal";
1071 case Set_kind:
1072 return "set display";
1073 case JoinedStr_kind:
1074 case FormattedValue_kind:
1075 return "f-string expression";
1076 case Constant_kind: {
1077 PyObject *value = e->v.Constant.value;
1078 if (value == Py_None) {
1079 return "None";
1080 }
1081 if (value == Py_False) {
1082 return "False";
1083 }
1084 if (value == Py_True) {
1085 return "True";
1086 }
1087 if (value == Py_Ellipsis) {
1088 return "ellipsis";
1089 }
1090 return "literal";
1091 }
1092 case Compare_kind:
1093 return "comparison";
1094 case IfExp_kind:
1095 return "conditional expression";
1096 case NamedExpr_kind:
1097 return "named expression";
1098 default:
1099 PyErr_Format(PyExc_SystemError,
1100 "unexpected expression in assignment %d (line %d)",
1101 e->kind, e->lineno);
1102 return NULL;
1103 }
1104 }
1105
1106 expr_ty
1107 _PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
1108 if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
1109 return comprehension->iter;
1110 }
1111 return PyPegen_last_item(comprehension->ifs, expr_ty);
1112 }
1113
1114 expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
1115 int lineno, int col_offset, int end_lineno,
1116 int end_col_offset, PyArena *arena) {
1117 Py_ssize_t args_len = asdl_seq_LEN(a);
1118 Py_ssize_t total_len = args_len;
1119
1120 if (b == NULL) {
1121 return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
1122 end_lineno, end_col_offset, arena);
1123
1124 }
1125
1126 asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
1127 if (!starreds && PyErr_Occurred()) {
1128 return NULL;
1129 }
1130
1131 asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
1132 if (!keywords && PyErr_Occurred()) {
1133 return NULL;
1134 }
1135
1136 if (starreds) {
1137 total_len += asdl_seq_LEN(starreds);
1138 }
1139
1140 asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
1141 if (args == NULL) {
1142 return NULL;
1143 }
1144
1145 Py_ssize_t i = 0;
1146 for (i = 0; i < args_len; i++) {
1147 asdl_seq_SET(args, i, asdl_seq_GET(a, i));
1148 }
1149 for (; i < total_len; i++) {
1150 asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
1151 }
1152
1153 return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
1154 col_offset, end_lineno, end_col_offset, arena);
1155 }
1156
1157 // AST Error reporting helpers
1158
1159 expr_ty
1160 _PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
1161 {
1162 if (e == NULL) {
1163 return NULL;
1164 }
1165
1166 #define VISIT_CONTAINER(CONTAINER, TYPE) do { \
1167 Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
1168 for (Py_ssize_t i = 0; i < len; i++) {\
1169 expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
1170 expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
1171 if (child != NULL) {\
1172 return child;\
1173 }\
1174 }\
1175 } while (0)
1176
1177 // We only need to visit List and Tuple nodes recursively as those
1178 // are the only ones that can contain valid names in targets when
1179 // they are parsed as expressions. Any other kind of expression
1180 // that is a container (like Sets or Dicts) is directly invalid and
1181 // we don't need to visit it recursively.
1182
1183 switch (e->kind) {
1184 case List_kind:
1185 VISIT_CONTAINER(e, List);
1186 return NULL;
1187 case Tuple_kind:
1188 VISIT_CONTAINER(e, Tuple);
1189 return NULL;
1190 case Starred_kind:
1191 if (targets_type == DEL_TARGETS) {
1192 return e;
1193 }
1194 return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
1195 case Compare_kind:
1196 // This is needed, because the `a in b` in `for a in b` gets parsed
1197 // as a comparison, and so we need to search the left side of the comparison
1198 // for invalid targets.
1199 if (targets_type == FOR_TARGETS) {
1200 cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
1201 if (cmpop == In) {
1202 return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
1203 }
1204 return NULL;
1205 }
1206 return e;
1207 case Name_kind:
1208 case Subscript_kind:
1209 case Attribute_kind:
1210 return NULL;
1211 default:
1212 return e;
1213 }
1214 }
1215
1216 void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
1217 int kwarg_unpacking = 0;
1218 for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
1219 keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
1220 if (!keyword->arg) {
1221 kwarg_unpacking = 1;
1222 }
1223 }
1224
1225 const char *msg = NULL;
1226 if (kwarg_unpacking) {
1227 msg = "positional argument follows keyword argument unpacking";
1228 } else {
1229 msg = "positional argument follows keyword argument";
1230 }
1231
1232 return RAISE_SYNTAX_ERROR(msg);
1233 }
1234
1235 void *
1236 _PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions)
1237 {
1238 /* The rule that calls this function is 'args for_if_clauses'.
1239 For the input f(L, x for x in y), L and x are in args and
1240 the for is parsed as a for_if_clause. We have to check if
1241 len <= 1, so that input like dict((a, b) for a, b in x)
1242 gets successfully parsed and then we pass the last
1243 argument (x in the above example) as the location of the
1244 error */
1245 Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
1246 if (len <= 1) {
1247 return NULL;
1248 }
1249
1250 comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
1251
1252 return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1253 (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
1254 _PyPegen_get_last_comprehension_item(last_comprehension),
1255 "Generator expression must be parenthesized"
1256 );
1257 }
1258
1259 // Fstring stuff
1260
1261 static expr_ty
1262 _PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant, Token* token) {
1263 assert(PyUnicode_CheckExact(constant->v.Constant.value));
1264
1265 const char* bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
1266 if (bstr == NULL) {
1267 return NULL;
1268 }
1269
1270 size_t len;
1271 if (strcmp(bstr, "{{") == 0 || strcmp(bstr, "}}") == 0) {
1272 len = 1;
1273 } else {
1274 len = strlen(bstr);
1275 }
1276
1277 is_raw = is_raw || strchr(bstr, '\\') == NULL;
1278 PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
1279 if (str == NULL) {
1280 _Pypegen_raise_decode_error(p);
1281 return NULL;
1282 }
1283 if (_PyArena_AddPyObject(p->arena, str) < 0) {
1284 Py_DECREF(str);
1285 return NULL;
1286 }
1287 return _PyAST_Constant(str, NULL, constant->lineno, constant->col_offset,
1288 constant->end_lineno, constant->end_col_offset,
1289 p->arena);
1290 }
1291
1292 expr_ty
1293 _PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* expr, Token*b) {
1294
1295 /* The parser might put multiple f-string values into an individual
1296 * JoinedStr node at the top level due to stuff like f-string debugging
1297 * expressions. This function flattens those and promotes them to the
1298 * upper level. Only simplifies AST, but the compiler already takes care
1299 * of the regular output, so this is not necessary if you are not going
1300 * to expose the output AST to Python level. */
1301
1302 Py_ssize_t n_items = asdl_seq_LEN(expr);
1303 Py_ssize_t total_items = n_items;
1304 for (Py_ssize_t i = 0; i < n_items; i++) {
1305 expr_ty item = asdl_seq_GET(expr, i);
1306 if (item->kind == JoinedStr_kind) {
1307 total_items += asdl_seq_LEN(item->v.JoinedStr.values) - 1;
1308 }
1309 }
1310
1311 const char* quote_str = PyBytes_AsString(a->bytes);
1312 if (quote_str == NULL) {
1313 return NULL;
1314 }
1315 int is_raw = strpbrk(quote_str, "rR") != NULL;
1316
1317 asdl_expr_seq *seq = _Py_asdl_expr_seq_new(total_items, p->arena);
1318 if (seq == NULL) {
1319 return NULL;
1320 }
1321
1322 Py_ssize_t index = 0;
1323 for (Py_ssize_t i = 0; i < n_items; i++) {
1324 expr_ty item = asdl_seq_GET(expr, i);
1325
1326 // This should correspond to a JoinedStr node of two elements
1327 // created _PyPegen_formatted_value. This situation can only be the result of
1328 // a f-string debug expression where the first element is a constant with the text and the second
1329 // a formatted value with the expression.
1330 if (item->kind == JoinedStr_kind) {
1331 asdl_expr_seq *values = item->v.JoinedStr.values;
1332 if (asdl_seq_LEN(values) != 2) {
1333 PyErr_Format(PyExc_SystemError,
1334 "unexpected JoinedStr node without debug data in f-string at line %d",
1335 item->lineno);
1336 return NULL;
1337 }
1338
1339 expr_ty first = asdl_seq_GET(values, 0);
1340 assert(first->kind == Constant_kind);
1341 asdl_seq_SET(seq, index++, first);
1342
1343 expr_ty second = asdl_seq_GET(values, 1);
1344 assert(second->kind == FormattedValue_kind);
1345 asdl_seq_SET(seq, index++, second);
1346
1347 continue;
1348 }
1349
1350 if (item->kind == Constant_kind) {
1351 item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
1352 if (item == NULL) {
1353 return NULL;
1354 }
1355
1356 /* Tokenizer emits string parts even when the underlying string
1357 might become an empty value (e.g. FSTRING_MIDDLE with the value \\n)
1358 so we need to check for them and simplify it here. */
1359 if (PyUnicode_CheckExact(item->v.Constant.value)
1360 && PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1361 continue;
1362 }
1363 }
1364 asdl_seq_SET(seq, index++, item);
1365 }
1366
1367 asdl_expr_seq *resized_exprs;
1368 if (index != total_items) {
1369 resized_exprs = _Py_asdl_expr_seq_new(index, p->arena);
1370 if (resized_exprs == NULL) {
1371 return NULL;
1372 }
1373 for (Py_ssize_t i = 0; i < index; i++) {
1374 asdl_seq_SET(resized_exprs, i, asdl_seq_GET(seq, i));
1375 }
1376 }
1377 else {
1378 resized_exprs = seq;
1379 }
1380
1381 return _PyAST_JoinedStr(resized_exprs, a->lineno, a->col_offset,
1382 b->end_lineno, b->end_col_offset,
1383 p->arena);
1384 }
1385
1386 expr_ty _PyPegen_decoded_constant_from_token(Parser* p, Token* tok) {
1387 Py_ssize_t bsize;
1388 char* bstr;
1389 if (PyBytes_AsStringAndSize(tok->bytes, &bstr, &bsize) == -1) {
1390 return NULL;
1391 }
1392
1393 // Check if we're inside a raw f-string for format spec decoding
1394 int is_raw = 0;
1395 if (INSIDE_FSTRING(p->tok)) {
1396 tokenizer_mode *mode = TOK_GET_MODE(p->tok);
1397 is_raw = mode->f_string_raw;
1398 }
1399
1400 PyObject* str = _PyPegen_decode_string(p, is_raw, bstr, bsize, tok);
1401 if (str == NULL) {
1402 return NULL;
1403 }
1404 if (_PyArena_AddPyObject(p->arena, str) < 0) {
1405 Py_DECREF(str);
1406 return NULL;
1407 }
1408 return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1409 tok->end_lineno, tok->end_col_offset,
1410 p->arena);
1411 }
1412
1413 expr_ty _PyPegen_constant_from_token(Parser* p, Token* tok) {
1414 char* bstr = PyBytes_AsString(tok->bytes);
1415 if (bstr == NULL) {
1416 return NULL;
1417 }
1418 PyObject* str = PyUnicode_FromString(bstr);
1419 if (str == NULL) {
1420 return NULL;
1421 }
1422 if (_PyArena_AddPyObject(p->arena, str) < 0) {
1423 Py_DECREF(str);
1424 return NULL;
1425 }
1426 return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1427 tok->end_lineno, tok->end_col_offset,
1428 p->arena);
1429 }
1430
1431 expr_ty _PyPegen_constant_from_string(Parser* p, Token* tok) {
1432 char* the_str = PyBytes_AsString(tok->bytes);
1433 if (the_str == NULL) {
1434 return NULL;
1435 }
1436 PyObject *s = _PyPegen_parse_string(p, tok);
1437 if (s == NULL) {
1438 _Pypegen_raise_decode_error(p);
1439 return NULL;
1440 }
1441 if (_PyArena_AddPyObject(p->arena, s) < 0) {
1442 Py_DECREF(s);
1443 return NULL;
1444 }
1445 PyObject *kind = NULL;
1446 if (the_str && the_str[0] == 'u') {
1447 kind = _PyPegen_new_identifier(p, "u");
1448 if (kind == NULL) {
1449 return NULL;
1450 }
1451 }
1452 return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno, tok->end_col_offset, p->arena);
1453 }
1454
1455 expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug, ResultTokenWithMetadata *conversion,
1456 ResultTokenWithMetadata *format, Token *closing_brace, int lineno, int col_offset,
1457 int end_lineno, int end_col_offset, PyArena *arena) {
1458 int conversion_val = -1;
1459 if (conversion != NULL) {
1460 expr_ty conversion_expr = (expr_ty) conversion->result;
1461 assert(conversion_expr->kind == Name_kind);
1462 Py_UCS4 first = PyUnicode_READ_CHAR(conversion_expr->v.Name.id, 0);
1463
1464 if (PyUnicode_GET_LENGTH(conversion_expr->v.Name.id) > 1 ||
1465 !(first == 's' || first == 'r' || first == 'a')) {
1466 RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conversion_expr,
1467 "f-string: invalid conversion character %R: expected 's', 'r', or 'a'",
1468 conversion_expr->v.Name.id);
1469 return NULL;
1470 }
1471
1472 conversion_val = Py_SAFE_DOWNCAST(first, Py_UCS4, int);
1473 }
1474 else if (debug && !format) {
1475 /* If no conversion is specified, use !r for debug expressions */
1476 conversion_val = (int)'r';
1477 }
1478
1479 expr_ty formatted_value = _PyAST_FormattedValue(
1480 expression, conversion_val, format ? (expr_ty) format->result : NULL,
1481 lineno, col_offset, end_lineno,
1482 end_col_offset, arena
1483 );
1484
1485 if (!formatted_value) {
1486 return NULL;
1487 }
1488 if (debug) {
1489 /* Find the non whitespace token after the "=" */
1490 int debug_end_line, debug_end_offset;
1491 PyObject *debug_metadata;
1492
1493 if (conversion) {
1494 debug_end_line = ((expr_ty) conversion->result)->lineno;
1495 debug_end_offset = ((expr_ty) conversion->result)->col_offset;
1496 debug_metadata = conversion->metadata;
1497 }
1498 else if (format) {
1499 debug_end_line = ((expr_ty) format->result)->lineno;
1500 debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1501 debug_metadata = format->metadata;
1502 }
1503 else {
1504 debug_end_line = end_lineno;
1505 debug_end_offset = end_col_offset;
1506 debug_metadata = closing_brace->metadata;
1507 }
1508 expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1509 debug_end_offset - 1, p->arena);
1510 if (!debug_text) {
1511 return NULL;
1512 }
1513
1514 asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1515 if (values == NULL) {
1516 return NULL;
1517 }
1518 asdl_seq_SET(values, 0, debug_text);
1519 asdl_seq_SET(values, 1, formatted_value);
1520 return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1521 }
1522 else {
1523 return formatted_value;
1524 }
1525 }
1526
1527 expr_ty
1528 _PyPegen_concatenate_strings(Parser *p, asdl_expr_seq *strings,
1529 int lineno, int col_offset, int end_lineno,
1530 int end_col_offset, PyArena *arena)
1531 {
1532 Py_ssize_t len = asdl_seq_LEN(strings);
1533 assert(len > 0);
1534
1535 int f_string_found = 0;
1536 int unicode_string_found = 0;
1537 int bytes_found = 0;
1538
1539 Py_ssize_t i = 0;
1540 Py_ssize_t n_flattened_elements = 0;
1541 for (i = 0; i < len; i++) {
1542 expr_ty elem = asdl_seq_GET(strings, i);
1543 switch(elem->kind) {
1544 case Constant_kind:
1545 if (PyBytes_CheckExact(elem->v.Constant.value)) {
1546 bytes_found = 1;
1547 } else {
1548 unicode_string_found = 1;
1549 }
1550 n_flattened_elements++;
1551 break;
1552 case JoinedStr_kind:
1553 n_flattened_elements += asdl_seq_LEN(elem->v.JoinedStr.values);
1554 f_string_found = 1;
1555 break;
1556 default:
1557 n_flattened_elements++;
1558 f_string_found = 1;
1559 break;
1560 }
1561 }
1562
1563 if ((unicode_string_found || f_string_found) && bytes_found) {
1564 RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1565 return NULL;
1566 }
1567
1568 if (bytes_found) {
1569 PyObject* res = PyBytes_FromString("");
1570
1571 /* Bytes literals never get a kind, but just for consistency
1572 since they are represented as Constant nodes, we'll mirror
1573 the same behavior as unicode strings for determining the
1574 kind. */
1575 PyObject* kind = asdl_seq_GET(strings, 0)->v.Constant.kind;
1576 for (i = 0; i < len; i++) {
1577 expr_ty elem = asdl_seq_GET(strings, i);
1578 PyBytes_Concat(&res, elem->v.Constant.value);
1579 }
1580 if (!res || _PyArena_AddPyObject(arena, res) < 0) {
1581 Py_XDECREF(res);
1582 return NULL;
1583 }
1584 return _PyAST_Constant(res, kind, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1585 }
1586
1587 if (!f_string_found && len == 1) {
1588 return asdl_seq_GET(strings, 0);
1589 }
1590
1591 asdl_expr_seq* flattened = _Py_asdl_expr_seq_new(n_flattened_elements, p->arena);
1592 if (flattened == NULL) {
1593 return NULL;
1594 }
1595
1596 /* build flattened list */
1597 Py_ssize_t current_pos = 0;
1598 Py_ssize_t j = 0;
1599 for (i = 0; i < len; i++) {
1600 expr_ty elem = asdl_seq_GET(strings, i);
1601 switch(elem->kind) {
1602 case JoinedStr_kind:
1603 for (j = 0; j < asdl_seq_LEN(elem->v.JoinedStr.values); j++) {
1604 expr_ty subvalue = asdl_seq_GET(elem->v.JoinedStr.values, j);
1605 if (subvalue == NULL) {
1606 return NULL;
1607 }
1608 asdl_seq_SET(flattened, current_pos++, subvalue);
1609 }
1610 break;
1611 default:
1612 asdl_seq_SET(flattened, current_pos++, elem);
1613 break;
1614 }
1615 }
1616
1617 /* calculate folded element count */
1618 Py_ssize_t n_elements = 0;
1619 int prev_is_constant = 0;
1620 for (i = 0; i < n_flattened_elements; i++) {
1621 expr_ty elem = asdl_seq_GET(flattened, i);
1622
1623 /* The concatenation of a FormattedValue and an empty Contant should
1624 lead to the FormattedValue itself. Thus, we will not take any empty
1625 constants into account, just as in `_PyPegen_joined_str` */
1626 if (f_string_found && elem->kind == Constant_kind &&
1627 PyUnicode_CheckExact(elem->v.Constant.value) &&
1628 PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0)
1629 continue;
1630
1631 if (!prev_is_constant || elem->kind != Constant_kind) {
1632 n_elements++;
1633 }
1634 prev_is_constant = elem->kind == Constant_kind;
1635 }
1636
1637 asdl_expr_seq* values = _Py_asdl_expr_seq_new(n_elements, p->arena);
1638 if (values == NULL) {
1639 return NULL;
1640 }
1641
1642 /* build folded list */
1643 _PyUnicodeWriter writer;
1644 current_pos = 0;
1645 for (i = 0; i < n_flattened_elements; i++) {
1646 expr_ty elem = asdl_seq_GET(flattened, i);
1647
1648 /* if the current elem and the following are constants,
1649 fold them and all consequent constants */
1650 if (elem->kind == Constant_kind) {
1651 if (i + 1 < n_flattened_elements &&
1652 asdl_seq_GET(flattened, i + 1)->kind == Constant_kind) {
1653 expr_ty first_elem = elem;
1654
1655 /* When a string is getting concatenated, the kind of the string
1656 is determined by the first string in the concatenation
1657 sequence.
1658
1659 u"abc" "def" -> u"abcdef"
1660 "abc" u"abc" -> "abcabc" */
1661 PyObject *kind = elem->v.Constant.kind;
1662
1663 _PyUnicodeWriter_Init(&writer);
1664 expr_ty last_elem = elem;
1665 for (j = i; j < n_flattened_elements; j++) {
1666 expr_ty current_elem = asdl_seq_GET(flattened, j);
1667 if (current_elem->kind == Constant_kind) {
1668 if (_PyUnicodeWriter_WriteStr(
1669 &writer, current_elem->v.Constant.value)) {
1670 _PyUnicodeWriter_Dealloc(&writer);
1671 return NULL;
1672 }
1673 last_elem = current_elem;
1674 } else {
1675 break;
1676 }
1677 }
1678 i = j - 1;
1679
1680 PyObject *concat_str = _PyUnicodeWriter_Finish(&writer);
1681 if (concat_str == NULL) {
1682 _PyUnicodeWriter_Dealloc(&writer);
1683 return NULL;
1684 }
1685 if (_PyArena_AddPyObject(p->arena, concat_str) < 0) {
1686 Py_DECREF(concat_str);
1687 return NULL;
1688 }
1689 elem = _PyAST_Constant(concat_str, kind, first_elem->lineno,
1690 first_elem->col_offset,
1691 last_elem->end_lineno,
1692 last_elem->end_col_offset, p->arena);
1693 if (elem == NULL) {
1694 return NULL;
1695 }
1696 }
1697
1698 /* Drop all empty contanst strings */
1699 if (f_string_found &&
1700 PyUnicode_CheckExact(elem->v.Constant.value) &&
1701 PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0) {
1702 continue;
1703 }
1704 }
1705
1706 asdl_seq_SET(values, current_pos++, elem);
1707 }
1708
1709 if (!f_string_found) {
1710 assert(n_elements == 1);
1711 expr_ty elem = asdl_seq_GET(values, 0);
1712 assert(elem->kind == Constant_kind);
1713 return elem;
1714 }
1715
1716 assert(current_pos == n_elements);
1717 return _PyAST_JoinedStr(values, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1718 }
1719
1720 stmt_ty
1721 _PyPegen_checked_future_import(Parser *p, identifier module, asdl_alias_seq * names, int level,
1722 int lineno, int col_offset, int end_lineno, int end_col_offset,
1723 PyArena *arena) {
1724 if (level == 0 && PyUnicode_CompareWithASCIIString(module, "__future__") == 0) {
1725 for (Py_ssize_t i = 0; i < asdl_seq_LEN(names); i++) {
1726 alias_ty alias = asdl_seq_GET(names, i);
1727 if (PyUnicode_CompareWithASCIIString(alias->name, "barry_as_FLUFL") == 0) {
1728 p->flags |= PyPARSE_BARRY_AS_BDFL;
1729 }
1730 }
1731 }
1732 return _PyAST_ImportFrom(module, names, level, lineno, col_offset, end_lineno, end_col_offset, arena);
1733 }