Coverage Report

Created: 2025-08-24 07:03

/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.3k
{
13
76.3k
    return &_PyRuntime.parser.dummy_name;
14
76.3k
}
15
16
/* Creates a single-element asdl_seq* that contains a */
17
asdl_seq *
18
_PyPegen_singleton_seq(Parser *p, void *a)
19
178k
{
20
178k
    assert(a != NULL);
21
178k
    asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
22
178k
    if (!seq) {
23
0
        return NULL;
24
0
    }
25
178k
    asdl_seq_SET_UNTYPED(seq, 0, a);
26
178k
    return seq;
27
178k
}
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
382k
{
33
382k
    assert(a != NULL);
34
382k
    if (!seq) {
35
8.77k
        return _PyPegen_singleton_seq(p, a);
36
8.77k
    }
37
38
373k
    asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
39
373k
    if (!new_seq) {
40
0
        return NULL;
41
0
    }
42
43
373k
    asdl_seq_SET_UNTYPED(new_seq, 0, a);
44
668k
    for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
45
295k
        asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
46
295k
    }
47
373k
    return new_seq;
48
373k
}
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.3k
{
74
29.3k
    Py_ssize_t size = 0;
75
145k
    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.3k
    return size;
80
29.3k
}
81
82
/* Flattens an asdl_seq* of asdl_seq*s */
83
asdl_seq *
84
_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
85
29.3k
{
86
29.3k
    Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
87
29.3k
    assert(flattened_seq_size > 0);
88
89
29.3k
    asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
90
29.3k
    if (!flattened_seq) {
91
0
        return NULL;
92
0
    }
93
94
29.3k
    int flattened_seq_idx = 0;
95
145k
    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
238k
        for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
98
122k
            asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
99
122k
        }
100
115k
    }
101
29.3k
    assert(flattened_seq_idx == flattened_seq_size);
102
103
29.3k
    return flattened_seq;
104
29.3k
}
105
106
void *
107
_PyPegen_seq_last_item(asdl_seq *seq)
108
1.14k
{
109
1.14k
    Py_ssize_t len = asdl_seq_LEN(seq);
110
1.14k
    return asdl_seq_GET_UNTYPED(seq, len - 1);
111
1.14k
}
112
113
void *
114
_PyPegen_seq_first_item(asdl_seq *seq)
115
1.07k
{
116
1.07k
    return asdl_seq_GET_UNTYPED(seq, 0);
117
1.07k
}
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.48k
{
123
2.48k
    assert(first_name != NULL && second_name != NULL);
124
2.48k
    PyObject *uni = PyUnicode_FromFormat("%U.%U",
125
2.48k
            first_name->v.Name.id, second_name->v.Name.id);
126
2.48k
    if (!uni) {
127
0
        return NULL;
128
0
    }
129
2.48k
    PyInterpreterState *interp = _PyInterpreterState_GET();
130
2.48k
    _PyUnicode_InternImmortal(interp, &uni);
131
2.48k
    if (_PyArena_AddPyObject(p->arena, uni) < 0) {
132
0
        Py_DECREF(uni);
133
0
        return NULL;
134
0
    }
135
136
2.48k
    return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
137
2.48k
}
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.31k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
145
4.16k
        Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
146
4.16k
        switch (current_expr->type) {
147
1.78k
            case ELLIPSIS:
148
1.78k
                number_of_dots += 3;
149
1.78k
                break;
150
2.38k
            case DOT:
151
2.38k
                number_of_dots += 1;
152
2.38k
                break;
153
0
            default:
154
0
                Py_UNREACHABLE();
155
4.16k
        }
156
4.16k
    }
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
607
                        int end_col_offset, PyArena *arena) {
165
607
    PyObject *str = PyUnicode_InternFromString("*");
166
607
    if (!str) {
167
0
        return NULL;
168
0
    }
169
607
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
170
0
        Py_DECREF(str);
171
0
        return NULL;
172
0
    }
173
607
    return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
174
607
}
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.14k
{
180
2.14k
    Py_ssize_t len = asdl_seq_LEN(seq);
181
2.14k
    assert(len > 0);
182
183
2.14k
    asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
184
2.14k
    if (!new_seq) {
185
0
        return NULL;
186
0
    }
187
7.67k
    for (Py_ssize_t i = 0; i < len; i++) {
188
5.53k
        expr_ty e = asdl_seq_GET(seq, i);
189
5.53k
        asdl_seq_SET(new_seq, i, e->v.Name.id);
190
5.53k
    }
191
2.14k
    return new_seq;
192
2.14k
}
193
194
/* Constructs a CmpopExprPair */
195
CmpopExprPair *
196
_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
197
23.0k
{
198
23.0k
    assert(expr != NULL);
199
23.0k
    CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
200
23.0k
    if (!a) {
201
0
        return NULL;
202
0
    }
203
23.0k
    a->cmpop = cmpop;
204
23.0k
    a->expr = expr;
205
23.0k
    return a;
206
23.0k
}
207
208
asdl_int_seq *
209
_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
210
10.1k
{
211
10.1k
    Py_ssize_t len = asdl_seq_LEN(seq);
212
10.1k
    assert(len > 0);
213
214
10.1k
    asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
215
10.1k
    if (!new_seq) {
216
0
        return NULL;
217
0
    }
218
32.3k
    for (Py_ssize_t i = 0; i < len; i++) {
219
22.2k
        CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
220
22.2k
        asdl_seq_SET(new_seq, i, pair->cmpop);
221
22.2k
    }
222
10.1k
    return new_seq;
223
10.1k
}
224
225
asdl_expr_seq *
226
_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
227
10.1k
{
228
10.1k
    Py_ssize_t len = asdl_seq_LEN(seq);
229
10.1k
    assert(len > 0);
230
231
10.1k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
232
10.1k
    if (!new_seq) {
233
0
        return NULL;
234
0
    }
235
32.3k
    for (Py_ssize_t i = 0; i < len; i++) {
236
22.2k
        CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
237
22.2k
        asdl_seq_SET(new_seq, i, pair->expr);
238
22.2k
    }
239
10.1k
    return new_seq;
240
10.1k
}
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.66k
{
246
7.66k
    Py_ssize_t len = asdl_seq_LEN(seq);
247
7.66k
    if (len == 0) {
248
3.90k
        return NULL;
249
3.90k
    }
250
251
3.75k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
252
3.75k
    if (!new_seq) {
253
0
        return NULL;
254
0
    }
255
11.2k
    for (Py_ssize_t i = 0; i < len; i++) {
256
7.53k
        expr_ty e = asdl_seq_GET(seq, i);
257
7.53k
        asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
258
7.53k
    }
259
3.75k
    return new_seq;
260
3.75k
}
261
262
static expr_ty
263
_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
264
216k
{
265
216k
    return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
266
216k
}
267
268
static expr_ty
269
_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
270
6.44k
{
271
6.44k
    return _PyAST_Tuple(
272
6.44k
            _set_seq_context(p, e->v.Tuple.elts, ctx),
273
6.44k
            ctx,
274
6.44k
            EXTRA_EXPR(e, e));
275
6.44k
}
276
277
static expr_ty
278
_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
279
1.22k
{
280
1.22k
    return _PyAST_List(
281
1.22k
            _set_seq_context(p, e->v.List.elts, ctx),
282
1.22k
            ctx,
283
1.22k
            EXTRA_EXPR(e, e));
284
1.22k
}
285
286
static expr_ty
287
_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
288
423
{
289
423
    return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
290
423
                            ctx, EXTRA_EXPR(e, e));
291
423
}
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
620
{
303
620
    return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
304
620
                          ctx, EXTRA_EXPR(e, e));
305
620
}
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
225k
{
311
225k
    assert(expr != NULL);
312
313
225k
    expr_ty new = NULL;
314
225k
    switch (expr->kind) {
315
216k
        case Name_kind:
316
216k
            new = _set_name_context(p, expr, ctx);
317
216k
            break;
318
6.44k
        case Tuple_kind:
319
6.44k
            new = _set_tuple_context(p, expr, ctx);
320
6.44k
            break;
321
1.22k
        case List_kind:
322
1.22k
            new = _set_list_context(p, expr, ctx);
323
1.22k
            break;
324
423
        case Subscript_kind:
325
423
            new = _set_subscript_context(p, expr, ctx);
326
423
            break;
327
80
        case Attribute_kind:
328
80
            new = _set_attribute_context(p, expr, ctx);
329
80
            break;
330
620
        case Starred_kind:
331
620
            new = _set_starred_context(p, expr, ctx);
332
620
            break;
333
0
        default:
334
0
            new = expr;
335
225k
    }
336
225k
    return new;
337
225k
}
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
46.3k
{
343
46.3k
    KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
344
46.3k
    if (!a) {
345
0
        return NULL;
346
0
    }
347
46.3k
    a->key = key;
348
46.3k
    a->value = value;
349
46.3k
    return a;
350
46.3k
}
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
3.97k
{
356
3.97k
    Py_ssize_t len = asdl_seq_LEN(seq);
357
3.97k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
358
3.97k
    if (!new_seq) {
359
0
        return NULL;
360
0
    }
361
39.1k
    for (Py_ssize_t i = 0; i < len; i++) {
362
35.1k
        KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
363
35.1k
        asdl_seq_SET(new_seq, i, pair->key);
364
35.1k
    }
365
3.97k
    return new_seq;
366
3.97k
}
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
3.97k
{
372
3.97k
    Py_ssize_t len = asdl_seq_LEN(seq);
373
3.97k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
374
3.97k
    if (!new_seq) {
375
0
        return NULL;
376
0
    }
377
39.1k
    for (Py_ssize_t i = 0; i < len; i++) {
378
35.1k
        KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
379
35.1k
        asdl_seq_SET(new_seq, i, pair->value);
380
35.1k
    }
381
3.97k
    return new_seq;
382
3.97k
}
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.5k
{
388
11.5k
    KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
389
11.5k
    if (!a) {
390
0
        return NULL;
391
0
    }
392
11.5k
    a->key = key;
393
11.5k
    a->pattern = pattern;
394
11.5k
    return a;
395
11.5k
}
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.88k
{
401
1.88k
    Py_ssize_t len = asdl_seq_LEN(seq);
402
1.88k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
403
1.88k
    if (!new_seq) {
404
0
        return NULL;
405
0
    }
406
4.74k
    for (Py_ssize_t i = 0; i < len; i++) {
407
2.85k
        KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
408
2.85k
        asdl_seq_SET(new_seq, i, pair->key);
409
2.85k
    }
410
1.88k
    return new_seq;
411
1.88k
}
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.88k
{
417
1.88k
    Py_ssize_t len = asdl_seq_LEN(seq);
418
1.88k
    asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
419
1.88k
    if (!new_seq) {
420
0
        return NULL;
421
0
    }
422
4.74k
    for (Py_ssize_t i = 0; i < len; i++) {
423
2.85k
        KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
424
2.85k
        asdl_seq_SET(new_seq, i, pair->pattern);
425
2.85k
    }
426
1.88k
    return new_seq;
427
1.88k
}
428
429
/* Constructs a NameDefaultPair */
430
NameDefaultPair *
431
_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
432
83.1k
{
433
83.1k
    NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
434
83.1k
    if (!a) {
435
0
        return NULL;
436
0
    }
437
83.1k
    a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
438
83.1k
    a->value = value;
439
83.1k
    return a;
440
83.1k
}
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.27k
{
459
6.27k
    StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
460
6.27k
    if (!a) {
461
0
        return NULL;
462
0
    }
463
6.27k
    a->vararg = vararg;
464
6.27k
    a->kwonlyargs = kwonlyargs;
465
6.27k
    a->kwarg = kwarg;
466
6.27k
    return a;
467
6.27k
}
468
469
asdl_seq *
470
_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
471
13.5k
{
472
13.5k
    Py_ssize_t first_len = asdl_seq_LEN(a);
473
13.5k
    Py_ssize_t second_len = asdl_seq_LEN(b);
474
13.5k
    asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
475
13.5k
    if (!new_seq) {
476
0
        return NULL;
477
0
    }
478
479
13.5k
    int k = 0;
480
36.1k
    for (Py_ssize_t i = 0; i < first_len; i++) {
481
22.5k
        asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
482
22.5k
    }
483
22.9k
    for (Py_ssize_t i = 0; i < second_len; i++) {
484
9.40k
        asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
485
9.40k
    }
486
487
13.5k
    return new_seq;
488
13.5k
}
489
490
static asdl_arg_seq*
491
_get_names(Parser *p, asdl_seq *names_with_defaults)
492
20.8k
{
493
20.8k
    Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
494
20.8k
    asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
495
20.8k
    if (!seq) {
496
0
        return NULL;
497
0
    }
498
36.2k
    for (Py_ssize_t i = 0; i < len; i++) {
499
15.3k
        NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
500
15.3k
        asdl_seq_SET(seq, i, pair->arg);
501
15.3k
    }
502
20.8k
    return seq;
503
20.8k
}
504
505
static asdl_expr_seq *
506
_get_defaults(Parser *p, asdl_seq *names_with_defaults)
507
20.8k
{
508
20.8k
    Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
509
20.8k
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
510
20.8k
    if (!seq) {
511
0
        return NULL;
512
0
    }
513
36.2k
    for (Py_ssize_t i = 0; i < len; i++) {
514
15.3k
        NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
515
15.3k
        asdl_seq_SET(seq, i, pair->value);
516
15.3k
    }
517
20.8k
    return seq;
518
20.8k
}
519
520
static int
521
_make_posonlyargs(Parser *p,
522
                  asdl_arg_seq *slash_without_default,
523
                  SlashWithDefault *slash_with_default,
524
19.1k
                  asdl_arg_seq **posonlyargs) {
525
19.1k
    if (slash_without_default != NULL) {
526
1.32k
        *posonlyargs = slash_without_default;
527
1.32k
    }
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.1k
    return *posonlyargs == NULL ? -1 : 0;
543
19.1k
}
544
545
static int
546
_make_posargs(Parser *p,
547
              asdl_arg_seq *plain_names,
548
              asdl_seq *names_with_default,
549
19.1k
              asdl_arg_seq **posargs) {
550
551
19.1k
    if (names_with_default != NULL) {
552
13.5k
        if (plain_names != NULL) {
553
9.02k
            asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
554
9.02k
            if (!names_with_default_names) {
555
0
                return -1;
556
0
            }
557
9.02k
            *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
558
9.02k
                    p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
559
9.02k
        }
560
4.55k
        else {
561
4.55k
            *posargs = _get_names(p, names_with_default);
562
4.55k
        }
563
13.5k
    }
564
5.56k
    else {
565
5.56k
        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.56k
        else {
572
5.56k
            *posargs = _Py_asdl_arg_seq_new(0, p->arena);
573
5.56k
        }
574
5.56k
    }
575
19.1k
    return *posargs == NULL ? -1 : 0;
576
19.1k
}
577
578
static int
579
_make_posdefaults(Parser *p,
580
                  SlashWithDefault *slash_with_default,
581
                  asdl_seq *names_with_default,
582
19.1k
                  asdl_expr_seq **posdefaults) {
583
19.1k
    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.0k
    else if (slash_with_default == NULL && names_with_default != NULL) {
599
11.5k
        *posdefaults = _get_defaults(p, names_with_default);
600
11.5k
    }
601
5.56k
    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.56k
    else {
605
5.56k
        *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
606
5.56k
    }
607
19.1k
    return *posdefaults == NULL ? -1 : 0;
608
19.1k
}
609
610
static int
611
_make_kwargs(Parser *p, StarEtc *star_etc,
612
             asdl_arg_seq **kwonlyargs,
613
19.1k
             asdl_expr_seq **kwdefaults) {
614
19.1k
    if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
615
5.21k
        *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
616
5.21k
    }
617
13.9k
    else {
618
13.9k
        *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
619
13.9k
    }
620
621
19.1k
    if (*kwonlyargs == NULL) {
622
0
        return -1;
623
0
    }
624
625
19.1k
    if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
626
5.21k
        *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
627
5.21k
    }
628
13.9k
    else {
629
13.9k
        *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
630
13.9k
    }
631
632
19.1k
    if (*kwdefaults == NULL) {
633
0
        return -1;
634
0
    }
635
636
19.1k
    return 0;
637
19.1k
}
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.1k
{
645
19.1k
    asdl_arg_seq *posonlyargs;
646
19.1k
    if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
647
0
        return NULL;
648
0
    }
649
650
19.1k
    asdl_arg_seq *posargs;
651
19.1k
    if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
652
0
        return NULL;
653
0
    }
654
655
19.1k
    asdl_expr_seq *posdefaults;
656
19.1k
    if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
657
0
        return NULL;
658
0
    }
659
660
19.1k
    arg_ty vararg = NULL;
661
19.1k
    if (star_etc != NULL && star_etc->vararg != NULL) {
662
3.08k
        vararg = star_etc->vararg;
663
3.08k
    }
664
665
19.1k
    asdl_arg_seq *kwonlyargs;
666
19.1k
    asdl_expr_seq *kwdefaults;
667
19.1k
    if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
668
0
        return NULL;
669
0
    }
670
671
19.1k
    arg_ty kwarg = NULL;
672
19.1k
    if (star_etc != NULL && star_etc->kwarg != NULL) {
673
1.14k
        kwarg = star_etc->kwarg;
674
1.14k
    }
675
676
19.1k
    return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
677
19.1k
                            kwdefaults, kwarg, posdefaults, p->arena);
678
19.1k
}
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.94k
{
715
2.94k
    AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
716
2.94k
    if (!a) {
717
0
        return NULL;
718
0
    }
719
2.94k
    a->kind = kind;
720
2.94k
    return a;
721
2.94k
}
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
972
{
727
972
    assert(function_def != NULL);
728
972
    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
763
    return _PyAST_FunctionDef(
741
763
        function_def->v.FunctionDef.name,
742
763
        function_def->v.FunctionDef.args,
743
763
        function_def->v.FunctionDef.body, decorators,
744
763
        function_def->v.FunctionDef.returns,
745
763
        function_def->v.FunctionDef.type_comment,
746
763
        function_def->v.FunctionDef.type_params,
747
763
        function_def->lineno, function_def->col_offset,
748
763
        function_def->end_lineno, function_def->end_col_offset, p->arena);
749
972
}
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
388
{
755
388
    assert(class_def != NULL);
756
388
    return _PyAST_ClassDef(
757
388
        class_def->v.ClassDef.name,
758
388
        class_def->v.ClassDef.bases, class_def->v.ClassDef.keywords,
759
388
        class_def->v.ClassDef.body, decorators,
760
388
        class_def->v.ClassDef.type_params,
761
388
        class_def->lineno, class_def->col_offset, class_def->end_lineno,
762
388
        class_def->end_col_offset, p->arena);
763
388
}
764
765
/* Construct a KeywordOrStarred */
766
KeywordOrStarred *
767
_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
768
36.7k
{
769
36.7k
    KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
770
36.7k
    if (!a) {
771
0
        return NULL;
772
0
    }
773
36.7k
    a->element = element;
774
36.7k
    a->is_keyword = is_keyword;
775
36.7k
    return a;
776
36.7k
}
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.3k
{
782
18.3k
    int n = 0;
783
57.6k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
784
39.3k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
785
39.3k
        if (!k->is_keyword) {
786
2.42k
            n++;
787
2.42k
        }
788
39.3k
    }
789
18.3k
    return n;
790
18.3k
}
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.15k
{
796
9.15k
    int new_len = _seq_number_of_starred_exprs(kwargs);
797
9.15k
    if (new_len == 0) {
798
8.64k
        return NULL;
799
8.64k
    }
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.15k
{
819
9.15k
    Py_ssize_t len = asdl_seq_LEN(kwargs);
820
9.15k
    Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
821
9.15k
    if (new_len == 0) {
822
0
        return NULL;
823
0
    }
824
9.15k
    asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
825
9.15k
    if (!new_seq) {
826
0
        return NULL;
827
0
    }
828
829
9.15k
    int idx = 0;
830
28.8k
    for (Py_ssize_t i = 0; i < len; i++) {
831
19.6k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
832
19.6k
        if (k->is_keyword) {
833
18.4k
            asdl_seq_SET(new_seq, idx++, k->element);
834
18.4k
        }
835
19.6k
    }
836
9.15k
    return new_seq;
837
9.15k
}
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.47k
_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
861
7.47k
    asdl_type_ignore_seq *type_ignores = NULL;
862
7.47k
    Py_ssize_t num = p->type_ignore_comments.num_items;
863
7.47k
    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.47k
    return _PyAST_Module(a, type_ignores, p->arena);
883
7.47k
}
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
158k
{
902
158k
    if (tc == NULL) {
903
158k
        return a;
904
158k
    }
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.46k
_PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
938
8.46k
    if (name->kind != Name_kind) {
939
2.46k
        return 0;
940
2.46k
    }
941
6.00k
    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.60k
    return 0;
948
6.00k
}
949
950
static ResultTokenWithMetadata *
951
result_token_with_metadata(Parser *p, void *result, PyObject *metadata)
952
7.44k
{
953
7.44k
    ResultTokenWithMetadata *res = _PyArena_Malloc(p->arena, sizeof(ResultTokenWithMetadata));
954
7.44k
    if (res == NULL) {
955
0
        return NULL;
956
0
    }
957
7.44k
    res->metadata = metadata;
958
7.44k
    res->result = result;
959
7.44k
    return res;
960
7.44k
}
961
962
ResultTokenWithMetadata *
963
_PyPegen_check_fstring_conversion(Parser *p, Token* conv_token, expr_ty conv)
964
1.60k
{
965
1.60k
    if (conv_token->lineno != conv->lineno || conv_token->end_col_offset != conv->col_offset) {
966
4
        return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
967
4
            conv_token, conv,
968
4
            "%c-string: conversion type must come right after the exclamation mark",
969
4
            TOK_GET_STRING_PREFIX(p->tok)
970
4
        );
971
4
    }
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.58k
    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
5.85k
{
990
5.85k
    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
5.85k
    Py_ssize_t n_items = asdl_seq_LEN(spec);
998
5.85k
    Py_ssize_t non_empty_count = 0;
999
17.0k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1000
11.2k
        expr_ty item = asdl_seq_GET(spec, i);
1001
11.2k
        non_empty_count += !(item->kind == Constant_kind &&
1002
11.2k
                             PyUnicode_CheckExact(item->v.Constant.value) &&
1003
11.2k
                             PyUnicode_GET_LENGTH(item->v.Constant.value) == 0);
1004
11.2k
    }
1005
5.85k
    if (non_empty_count != n_items) {
1006
1.93k
        asdl_expr_seq *resized_spec =
1007
1.93k
            _Py_asdl_expr_seq_new(non_empty_count, p->arena);
1008
1.93k
        if (resized_spec == NULL) {
1009
0
            return NULL;
1010
0
        }
1011
1.93k
        Py_ssize_t j = 0;
1012
5.80k
        for (Py_ssize_t i = 0; i < n_items; i++) {
1013
3.86k
            expr_ty item = asdl_seq_GET(spec, i);
1014
3.86k
            if (item->kind == Constant_kind &&
1015
3.86k
                PyUnicode_CheckExact(item->v.Constant.value) &&
1016
3.86k
                PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1017
1.93k
                continue;
1018
1.93k
            }
1019
1.93k
            asdl_seq_SET(resized_spec, j++, item);
1020
1.93k
        }
1021
1.93k
        assert(j == non_empty_count);
1022
1.93k
        spec = resized_spec;
1023
1.93k
    }
1024
5.85k
    expr_ty res;
1025
5.85k
    Py_ssize_t n = asdl_seq_LEN(spec);
1026
5.85k
    if (n == 0 || (n == 1 && asdl_seq_GET(spec, 0)->kind == Constant_kind)) {
1027
4.94k
        res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno,
1028
4.94k
                                    end_col_offset, p->arena);
1029
4.94k
    } else {
1030
914
        res = _PyPegen_concatenate_strings(p, spec,
1031
914
                             lineno, col_offset, end_lineno,
1032
914
                             end_col_offset, arena);
1033
914
    }
1034
5.85k
    if (!res) {
1035
0
        return NULL;
1036
0
    }
1037
5.85k
    return result_token_with_metadata(p, res, colon->metadata);
1038
5.85k
}
1039
1040
const char *
1041
_PyPegen_get_expr_name(expr_ty e)
1042
172
{
1043
172
    assert(e != NULL);
1044
172
    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
3
        case Tuple_kind:
1056
3
            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
22
        case BinOp_kind:
1063
28
        case UnaryOp_kind:
1064
28
            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
7
        case JoinedStr_kind:
1083
7
        case FormattedValue_kind:
1084
7
            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
14
        case Compare_kind:
1105
14
            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
172
    }
1116
172
}
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.5k
                     int end_col_offset, PyArena *arena) {
1129
34.5k
    Py_ssize_t args_len = asdl_seq_LEN(a);
1130
34.5k
    Py_ssize_t total_len = args_len;
1131
1132
34.5k
    if (b == NULL) {
1133
32.0k
        return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
1134
32.0k
                        end_lineno, end_col_offset, arena);
1135
1136
32.0k
    }
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.96k
    for (i = 0; i < args_len; i++) {
1152
3.48k
        asdl_seq_SET(args, i, asdl_seq_GET(a, i));
1153
3.48k
    }
1154
3.17k
    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.3k
{
1167
10.3k
    if (e == NULL) {
1168
0
        return NULL;
1169
0
    }
1170
1171
10.3k
#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
1172
2.77k
        Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
1173
8.75k
        for (Py_ssize_t i = 0; i < len; i++) {\
1174
6.11k
            expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
1175
6.11k
            expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
1176
6.11k
            if (child != NULL) {\
1177
136
                return child;\
1178
136
            }\
1179
6.11k
        }\
1180
2.77k
    } 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.3k
    switch (e->kind) {
1189
852
        case List_kind:
1190
852
            VISIT_CONTAINER(e, List);
1191
831
            return NULL;
1192
1.92k
        case Tuple_kind:
1193
1.92k
            VISIT_CONTAINER(e, Tuple);
1194
1.80k
            return NULL;
1195
1.91k
        case Starred_kind:
1196
1.91k
            if (targets_type == DEL_TARGETS) {
1197
1
                return e;
1198
1
            }
1199
1.91k
            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.87k
        case Name_kind:
1213
4.65k
        case Subscript_kind:
1214
5.13k
        case Attribute_kind:
1215
5.13k
            return NULL;
1216
120
        default:
1217
120
            return e;
1218
10.3k
    }
1219
10.3k
}
1220
1221
34
void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
1222
34
    int kwarg_unpacking = 0;
1223
628
    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
278
            kwarg_unpacking = 1;
1227
278
        }
1228
594
    }
1229
1230
34
    const char *msg = NULL;
1231
34
    if (kwarg_unpacking) {
1232
20
        msg = "positional argument follows keyword argument unpacking";
1233
20
    } else {
1234
14
        msg = "positional argument follows keyword argument";
1235
14
    }
1236
1237
34
    return RAISE_SYNTAX_ERROR(msg);
1238
34
}
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.2k
_PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant, Token* token) {
1268
25.2k
    assert(PyUnicode_CheckExact(constant->v.Constant.value));
1269
1270
25.2k
    const char* bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
1271
25.2k
    if (bstr == NULL) {
1272
0
        return NULL;
1273
0
    }
1274
1275
25.2k
    size_t len;
1276
25.2k
    if (strcmp(bstr, "{{") == 0 || strcmp(bstr, "}}") == 0) {
1277
0
        len = 1;
1278
25.2k
    } else {
1279
25.2k
        len = strlen(bstr);
1280
25.2k
    }
1281
1282
25.2k
    is_raw = is_raw || strchr(bstr, '\\') == NULL;
1283
25.2k
    PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
1284
25.2k
    if (str == NULL) {
1285
5
        _Pypegen_raise_decode_error(p);
1286
5
        return NULL;
1287
5
    }
1288
25.1k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1289
0
        Py_DECREF(str);
1290
0
        return NULL;
1291
0
    }
1292
25.1k
    return _PyAST_Constant(str, NULL, constant->lineno, constant->col_offset,
1293
25.1k
                           constant->end_lineno, constant->end_col_offset,
1294
25.1k
                           p->arena);
1295
25.1k
}
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
17.8k
{
1300
17.8k
    Py_ssize_t n_items = asdl_seq_LEN(raw_expressions);
1301
17.8k
    Py_ssize_t total_items = n_items;
1302
61.1k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1303
43.3k
        expr_ty item = asdl_seq_GET(raw_expressions, i);
1304
43.3k
        if (item->kind == JoinedStr_kind) {
1305
5.07k
            total_items += asdl_seq_LEN(item->v.JoinedStr.values) - 1;
1306
5.07k
        }
1307
43.3k
    }
1308
1309
17.8k
    const char* quote_str = PyBytes_AsString(a->bytes);
1310
17.8k
    if (quote_str == NULL) {
1311
0
        return NULL;
1312
0
    }
1313
17.8k
    int is_raw = strpbrk(quote_str, "rR") != NULL;
1314
1315
17.8k
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(total_items, p->arena);
1316
17.8k
    if (seq == NULL) {
1317
0
        return NULL;
1318
0
    }
1319
1320
17.8k
    Py_ssize_t index = 0;
1321
61.1k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1322
43.3k
        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.3k
        if (item->kind == JoinedStr_kind) {
1329
5.07k
            asdl_expr_seq *values = item->v.JoinedStr.values;
1330
5.07k
            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.07k
            expr_ty first = asdl_seq_GET(values, 0);
1340
5.07k
            assert(first->kind == Constant_kind);
1341
5.07k
            asdl_seq_SET(seq, index++, first);
1342
1343
5.07k
            expr_ty second = asdl_seq_GET(values, 1);
1344
5.07k
            assert((string_kind == TSTRING && second->kind == Interpolation_kind) || second->kind == FormattedValue_kind);
1345
5.07k
            asdl_seq_SET(seq, index++, second);
1346
1347
5.07k
            continue;
1348
5.07k
        }
1349
1350
38.2k
        if (item->kind == Constant_kind) {
1351
25.2k
            item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
1352
25.2k
            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.1k
            if (PyUnicode_CheckExact(item->v.Constant.value)
1360
25.1k
                && PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1361
424
                continue;
1362
424
            }
1363
25.1k
        }
1364
37.8k
        asdl_seq_SET(seq, index++, item);
1365
37.8k
    }
1366
1367
17.8k
    asdl_expr_seq *resized_exprs;
1368
17.8k
    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.4k
    else {
1378
17.4k
        resized_exprs = seq;
1379
17.4k
    }
1380
17.8k
    return resized_exprs;
1381
17.8k
}
1382
1383
expr_ty
1384
3.74k
_PyPegen_template_str(Parser *p, Token *a, asdl_expr_seq *raw_expressions, Token *b) {
1385
1386
3.74k
    asdl_expr_seq *resized_exprs = _get_resized_exprs(p, a, raw_expressions, b, TSTRING);
1387
3.74k
    return _PyAST_TemplateStr(resized_exprs, a->lineno, a->col_offset,
1388
3.74k
                              b->end_lineno, b->end_col_offset,
1389
3.74k
                              p->arena);
1390
3.74k
}
1391
1392
expr_ty
1393
14.1k
_PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* raw_expressions, Token*b) {
1394
1395
14.1k
    asdl_expr_seq *resized_exprs = _get_resized_exprs(p, a, raw_expressions, b, FSTRING);
1396
14.1k
    return _PyAST_JoinedStr(resized_exprs, a->lineno, a->col_offset,
1397
14.1k
                            b->end_lineno, b->end_col_offset,
1398
14.1k
                            p->arena);
1399
14.1k
}
1400
1401
7.95k
expr_ty _PyPegen_decoded_constant_from_token(Parser* p, Token* tok) {
1402
7.95k
    Py_ssize_t bsize;
1403
7.95k
    char* bstr;
1404
7.95k
    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
7.95k
    int is_raw = 0;
1410
7.95k
    if (INSIDE_FSTRING(p->tok)) {
1411
5.11k
        tokenizer_mode *mode = TOK_GET_MODE(p->tok);
1412
5.11k
        is_raw = mode->raw;
1413
5.11k
    }
1414
1415
7.95k
    PyObject* str = _PyPegen_decode_string(p, is_raw, bstr, bsize, tok);
1416
7.95k
    if (str == NULL) {
1417
2
        return NULL;
1418
2
    }
1419
7.95k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1420
0
        Py_DECREF(str);
1421
0
        return NULL;
1422
0
    }
1423
7.95k
    return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1424
7.95k
                           tok->end_lineno, tok->end_col_offset,
1425
7.95k
                           p->arena);
1426
7.95k
}
1427
1428
31.8k
expr_ty _PyPegen_constant_from_token(Parser* p, Token* tok) {
1429
31.8k
    char* bstr = PyBytes_AsString(tok->bytes);
1430
31.8k
    if (bstr == NULL) {
1431
0
        return NULL;
1432
0
    }
1433
31.8k
    PyObject* str = PyUnicode_FromString(bstr);
1434
31.8k
    if (str == NULL) {
1435
11
        return NULL;
1436
11
    }
1437
31.8k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1438
0
        Py_DECREF(str);
1439
0
        return NULL;
1440
0
    }
1441
31.8k
    return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1442
31.8k
                           tok->end_lineno, tok->end_col_offset,
1443
31.8k
                           p->arena);
1444
31.8k
}
1445
1446
73.0k
expr_ty _PyPegen_constant_from_string(Parser* p, Token* tok) {
1447
73.0k
    char* the_str = PyBytes_AsString(tok->bytes);
1448
73.0k
    if (the_str == NULL) {
1449
0
        return NULL;
1450
0
    }
1451
73.0k
    PyObject *s = _PyPegen_parse_string(p, tok);
1452
73.0k
    if (s == NULL) {
1453
355
        _Pypegen_raise_decode_error(p);
1454
355
        return NULL;
1455
355
    }
1456
72.6k
    if (_PyArena_AddPyObject(p->arena, s) < 0) {
1457
0
        Py_DECREF(s);
1458
0
        return NULL;
1459
0
    }
1460
72.6k
    PyObject *kind = NULL;
1461
72.6k
    if (the_str && the_str[0] == 'u') {
1462
486
        kind = _PyPegen_new_identifier(p, "u");
1463
486
        if (kind == NULL) {
1464
0
            return NULL;
1465
0
        }
1466
486
    }
1467
72.6k
    return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno, tok->end_col_offset, p->arena);
1468
72.6k
}
1469
1470
static int
1471
_get_interpolation_conversion(Parser *p, Token *debug, ResultTokenWithMetadata *conversion,
1472
                              ResultTokenWithMetadata *format)
1473
25.1k
{
1474
25.1k
    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
23.6k
    else if (debug && !format) {
1481
        /* If no conversion is specified, use !r for debug expressions */
1482
5.18k
        return (int)'r';
1483
5.18k
    }
1484
18.4k
    return -1;
1485
25.1k
}
1486
1487
static PyObject *
1488
_strip_interpolation_expr(PyObject *exprstr)
1489
5.13k
{
1490
5.13k
    Py_ssize_t len = PyUnicode_GET_LENGTH(exprstr);
1491
1492
10.3k
    for (Py_ssize_t i = len - 1; i >= 0; i--) {
1493
10.3k
        Py_UCS4 c = PyUnicode_READ_CHAR(exprstr, i);
1494
10.3k
        if (_PyUnicode_IsWhitespace(c) || c == '=') {
1495
5.18k
            len--;
1496
5.18k
        }
1497
5.13k
        else {
1498
5.13k
            break;
1499
5.13k
        }
1500
10.3k
    }
1501
1502
5.13k
    return PyUnicode_Substring(exprstr, 0, len);
1503
5.13k
}
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.13k
                                 int end_lineno, int end_col_offset, PyArena *arena) {
1508
1509
5.13k
    int conversion_val = _get_interpolation_conversion(p, debug, conversion, format);
1510
1511
    /* Find the non whitespace token after the "=" */
1512
5.13k
    int debug_end_line, debug_end_offset;
1513
5.13k
    PyObject *debug_metadata;
1514
5.13k
    constant exprstr;
1515
1516
5.13k
    if (conversion) {
1517
547
        debug_end_line = ((expr_ty) conversion->result)->lineno;
1518
547
        debug_end_offset = ((expr_ty) conversion->result)->col_offset;
1519
547
        debug_metadata = exprstr = conversion->metadata;
1520
547
    }
1521
4.59k
    else if (format) {
1522
646
        debug_end_line = ((expr_ty) format->result)->lineno;
1523
646
        debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1524
646
        debug_metadata = exprstr = format->metadata;
1525
646
    }
1526
3.94k
    else {
1527
3.94k
        debug_end_line = end_lineno;
1528
3.94k
        debug_end_offset = end_col_offset;
1529
3.94k
        debug_metadata = exprstr = closing_brace->metadata;
1530
3.94k
    }
1531
1532
5.13k
    assert(exprstr != NULL);
1533
5.13k
    PyObject *final_exprstr = _strip_interpolation_expr(exprstr);
1534
5.13k
    if (!final_exprstr || _PyArena_AddPyObject(arena, final_exprstr) < 0) {
1535
0
        Py_XDECREF(final_exprstr);
1536
0
        return NULL;
1537
0
    }
1538
1539
5.13k
    expr_ty interpolation = _PyAST_Interpolation(
1540
5.13k
        expression, final_exprstr, conversion_val, format ? (expr_ty) format->result : NULL,
1541
5.13k
        lineno, col_offset, end_lineno,
1542
5.13k
        end_col_offset, arena
1543
5.13k
    );
1544
1545
5.13k
    if (!debug) {
1546
4.78k
        return interpolation;
1547
4.78k
    }
1548
1549
355
    expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1550
355
                                            debug_end_offset - 1, p->arena);
1551
355
    if (!debug_text) {
1552
0
        return NULL;
1553
0
    }
1554
1555
355
    asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1556
355
    asdl_seq_SET(values, 0, debug_text);
1557
355
    asdl_seq_SET(values, 1, interpolation);
1558
355
    return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1559
355
}
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.0k
                                 int end_lineno, int end_col_offset, PyArena *arena) {
1564
20.0k
    int conversion_val = _get_interpolation_conversion(p, debug, conversion, format);
1565
1566
20.0k
    expr_ty formatted_value = _PyAST_FormattedValue(
1567
20.0k
        expression, conversion_val, format ? (expr_ty) format->result : NULL,
1568
20.0k
        lineno, col_offset, end_lineno,
1569
20.0k
        end_col_offset, arena
1570
20.0k
    );
1571
1572
20.0k
    if (!debug) {
1573
14.3k
        return formatted_value;
1574
14.3k
    }
1575
1576
    /* Find the non whitespace token after the "=" */
1577
5.62k
    int debug_end_line, debug_end_offset;
1578
5.62k
    PyObject *debug_metadata;
1579
1580
5.62k
    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.06k
    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
4.95k
    else {
1591
4.95k
        debug_end_line = end_lineno;
1592
4.95k
        debug_end_offset = end_col_offset;
1593
4.95k
        debug_metadata = closing_brace->metadata;
1594
4.95k
    }
1595
5.62k
    expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1596
5.62k
                                            debug_end_offset - 1, p->arena);
1597
5.62k
    if (!debug_text) {
1598
2
        return NULL;
1599
2
    }
1600
1601
5.62k
    asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1602
5.62k
    asdl_seq_SET(values, 0, debug_text);
1603
5.62k
    asdl_seq_SET(values, 1, formatted_value);
1604
5.62k
    return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1605
5.62k
}
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
784
{
1612
784
    Py_ssize_t len = asdl_seq_LEN(strings);
1613
784
    assert(len > 0);
1614
1615
784
    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
784
    PyObject* kind = asdl_seq_GET(strings, 0)->v.Constant.kind;
1622
3.86k
    for (Py_ssize_t i = 0; i < len; i++) {
1623
3.08k
        expr_ty elem = asdl_seq_GET(strings, i);
1624
3.08k
        PyBytes_Concat(&res, elem->v.Constant.value);
1625
3.08k
    }
1626
784
    if (!res || _PyArena_AddPyObject(arena, res) < 0) {
1627
0
        Py_XDECREF(res);
1628
0
        return NULL;
1629
0
    }
1630
784
    return _PyAST_Constant(res, kind, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1631
784
}
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.61k
{
1638
1.61k
    Py_ssize_t len = asdl_seq_LEN(strings);
1639
1.61k
    assert(len > 1);
1640
1641
1.61k
    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.61k
    PyObject *kind = first->v.Constant.kind;
1650
1651
1.61k
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1652
1.61k
    if (writer == NULL) {
1653
0
        return NULL;
1654
0
    }
1655
1656
22.7k
    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.61k
    PyObject *final = PyUnicodeWriter_Finish(writer);
1668
1.61k
    if (final == NULL) {
1669
0
        return NULL;
1670
0
    }
1671
1.61k
    if (_PyArena_AddPyObject(p->arena, final) < 0) {
1672
0
        Py_DECREF(final);
1673
0
        return NULL;
1674
0
    }
1675
1.61k
    return _PyAST_Constant(final, kind, lineno, col_offset,
1676
1.61k
                           end_lineno, end_col_offset, arena);
1677
1.61k
}
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
12.7k
{
1684
12.7k
    Py_ssize_t len = asdl_seq_LEN(strings);
1685
12.7k
    assert(len > 0);
1686
1687
12.7k
    Py_ssize_t n_flattened_elements = 0;
1688
40.1k
    for (Py_ssize_t i = 0; i < len; i++) {
1689
27.4k
        expr_ty elem = asdl_seq_GET(strings, i);
1690
27.4k
        switch(elem->kind) {
1691
12.1k
            case JoinedStr_kind:
1692
12.1k
                n_flattened_elements += asdl_seq_LEN(elem->v.JoinedStr.values);
1693
12.1k
                break;
1694
3.59k
            case TemplateStr_kind:
1695
3.59k
                n_flattened_elements += asdl_seq_LEN(elem->v.TemplateStr.values);
1696
3.59k
                break;
1697
11.6k
            default:
1698
11.6k
                n_flattened_elements++;
1699
11.6k
                break;
1700
27.4k
        }
1701
27.4k
    }
1702
1703
1704
12.7k
    asdl_expr_seq* flattened = _Py_asdl_expr_seq_new(n_flattened_elements, p->arena);
1705
12.7k
    if (flattened == NULL) {
1706
0
        return NULL;
1707
0
    }
1708
1709
    /* build flattened list */
1710
12.7k
    Py_ssize_t current_pos = 0;
1711
40.1k
    for (Py_ssize_t i = 0; i < len; i++) {
1712
27.4k
        expr_ty elem = asdl_seq_GET(strings, i);
1713
27.4k
        switch(elem->kind) {
1714
12.1k
            case JoinedStr_kind:
1715
49.4k
                for (Py_ssize_t j = 0; j < asdl_seq_LEN(elem->v.JoinedStr.values); j++) {
1716
37.2k
                    expr_ty subvalue = asdl_seq_GET(elem->v.JoinedStr.values, j);
1717
37.2k
                    if (subvalue == NULL) {
1718
0
                        return NULL;
1719
0
                    }
1720
37.2k
                    asdl_seq_SET(flattened, current_pos++, subvalue);
1721
37.2k
                }
1722
12.1k
                break;
1723
12.1k
            case TemplateStr_kind:
1724
11.1k
                for (Py_ssize_t j = 0; j < asdl_seq_LEN(elem->v.TemplateStr.values); j++) {
1725
7.52k
                    expr_ty subvalue = asdl_seq_GET(elem->v.TemplateStr.values, j);
1726
7.52k
                    if (subvalue == NULL) {
1727
0
                        return NULL;
1728
0
                    }
1729
7.52k
                    asdl_seq_SET(flattened, current_pos++, subvalue);
1730
7.52k
                }
1731
3.59k
                break;
1732
11.6k
            default:
1733
11.6k
                asdl_seq_SET(flattened, current_pos++, elem);
1734
11.6k
                break;
1735
27.4k
        }
1736
27.4k
    }
1737
1738
    /* calculate folded element count */
1739
12.7k
    Py_ssize_t n_elements = 0;
1740
12.7k
    int prev_is_constant = 0;
1741
69.0k
    for (Py_ssize_t i = 0; i < n_flattened_elements; i++) {
1742
56.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
56.3k
        if (elem->kind == Constant_kind &&
1748
56.3k
            PyUnicode_CheckExact(elem->v.Constant.value) &&
1749
56.3k
            PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0)
1750
1.56k
            continue;
1751
1752
54.7k
        if (!prev_is_constant || elem->kind != Constant_kind) {
1753
45.0k
            n_elements++;
1754
45.0k
        }
1755
54.7k
        prev_is_constant = elem->kind == Constant_kind;
1756
54.7k
    }
1757
1758
12.7k
    asdl_expr_seq* values = _Py_asdl_expr_seq_new(n_elements, p->arena);
1759
12.7k
    if (values == NULL) {
1760
0
        return NULL;
1761
0
    }
1762
1763
    /* build folded list */
1764
12.7k
    current_pos = 0;
1765
58.0k
    for (Py_ssize_t i = 0; i < n_flattened_elements; i++) {
1766
45.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
45.2k
        if (elem->kind == Constant_kind) {
1771
24.0k
            if (i + 1 < n_flattened_elements &&
1772
24.0k
                asdl_seq_GET(flattened, i + 1)->kind == Constant_kind) {
1773
4.86k
                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
4.86k
                PyObject *kind = elem->v.Constant.kind;
1782
1783
4.86k
                PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1784
4.86k
                if (writer == NULL) {
1785
0
                    return NULL;
1786
0
                }
1787
4.86k
                expr_ty last_elem = elem;
1788
4.86k
                Py_ssize_t j;
1789
20.7k
                for (j = i; j < n_flattened_elements; j++) {
1790
18.5k
                    expr_ty current_elem = asdl_seq_GET(flattened, j);
1791
18.5k
                    if (current_elem->kind == Constant_kind) {
1792
15.9k
                        if (PyUnicodeWriter_WriteStr(writer,
1793
15.9k
                                                     current_elem->v.Constant.value)) {
1794
0
                            PyUnicodeWriter_Discard(writer);
1795
0
                            return NULL;
1796
0
                        }
1797
15.9k
                        last_elem = current_elem;
1798
15.9k
                    } else {
1799
2.64k
                        break;
1800
2.64k
                    }
1801
18.5k
                }
1802
4.86k
                i = j - 1;
1803
1804
4.86k
                PyObject *concat_str = PyUnicodeWriter_Finish(writer);
1805
4.86k
                if (concat_str == NULL) {
1806
0
                    return NULL;
1807
0
                }
1808
4.86k
                if (_PyArena_AddPyObject(p->arena, concat_str) < 0) {
1809
0
                    Py_DECREF(concat_str);
1810
0
                    return NULL;
1811
0
                }
1812
4.86k
                elem = _PyAST_Constant(concat_str, kind, first_elem->lineno,
1813
4.86k
                                       first_elem->col_offset,
1814
4.86k
                                       last_elem->end_lineno,
1815
4.86k
                                       last_elem->end_col_offset, p->arena);
1816
4.86k
                if (elem == NULL) {
1817
0
                    return NULL;
1818
0
                }
1819
4.86k
            }
1820
1821
            /* Drop all empty contanst strings */
1822
24.0k
            if (PyUnicode_CheckExact(elem->v.Constant.value) &&
1823
24.0k
                PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0) {
1824
263
                continue;
1825
263
            }
1826
24.0k
        }
1827
1828
45.0k
        asdl_seq_SET(values, current_pos++, elem);
1829
45.0k
    }
1830
1831
12.7k
    assert(current_pos == n_elements);
1832
12.7k
    return values;
1833
12.7k
}
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
9.84k
{
1840
9.84k
    asdl_expr_seq *values = _build_concatenated_str(p, strings, lineno,
1841
9.84k
        col_offset, end_lineno, end_col_offset, arena);
1842
9.84k
    return _PyAST_JoinedStr(values, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1843
9.84k
}
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
2.88k
{
1850
2.88k
    asdl_expr_seq *values = _build_concatenated_str(p, strings, lineno,
1851
2.88k
        col_offset, end_lineno, end_col_offset, arena);
1852
2.88k
    return _PyAST_TemplateStr(values, lineno, col_offset, end_lineno,
1853
2.88k
        end_col_offset, arena);
1854
2.88k
}
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
48.1k
{
1861
48.1k
    Py_ssize_t len = asdl_seq_LEN(strings);
1862
48.1k
    assert(len > 0);
1863
1864
48.1k
    int f_string_found = 0;
1865
48.1k
    int unicode_string_found = 0;
1866
48.1k
    int bytes_found = 0;
1867
1868
48.1k
    Py_ssize_t i = 0;
1869
132k
    for (i = 0; i < len; i++) {
1870
83.9k
        expr_ty elem = asdl_seq_GET(strings, i);
1871
83.9k
        switch(elem->kind) {
1872
68.1k
            case Constant_kind:
1873
68.1k
                if (PyBytes_CheckExact(elem->v.Constant.value)) {
1874
5.80k
                    bytes_found = 1;
1875
62.3k
                } else {
1876
62.3k
                    unicode_string_found = 1;
1877
62.3k
                }
1878
68.1k
                break;
1879
12.1k
            case JoinedStr_kind:
1880
12.1k
                f_string_found = 1;
1881
12.1k
                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.58k
            default:
1887
3.58k
                f_string_found = 1;
1888
3.58k
                break;
1889
83.9k
        }
1890
83.9k
    }
1891
1892
    // Cannot mix unicode and bytes
1893
48.1k
    if ((unicode_string_found || f_string_found) && bytes_found) {
1894
5
        RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1895
5
        return NULL;
1896
5
    }
1897
1898
    // If it's only bytes or only unicode string, do a simple concat
1899
48.1k
    if (!f_string_found) {
1900
38.3k
        if (len == 1) {
1901
35.9k
            return asdl_seq_GET(strings, 0);
1902
35.9k
        }
1903
2.40k
        else if (bytes_found) {
1904
784
            return _build_concatenated_bytes(p, strings, lineno, col_offset,
1905
784
                end_lineno, end_col_offset, arena);
1906
784
        }
1907
1.61k
        else {
1908
1.61k
            return _build_concatenated_unicode(p, strings, lineno, col_offset,
1909
1.61k
                end_lineno, end_col_offset, arena);
1910
1.61k
        }
1911
38.3k
    }
1912
1913
9.84k
    return _build_concatenated_joined_str(p, strings, lineno,
1914
9.84k
        col_offset, end_lineno, end_col_offset, arena);
1915
48.1k
}
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.92k
                             PyArena *arena) {
1921
1.92k
    if (level == 0 && PyUnicode_CompareWithASCIIString(module, "__future__") == 0) {
1922
1.30k
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(names); i++) {
1923
821
            alias_ty alias = asdl_seq_GET(names, i);
1924
821
            if (PyUnicode_CompareWithASCIIString(alias->name, "barry_as_FLUFL") == 0) {
1925
73
                p->flags |= PyPARSE_BARRY_AS_BDFL;
1926
73
            }
1927
821
        }
1928
482
    }
1929
1.92k
    return _PyAST_ImportFrom(module, names, level, lineno, col_offset, end_lineno, end_col_offset, arena);
1930
1.92k
}
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.2k
        return stmts;
1936
29.2k
    }
1937
8.34k
    Py_ssize_t len = asdl_seq_LEN(stmts);
1938
8.34k
    if (len == 0) {
1939
0
        return stmts;
1940
0
    }
1941
8.34k
    stmt_ty last_stmt = asdl_seq_GET(stmts, len - 1);
1942
8.34k
    if (p->last_stmt_location.lineno > last_stmt->lineno) {
1943
183
        return stmts;
1944
183
    }
1945
8.15k
    p->last_stmt_location.lineno = last_stmt->lineno;
1946
8.15k
    p->last_stmt_location.col_offset = last_stmt->col_offset;
1947
8.15k
    p->last_stmt_location.end_lineno = last_stmt->end_lineno;
1948
8.15k
    p->last_stmt_location.end_col_offset = last_stmt->end_col_offset;
1949
8.15k
    return stmts;
1950
8.34k
}