Coverage Report

Created: 2026-06-07 06:26

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