Coverage Report

Created: 2025-08-26 06:26

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