Coverage Report

Created: 2025-07-11 06:24

/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
75.0k
{
13
75.0k
    return &_PyRuntime.parser.dummy_name;
14
75.0k
}
15
16
/* Creates a single-element asdl_seq* that contains a */
17
asdl_seq *
18
_PyPegen_singleton_seq(Parser *p, void *a)
19
175k
{
20
175k
    assert(a != NULL);
21
175k
    asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
22
175k
    if (!seq) {
23
0
        return NULL;
24
0
    }
25
175k
    asdl_seq_SET_UNTYPED(seq, 0, a);
26
175k
    return seq;
27
175k
}
28
29
/* Creates a copy of seq and prepends a to it */
30
asdl_seq *
31
_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
32
391k
{
33
391k
    assert(a != NULL);
34
391k
    if (!seq) {
35
11.1k
        return _PyPegen_singleton_seq(p, a);
36
11.1k
    }
37
38
380k
    asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
39
380k
    if (!new_seq) {
40
0
        return NULL;
41
0
    }
42
43
380k
    asdl_seq_SET_UNTYPED(new_seq, 0, a);
44
686k
    for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
45
305k
        asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
46
305k
    }
47
380k
    return new_seq;
48
380k
}
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
27.0k
{
74
27.0k
    Py_ssize_t size = 0;
75
136k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
76
109k
        asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
77
109k
        size += asdl_seq_LEN(inner_seq);
78
109k
    }
79
27.0k
    return size;
80
27.0k
}
81
82
/* Flattens an asdl_seq* of asdl_seq*s */
83
asdl_seq *
84
_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
85
27.0k
{
86
27.0k
    Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
87
27.0k
    assert(flattened_seq_size > 0);
88
89
27.0k
    asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
90
27.0k
    if (!flattened_seq) {
91
0
        return NULL;
92
0
    }
93
94
27.0k
    int flattened_seq_idx = 0;
95
136k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
96
109k
        asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
97
226k
        for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
98
116k
            asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
99
116k
        }
100
109k
    }
101
27.0k
    assert(flattened_seq_idx == flattened_seq_size);
102
103
27.0k
    return flattened_seq;
104
27.0k
}
105
106
void *
107
_PyPegen_seq_last_item(asdl_seq *seq)
108
1.37k
{
109
1.37k
    Py_ssize_t len = asdl_seq_LEN(seq);
110
1.37k
    return asdl_seq_GET_UNTYPED(seq, len - 1);
111
1.37k
}
112
113
void *
114
_PyPegen_seq_first_item(asdl_seq *seq)
115
1.34k
{
116
1.34k
    return asdl_seq_GET_UNTYPED(seq, 0);
117
1.34k
}
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
3.00k
{
123
3.00k
    assert(first_name != NULL && second_name != NULL);
124
3.00k
    PyObject *uni = PyUnicode_FromFormat("%U.%U",
125
3.00k
            first_name->v.Name.id, second_name->v.Name.id);
126
3.00k
    if (!uni) {
127
0
        return NULL;
128
0
    }
129
3.00k
    PyInterpreterState *interp = _PyInterpreterState_GET();
130
3.00k
    _PyUnicode_InternImmortal(interp, &uni);
131
3.00k
    if (_PyArena_AddPyObject(p->arena, uni) < 0) {
132
0
        Py_DECREF(uni);
133
0
        return NULL;
134
0
    }
135
136
3.00k
    return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
137
3.00k
}
138
139
/* Counts the total number of dots in seq's tokens */
140
int
141
_PyPegen_seq_count_dots(asdl_seq *seq)
142
2.82k
{
143
2.82k
    int number_of_dots = 0;
144
6.55k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
145
3.72k
        Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
146
3.72k
        switch (current_expr->type) {
147
1.92k
            case ELLIPSIS:
148
1.92k
                number_of_dots += 3;
149
1.92k
                break;
150
1.80k
            case DOT:
151
1.80k
                number_of_dots += 1;
152
1.80k
                break;
153
0
            default:
154
0
                Py_UNREACHABLE();
155
3.72k
        }
156
3.72k
    }
157
158
2.82k
    return number_of_dots;
159
2.82k
}
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
645
                        int end_col_offset, PyArena *arena) {
165
645
    PyObject *str = PyUnicode_InternFromString("*");
166
645
    if (!str) {
167
0
        return NULL;
168
0
    }
169
645
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
170
0
        Py_DECREF(str);
171
0
        return NULL;
172
0
    }
173
645
    return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
174
645
}
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.28k
{
180
2.28k
    Py_ssize_t len = asdl_seq_LEN(seq);
181
2.28k
    assert(len > 0);
182
183
2.28k
    asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
184
2.28k
    if (!new_seq) {
185
0
        return NULL;
186
0
    }
187
7.14k
    for (Py_ssize_t i = 0; i < len; i++) {
188
4.85k
        expr_ty e = asdl_seq_GET(seq, i);
189
4.85k
        asdl_seq_SET(new_seq, i, e->v.Name.id);
190
4.85k
    }
191
2.28k
    return new_seq;
192
2.28k
}
193
194
/* Constructs a CmpopExprPair */
195
CmpopExprPair *
196
_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
197
23.9k
{
198
23.9k
    assert(expr != NULL);
199
23.9k
    CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
200
23.9k
    if (!a) {
201
0
        return NULL;
202
0
    }
203
23.9k
    a->cmpop = cmpop;
204
23.9k
    a->expr = expr;
205
23.9k
    return a;
206
23.9k
}
207
208
asdl_int_seq *
209
_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
210
9.32k
{
211
9.32k
    Py_ssize_t len = asdl_seq_LEN(seq);
212
9.32k
    assert(len > 0);
213
214
9.32k
    asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
215
9.32k
    if (!new_seq) {
216
0
        return NULL;
217
0
    }
218
32.6k
    for (Py_ssize_t i = 0; i < len; i++) {
219
23.3k
        CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
220
23.3k
        asdl_seq_SET(new_seq, i, pair->cmpop);
221
23.3k
    }
222
9.32k
    return new_seq;
223
9.32k
}
224
225
asdl_expr_seq *
226
_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
227
9.32k
{
228
9.32k
    Py_ssize_t len = asdl_seq_LEN(seq);
229
9.32k
    assert(len > 0);
230
231
9.32k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
232
9.32k
    if (!new_seq) {
233
0
        return NULL;
234
0
    }
235
32.6k
    for (Py_ssize_t i = 0; i < len; i++) {
236
23.3k
        CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
237
23.3k
        asdl_seq_SET(new_seq, i, pair->expr);
238
23.3k
    }
239
9.32k
    return new_seq;
240
9.32k
}
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
6.63k
{
246
6.63k
    Py_ssize_t len = asdl_seq_LEN(seq);
247
6.63k
    if (len == 0) {
248
2.89k
        return NULL;
249
2.89k
    }
250
251
3.74k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
252
3.74k
    if (!new_seq) {
253
0
        return NULL;
254
0
    }
255
10.3k
    for (Py_ssize_t i = 0; i < len; i++) {
256
6.57k
        expr_ty e = asdl_seq_GET(seq, i);
257
6.57k
        asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
258
6.57k
    }
259
3.74k
    return new_seq;
260
3.74k
}
261
262
static expr_ty
263
_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
264
219k
{
265
219k
    return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
266
219k
}
267
268
static expr_ty
269
_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
270
4.85k
{
271
4.85k
    return _PyAST_Tuple(
272
4.85k
            _set_seq_context(p, e->v.Tuple.elts, ctx),
273
4.85k
            ctx,
274
4.85k
            EXTRA_EXPR(e, e));
275
4.85k
}
276
277
static expr_ty
278
_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
279
1.78k
{
280
1.78k
    return _PyAST_List(
281
1.78k
            _set_seq_context(p, e->v.List.elts, ctx),
282
1.78k
            ctx,
283
1.78k
            EXTRA_EXPR(e, e));
284
1.78k
}
285
286
static expr_ty
287
_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
288
306
{
289
306
    return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
290
306
                            ctx, EXTRA_EXPR(e, e));
291
306
}
292
293
static expr_ty
294
_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
295
76
{
296
76
    return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
297
76
                            ctx, EXTRA_EXPR(e, e));
298
76
}
299
300
static expr_ty
301
_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
302
829
{
303
829
    return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
304
829
                          ctx, EXTRA_EXPR(e, e));
305
829
}
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
227k
{
311
227k
    assert(expr != NULL);
312
313
227k
    expr_ty new = NULL;
314
227k
    switch (expr->kind) {
315
219k
        case Name_kind:
316
219k
            new = _set_name_context(p, expr, ctx);
317
219k
            break;
318
4.85k
        case Tuple_kind:
319
4.85k
            new = _set_tuple_context(p, expr, ctx);
320
4.85k
            break;
321
1.78k
        case List_kind:
322
1.78k
            new = _set_list_context(p, expr, ctx);
323
1.78k
            break;
324
306
        case Subscript_kind:
325
306
            new = _set_subscript_context(p, expr, ctx);
326
306
            break;
327
76
        case Attribute_kind:
328
76
            new = _set_attribute_context(p, expr, ctx);
329
76
            break;
330
829
        case Starred_kind:
331
829
            new = _set_starred_context(p, expr, ctx);
332
829
            break;
333
0
        default:
334
0
            new = expr;
335
227k
    }
336
227k
    return new;
337
227k
}
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
45.5k
{
343
45.5k
    KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
344
45.5k
    if (!a) {
345
0
        return NULL;
346
0
    }
347
45.5k
    a->key = key;
348
45.5k
    a->value = value;
349
45.5k
    return a;
350
45.5k
}
351
352
/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
353
asdl_expr_seq *
354
_PyPegen_get_keys(Parser *p, asdl_seq *seq)
355
4.37k
{
356
4.37k
    Py_ssize_t len = asdl_seq_LEN(seq);
357
4.37k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
358
4.37k
    if (!new_seq) {
359
0
        return NULL;
360
0
    }
361
39.8k
    for (Py_ssize_t i = 0; i < len; i++) {
362
35.5k
        KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
363
35.5k
        asdl_seq_SET(new_seq, i, pair->key);
364
35.5k
    }
365
4.37k
    return new_seq;
366
4.37k
}
367
368
/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
369
asdl_expr_seq *
370
_PyPegen_get_values(Parser *p, asdl_seq *seq)
371
4.37k
{
372
4.37k
    Py_ssize_t len = asdl_seq_LEN(seq);
373
4.37k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
374
4.37k
    if (!new_seq) {
375
0
        return NULL;
376
0
    }
377
39.8k
    for (Py_ssize_t i = 0; i < len; i++) {
378
35.5k
        KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
379
35.5k
        asdl_seq_SET(new_seq, i, pair->value);
380
35.5k
    }
381
4.37k
    return new_seq;
382
4.37k
}
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.9k
{
388
11.9k
    KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
389
11.9k
    if (!a) {
390
0
        return NULL;
391
0
    }
392
11.9k
    a->key = key;
393
11.9k
    a->pattern = pattern;
394
11.9k
    return a;
395
11.9k
}
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
2.15k
{
401
2.15k
    Py_ssize_t len = asdl_seq_LEN(seq);
402
2.15k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
403
2.15k
    if (!new_seq) {
404
0
        return NULL;
405
0
    }
406
5.34k
    for (Py_ssize_t i = 0; i < len; i++) {
407
3.18k
        KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
408
3.18k
        asdl_seq_SET(new_seq, i, pair->key);
409
3.18k
    }
410
2.15k
    return new_seq;
411
2.15k
}
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
2.15k
{
417
2.15k
    Py_ssize_t len = asdl_seq_LEN(seq);
418
2.15k
    asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
419
2.15k
    if (!new_seq) {
420
0
        return NULL;
421
0
    }
422
5.34k
    for (Py_ssize_t i = 0; i < len; i++) {
423
3.18k
        KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
424
3.18k
        asdl_seq_SET(new_seq, i, pair->pattern);
425
3.18k
    }
426
2.15k
    return new_seq;
427
2.15k
}
428
429
/* Constructs a NameDefaultPair */
430
NameDefaultPair *
431
_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
432
88.9k
{
433
88.9k
    NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
434
88.9k
    if (!a) {
435
0
        return NULL;
436
0
    }
437
88.9k
    a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
438
88.9k
    a->value = value;
439
88.9k
    return a;
440
88.9k
}
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
6.48k
{
446
6.48k
    SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
447
6.48k
    if (!a) {
448
0
        return NULL;
449
0
    }
450
6.48k
    a->plain_names = plain_names;
451
6.48k
    a->names_with_defaults = names_with_defaults;
452
6.48k
    return a;
453
6.48k
}
454
455
/* Constructs a StarEtc */
456
StarEtc *
457
_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
458
5.75k
{
459
5.75k
    StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
460
5.75k
    if (!a) {
461
0
        return NULL;
462
0
    }
463
5.75k
    a->vararg = vararg;
464
5.75k
    a->kwonlyargs = kwonlyargs;
465
5.75k
    a->kwarg = kwarg;
466
5.75k
    return a;
467
5.75k
}
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
38.0k
    for (Py_ssize_t i = 0; i < first_len; i++) {
481
24.5k
        asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
482
24.5k
    }
483
22.7k
    for (Py_ssize_t i = 0; i < second_len; i++) {
484
9.16k
        asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
485
9.16k
    }
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.4k
        NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
500
15.4k
        asdl_seq_SET(seq, i, pair->arg);
501
15.4k
    }
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.4k
        NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
515
15.4k
        asdl_seq_SET(seq, i, pair->value);
516
15.4k
    }
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
18.9k
                  asdl_arg_seq **posonlyargs) {
525
18.9k
    if (slash_without_default != NULL) {
526
1.48k
        *posonlyargs = slash_without_default;
527
1.48k
    }
528
17.4k
    else if (slash_with_default != NULL) {
529
2.25k
        asdl_arg_seq *slash_with_default_names =
530
2.25k
                _get_names(p, slash_with_default->names_with_defaults);
531
2.25k
        if (!slash_with_default_names) {
532
0
            return -1;
533
0
        }
534
2.25k
        *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
535
2.25k
                p,
536
2.25k
                (asdl_seq*)slash_with_default->plain_names,
537
2.25k
                (asdl_seq*)slash_with_default_names);
538
2.25k
    }
539
15.2k
    else {
540
15.2k
        *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
541
15.2k
    }
542
18.9k
    return *posonlyargs == NULL ? -1 : 0;
543
18.9k
}
544
545
static int
546
_make_posargs(Parser *p,
547
              asdl_arg_seq *plain_names,
548
              asdl_seq *names_with_default,
549
18.9k
              asdl_arg_seq **posargs) {
550
551
18.9k
    if (names_with_default != NULL) {
552
13.9k
        if (plain_names != NULL) {
553
8.67k
            asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
554
8.67k
            if (!names_with_default_names) {
555
0
                return -1;
556
0
            }
557
8.67k
            *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
558
8.67k
                    p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
559
8.67k
        }
560
5.26k
        else {
561
5.26k
            *posargs = _get_names(p, names_with_default);
562
5.26k
        }
563
13.9k
    }
564
5.02k
    else {
565
5.02k
        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.02k
        else {
572
5.02k
            *posargs = _Py_asdl_arg_seq_new(0, p->arena);
573
5.02k
        }
574
5.02k
    }
575
18.9k
    return *posargs == NULL ? -1 : 0;
576
18.9k
}
577
578
static int
579
_make_posdefaults(Parser *p,
580
                  SlashWithDefault *slash_with_default,
581
                  asdl_seq *names_with_default,
582
18.9k
                  asdl_expr_seq **posdefaults) {
583
18.9k
    if (slash_with_default != NULL && names_with_default != NULL) {
584
2.25k
        asdl_expr_seq *slash_with_default_values =
585
2.25k
                _get_defaults(p, slash_with_default->names_with_defaults);
586
2.25k
        if (!slash_with_default_values) {
587
0
            return -1;
588
0
        }
589
2.25k
        asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
590
2.25k
        if (!names_with_default_values) {
591
0
            return -1;
592
0
        }
593
2.25k
        *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
594
2.25k
                p,
595
2.25k
                (asdl_seq*)slash_with_default_values,
596
2.25k
                (asdl_seq*)names_with_default_values);
597
2.25k
    }
598
16.7k
    else if (slash_with_default == NULL && names_with_default != NULL) {
599
11.6k
        *posdefaults = _get_defaults(p, names_with_default);
600
11.6k
    }
601
5.02k
    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.02k
    else {
605
5.02k
        *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
606
5.02k
    }
607
18.9k
    return *posdefaults == NULL ? -1 : 0;
608
18.9k
}
609
610
static int
611
_make_kwargs(Parser *p, StarEtc *star_etc,
612
             asdl_arg_seq **kwonlyargs,
613
18.9k
             asdl_expr_seq **kwdefaults) {
614
18.9k
    if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
615
4.63k
        *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
616
4.63k
    }
617
14.3k
    else {
618
14.3k
        *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
619
14.3k
    }
620
621
18.9k
    if (*kwonlyargs == NULL) {
622
0
        return -1;
623
0
    }
624
625
18.9k
    if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
626
4.63k
        *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
627
4.63k
    }
628
14.3k
    else {
629
14.3k
        *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
630
14.3k
    }
631
632
18.9k
    if (*kwdefaults == NULL) {
633
0
        return -1;
634
0
    }
635
636
18.9k
    return 0;
637
18.9k
}
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
18.9k
{
645
18.9k
    asdl_arg_seq *posonlyargs;
646
18.9k
    if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
647
0
        return NULL;
648
0
    }
649
650
18.9k
    asdl_arg_seq *posargs;
651
18.9k
    if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
652
0
        return NULL;
653
0
    }
654
655
18.9k
    asdl_expr_seq *posdefaults;
656
18.9k
    if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
657
0
        return NULL;
658
0
    }
659
660
18.9k
    arg_ty vararg = NULL;
661
18.9k
    if (star_etc != NULL && star_etc->vararg != NULL) {
662
3.35k
        vararg = star_etc->vararg;
663
3.35k
    }
664
665
18.9k
    asdl_arg_seq *kwonlyargs;
666
18.9k
    asdl_expr_seq *kwdefaults;
667
18.9k
    if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
668
0
        return NULL;
669
0
    }
670
671
18.9k
    arg_ty kwarg = NULL;
672
18.9k
    if (star_etc != NULL && star_etc->kwarg != NULL) {
673
1.20k
        kwarg = star_etc->kwarg;
674
1.20k
    }
675
676
18.9k
    return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
677
18.9k
                            kwdefaults, kwarg, posdefaults, p->arena);
678
18.9k
}
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
1.91k
{
686
1.91k
    asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
687
1.91k
    if (!posonlyargs) {
688
0
        return NULL;
689
0
    }
690
1.91k
    asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
691
1.91k
    if (!posargs) {
692
0
        return NULL;
693
0
    }
694
1.91k
    asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
695
1.91k
    if (!posdefaults) {
696
0
        return NULL;
697
0
    }
698
1.91k
    asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
699
1.91k
    if (!kwonlyargs) {
700
0
        return NULL;
701
0
    }
702
1.91k
    asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
703
1.91k
    if (!kwdefaults) {
704
0
        return NULL;
705
0
    }
706
707
1.91k
    return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
708
1.91k
                            kwdefaults, NULL, posdefaults, p->arena);
709
1.91k
}
710
711
/* Encapsulates the value of an operator_ty into an AugOperator struct */
712
AugOperator *
713
_PyPegen_augoperator(Parser *p, operator_ty kind)
714
3.08k
{
715
3.08k
    AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
716
3.08k
    if (!a) {
717
0
        return NULL;
718
0
    }
719
3.08k
    a->kind = kind;
720
3.08k
    return a;
721
3.08k
}
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
951
{
727
951
    assert(function_def != NULL);
728
951
    if (function_def->kind == AsyncFunctionDef_kind) {
729
273
        return _PyAST_AsyncFunctionDef(
730
273
            function_def->v.AsyncFunctionDef.name,
731
273
            function_def->v.AsyncFunctionDef.args,
732
273
            function_def->v.AsyncFunctionDef.body, decorators,
733
273
            function_def->v.AsyncFunctionDef.returns,
734
273
            function_def->v.AsyncFunctionDef.type_comment,
735
273
            function_def->v.AsyncFunctionDef.type_params,
736
273
            function_def->lineno, function_def->col_offset,
737
273
            function_def->end_lineno, function_def->end_col_offset, p->arena);
738
273
    }
739
740
678
    return _PyAST_FunctionDef(
741
678
        function_def->v.FunctionDef.name,
742
678
        function_def->v.FunctionDef.args,
743
678
        function_def->v.FunctionDef.body, decorators,
744
678
        function_def->v.FunctionDef.returns,
745
678
        function_def->v.FunctionDef.type_comment,
746
678
        function_def->v.FunctionDef.type_params,
747
678
        function_def->lineno, function_def->col_offset,
748
678
        function_def->end_lineno, function_def->end_col_offset, p->arena);
749
951
}
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
489
{
755
489
    assert(class_def != NULL);
756
489
    return _PyAST_ClassDef(
757
489
        class_def->v.ClassDef.name,
758
489
        class_def->v.ClassDef.bases, class_def->v.ClassDef.keywords,
759
489
        class_def->v.ClassDef.body, decorators,
760
489
        class_def->v.ClassDef.type_params,
761
489
        class_def->lineno, class_def->col_offset, class_def->end_lineno,
762
489
        class_def->end_col_offset, p->arena);
763
489
}
764
765
/* Construct a KeywordOrStarred */
766
KeywordOrStarred *
767
_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
768
36.9k
{
769
36.9k
    KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
770
36.9k
    if (!a) {
771
0
        return NULL;
772
0
    }
773
36.9k
    a->element = element;
774
36.9k
    a->is_keyword = is_keyword;
775
36.9k
    return a;
776
36.9k
}
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.7k
{
782
18.7k
    int n = 0;
783
57.7k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
784
39.0k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
785
39.0k
        if (!k->is_keyword) {
786
2.90k
            n++;
787
2.90k
        }
788
39.0k
    }
789
18.7k
    return n;
790
18.7k
}
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.36k
{
796
9.36k
    int new_len = _seq_number_of_starred_exprs(kwargs);
797
9.36k
    if (new_len == 0) {
798
8.71k
        return NULL;
799
8.71k
    }
800
653
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
801
653
    if (!new_seq) {
802
0
        return NULL;
803
0
    }
804
805
653
    int idx = 0;
806
3.33k
    for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
807
2.67k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
808
2.67k
        if (!k->is_keyword) {
809
1.45k
            asdl_seq_SET(new_seq, idx++, k->element);
810
1.45k
        }
811
2.67k
    }
812
653
    return new_seq;
813
653
}
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.36k
{
819
9.36k
    Py_ssize_t len = asdl_seq_LEN(kwargs);
820
9.36k
    Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
821
9.36k
    if (new_len == 0) {
822
0
        return NULL;
823
0
    }
824
9.36k
    asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
825
9.36k
    if (!new_seq) {
826
0
        return NULL;
827
0
    }
828
829
9.36k
    int idx = 0;
830
28.8k
    for (Py_ssize_t i = 0; i < len; i++) {
831
19.5k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
832
19.5k
        if (k->is_keyword) {
833
18.0k
            asdl_seq_SET(new_seq, idx++, k->element);
834
18.0k
        }
835
19.5k
    }
836
9.36k
    return new_seq;
837
9.36k
}
838
839
expr_ty
840
_PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
841
1.15k
{
842
1.15k
    if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
843
5
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
844
5
        return NULL;
845
5
    }
846
1.15k
    return exp;
847
1.15k
}
848
849
expr_ty
850
_PyPegen_ensure_real(Parser *p, expr_ty exp)
851
1.94k
{
852
1.94k
    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.94k
    return exp;
857
1.94k
}
858
859
mod_ty
860
7.65k
_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
861
7.65k
    asdl_type_ignore_seq *type_ignores = NULL;
862
7.65k
    Py_ssize_t num = p->type_ignore_comments.num_items;
863
7.65k
    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.65k
    return _PyAST_Module(a, type_ignores, p->arena);
883
7.65k
}
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
159k
{
902
159k
    if (tc == NULL) {
903
159k
        return a;
904
159k
    }
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.38k
_PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
922
1.38k
    assert(t->bytes != NULL);
923
1.38k
    assert(t->type == NOTEQUAL);
924
925
1.38k
    const char* tok_str = PyBytes_AS_STRING(t->bytes);
926
1.38k
    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.38k
    if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
931
1.38k
        return strcmp(tok_str, "!=");
932
1.38k
    }
933
0
    return 0;
934
1.38k
}
935
936
int
937
8.91k
_PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
938
8.91k
    if (name->kind != Name_kind) {
939
2.43k
        return 0;
940
2.43k
    }
941
6.48k
    const char* candidates[2] = {"print", "exec"};
942
18.8k
    for (int i=0; i<2; i++) {
943
12.7k
        if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
944
407
            return 1;
945
407
        }
946
12.7k
    }
947
6.07k
    return 0;
948
6.48k
}
949
950
static ResultTokenWithMetadata *
951
result_token_with_metadata(Parser *p, void *result, PyObject *metadata)
952
7.68k
{
953
7.68k
    ResultTokenWithMetadata *res = _PyArena_Malloc(p->arena, sizeof(ResultTokenWithMetadata));
954
7.68k
    if (res == NULL) {
955
0
        return NULL;
956
0
    }
957
7.68k
    res->metadata = metadata;
958
7.68k
    res->result = result;
959
7.68k
    return res;
960
7.68k
}
961
962
ResultTokenWithMetadata *
963
_PyPegen_check_fstring_conversion(Parser *p, Token* conv_token, expr_ty conv)
964
1.47k
{
965
1.47k
    if (conv_token->lineno != conv->lineno || conv_token->end_col_offset != conv->col_offset) {
966
2
        return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
967
2
            conv_token, conv,
968
2
            "%c-string: conversion type must come right after the exclamation mark",
969
2
            TOK_GET_STRING_PREFIX(p->tok)
970
2
        );
971
2
    }
972
973
1.47k
    Py_UCS4 first = PyUnicode_READ_CHAR(conv->v.Name.id, 0);
974
1.47k
    if (PyUnicode_GET_LENGTH(conv->v.Name.id) > 1 ||
975
1.47k
            !(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.46k
    return result_token_with_metadata(p, conv, conv_token->metadata);
984
1.47k
}
985
986
ResultTokenWithMetadata *
987
_PyPegen_setup_full_format_spec(Parser *p, Token *colon, asdl_expr_seq *spec, int lineno, int col_offset,
988
                                int end_lineno, int end_col_offset, PyArena *arena)
989
6.21k
{
990
6.21k
    if (!spec) {
991
0
        return NULL;
992
0
    }
993
994
    // This is needed to keep compatibility with 3.11, where an empty format
995
    // spec is parsed as an *empty* JoinedStr node, instead of having an empty
996
    // constant in it.
997
6.21k
    Py_ssize_t n_items = asdl_seq_LEN(spec);
998
6.21k
    Py_ssize_t non_empty_count = 0;
999
19.3k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1000
13.1k
        expr_ty item = asdl_seq_GET(spec, i);
1001
13.1k
        non_empty_count += !(item->kind == Constant_kind &&
1002
13.1k
                             PyUnicode_CheckExact(item->v.Constant.value) &&
1003
13.1k
                             PyUnicode_GET_LENGTH(item->v.Constant.value) == 0);
1004
13.1k
    }
1005
6.21k
    if (non_empty_count != n_items) {
1006
2.28k
        asdl_expr_seq *resized_spec =
1007
2.28k
            _Py_asdl_expr_seq_new(non_empty_count, p->arena);
1008
2.28k
        if (resized_spec == NULL) {
1009
0
            return NULL;
1010
0
        }
1011
2.28k
        Py_ssize_t j = 0;
1012
6.47k
        for (Py_ssize_t i = 0; i < n_items; i++) {
1013
4.18k
            expr_ty item = asdl_seq_GET(spec, i);
1014
4.18k
            if (item->kind == Constant_kind &&
1015
4.18k
                PyUnicode_CheckExact(item->v.Constant.value) &&
1016
4.18k
                PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1017
2.28k
                continue;
1018
2.28k
            }
1019
1.90k
            asdl_seq_SET(resized_spec, j++, item);
1020
1.90k
        }
1021
2.28k
        assert(j == non_empty_count);
1022
2.28k
        spec = resized_spec;
1023
2.28k
    }
1024
6.21k
    expr_ty res;
1025
6.21k
    Py_ssize_t n = asdl_seq_LEN(spec);
1026
6.21k
    if (n == 0 || (n == 1 && asdl_seq_GET(spec, 0)->kind == Constant_kind)) {
1027
5.14k
        res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno,
1028
5.14k
                                    end_col_offset, p->arena);
1029
5.14k
    } else {
1030
1.07k
        res = _PyPegen_concatenate_strings(p, spec,
1031
1.07k
                             lineno, col_offset, end_lineno,
1032
1.07k
                             end_col_offset, arena);
1033
1.07k
    }
1034
6.21k
    if (!res) {
1035
0
        return NULL;
1036
0
    }
1037
6.21k
    return result_token_with_metadata(p, res, colon->metadata);
1038
6.21k
}
1039
1040
const char *
1041
_PyPegen_get_expr_name(expr_ty e)
1042
192
{
1043
192
    assert(e != NULL);
1044
192
    switch (e->kind) {
1045
1
        case Attribute_kind:
1046
1
            return "attribute";
1047
1
        case Subscript_kind:
1048
1
            return "subscript";
1049
2
        case Starred_kind:
1050
2
            return "starred";
1051
10
        case Name_kind:
1052
10
            return "name";
1053
1
        case List_kind:
1054
1
            return "list";
1055
5
        case Tuple_kind:
1056
5
            return "tuple";
1057
1
        case Lambda_kind:
1058
1
            return "lambda";
1059
15
        case Call_kind:
1060
15
            return "function call";
1061
5
        case BoolOp_kind:
1062
20
        case BinOp_kind:
1063
31
        case UnaryOp_kind:
1064
31
            return "expression";
1065
1
        case GeneratorExp_kind:
1066
1
            return "generator expression";
1067
1
        case Yield_kind:
1068
2
        case YieldFrom_kind:
1069
2
            return "yield expression";
1070
1
        case Await_kind:
1071
1
            return "await expression";
1072
1
        case ListComp_kind:
1073
1
            return "list comprehension";
1074
1
        case SetComp_kind:
1075
1
            return "set comprehension";
1076
1
        case DictComp_kind:
1077
1
            return "dict comprehension";
1078
1
        case Dict_kind:
1079
1
            return "dict literal";
1080
1
        case Set_kind:
1081
1
            return "set display";
1082
7
        case JoinedStr_kind:
1083
7
        case FormattedValue_kind:
1084
7
            return "f-string expression";
1085
13
        case TemplateStr_kind:
1086
13
        case Interpolation_kind:
1087
13
            return "t-string expression";
1088
84
        case Constant_kind: {
1089
84
            PyObject *value = e->v.Constant.value;
1090
84
            if (value == Py_None) {
1091
1
                return "None";
1092
1
            }
1093
83
            if (value == Py_False) {
1094
1
                return "False";
1095
1
            }
1096
82
            if (value == Py_True) {
1097
1
                return "True";
1098
1
            }
1099
81
            if (value == Py_Ellipsis) {
1100
1
                return "ellipsis";
1101
1
            }
1102
80
            return "literal";
1103
81
        }
1104
10
        case Compare_kind:
1105
10
            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
192
    }
1116
192
}
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
33.6k
                     int end_col_offset, PyArena *arena) {
1129
33.6k
    Py_ssize_t args_len = asdl_seq_LEN(a);
1130
33.6k
    Py_ssize_t total_len = args_len;
1131
1132
33.6k
    if (b == NULL) {
1133
31.2k
        return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
1134
31.2k
                        end_lineno, end_col_offset, arena);
1135
1136
31.2k
    }
1137
1138
2.38k
    asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
1139
2.38k
    asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
1140
1141
2.38k
    if (starreds) {
1142
296
        total_len += asdl_seq_LEN(starreds);
1143
296
    }
1144
1145
2.38k
    asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
1146
2.38k
    if (args == NULL) {
1147
0
        return NULL;
1148
0
    }
1149
1150
2.38k
    Py_ssize_t i = 0;
1151
5.71k
    for (i = 0; i < args_len; i++) {
1152
3.32k
        asdl_seq_SET(args, i, asdl_seq_GET(a, i));
1153
3.32k
    }
1154
3.19k
    for (; i < total_len; i++) {
1155
806
        asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
1156
806
    }
1157
1158
2.38k
    return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
1159
2.38k
                       col_offset, end_lineno, end_col_offset, arena);
1160
2.38k
}
1161
1162
// AST Error reporting helpers
1163
1164
expr_ty
1165
_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
1166
8.48k
{
1167
8.48k
    if (e == NULL) {
1168
0
        return NULL;
1169
0
    }
1170
1171
8.48k
#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
1172
2.35k
        Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
1173
7.41k
        for (Py_ssize_t i = 0; i < len; i++) {\
1174
5.18k
            expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
1175
5.18k
            expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
1176
5.18k
            if (child != NULL) {\
1177
124
                return child;\
1178
124
            }\
1179
5.18k
        }\
1180
2.35k
    } 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
8.48k
    switch (e->kind) {
1189
809
        case List_kind:
1190
809
            VISIT_CONTAINER(e, List);
1191
772
            return NULL;
1192
1.54k
        case Tuple_kind:
1193
1.54k
            VISIT_CONTAINER(e, Tuple);
1194
1.46k
            return NULL;
1195
1.46k
        case Starred_kind:
1196
1.46k
            if (targets_type == DEL_TARGETS) {
1197
1
                return e;
1198
1
            }
1199
1.46k
            return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
1200
361
        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
361
            if (targets_type == FOR_TARGETS) {
1205
351
                cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
1206
351
                if (cmpop == In) {
1207
89
                    return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
1208
89
                }
1209
262
                return NULL;
1210
351
            }
1211
10
            return e;
1212
3.21k
        case Name_kind:
1213
3.83k
        case Subscript_kind:
1214
4.17k
        case Attribute_kind:
1215
4.17k
            return NULL;
1216
133
        default:
1217
133
            return e;
1218
8.48k
    }
1219
8.48k
}
1220
1221
30
void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
1222
30
    int kwarg_unpacking = 0;
1223
570
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
1224
540
        keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
1225
540
        if (!keyword->arg) {
1226
223
            kwarg_unpacking = 1;
1227
223
        }
1228
540
    }
1229
1230
30
    const char *msg = NULL;
1231
30
    if (kwarg_unpacking) {
1232
15
        msg = "positional argument follows keyword argument unpacking";
1233
15
    } else {
1234
15
        msg = "positional argument follows keyword argument";
1235
15
    }
1236
1237
30
    return RAISE_SYNTAX_ERROR(msg);
1238
30
}
1239
1240
void *
1241
_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions)
1242
301
{
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
301
    Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
1251
301
    if (len <= 1) {
1252
299
        return NULL;
1253
299
    }
1254
1255
2
    comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
1256
1257
2
    return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1258
301
        (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
1259
301
        _PyPegen_get_last_comprehension_item(last_comprehension),
1260
301
        "Generator expression must be parenthesized"
1261
301
    );
1262
301
}
1263
1264
// Fstring stuff
1265
1266
static expr_ty
1267
24.3k
_PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant, Token* token) {
1268
24.3k
    assert(PyUnicode_CheckExact(constant->v.Constant.value));
1269
1270
24.3k
    const char* bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
1271
24.3k
    if (bstr == NULL) {
1272
0
        return NULL;
1273
0
    }
1274
1275
24.3k
    size_t len;
1276
24.3k
    if (strcmp(bstr, "{{") == 0 || strcmp(bstr, "}}") == 0) {
1277
0
        len = 1;
1278
24.3k
    } else {
1279
24.3k
        len = strlen(bstr);
1280
24.3k
    }
1281
1282
24.3k
    is_raw = is_raw || strchr(bstr, '\\') == NULL;
1283
24.3k
    PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
1284
24.3k
    if (str == NULL) {
1285
7
        _Pypegen_raise_decode_error(p);
1286
7
        return NULL;
1287
7
    }
1288
24.3k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1289
0
        Py_DECREF(str);
1290
0
        return NULL;
1291
0
    }
1292
24.3k
    return _PyAST_Constant(str, NULL, constant->lineno, constant->col_offset,
1293
24.3k
                           constant->end_lineno, constant->end_col_offset,
1294
24.3k
                           p->arena);
1295
24.3k
}
1296
1297
static asdl_expr_seq *
1298
_get_resized_exprs(Parser *p, Token *a, asdl_expr_seq *raw_expressions, Token *b, enum string_kind_t string_kind)
1299
15.5k
{
1300
15.5k
    Py_ssize_t n_items = asdl_seq_LEN(raw_expressions);
1301
15.5k
    Py_ssize_t total_items = n_items;
1302
55.5k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1303
39.9k
        expr_ty item = asdl_seq_GET(raw_expressions, i);
1304
39.9k
        if (item->kind == JoinedStr_kind) {
1305
5.64k
            total_items += asdl_seq_LEN(item->v.JoinedStr.values) - 1;
1306
5.64k
        }
1307
39.9k
    }
1308
1309
15.5k
    const char* quote_str = PyBytes_AsString(a->bytes);
1310
15.5k
    if (quote_str == NULL) {
1311
0
        return NULL;
1312
0
    }
1313
15.5k
    int is_raw = strpbrk(quote_str, "rR") != NULL;
1314
1315
15.5k
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(total_items, p->arena);
1316
15.5k
    if (seq == NULL) {
1317
0
        return NULL;
1318
0
    }
1319
1320
15.5k
    Py_ssize_t index = 0;
1321
55.5k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1322
39.9k
        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
39.9k
        if (item->kind == JoinedStr_kind) {
1329
5.64k
            asdl_expr_seq *values = item->v.JoinedStr.values;
1330
5.64k
            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.64k
            expr_ty first = asdl_seq_GET(values, 0);
1340
5.64k
            assert(first->kind == Constant_kind);
1341
5.64k
            asdl_seq_SET(seq, index++, first);
1342
1343
5.64k
            expr_ty second = asdl_seq_GET(values, 1);
1344
5.64k
            assert((string_kind == TSTRING && second->kind == Interpolation_kind) || second->kind == FormattedValue_kind);
1345
5.64k
            asdl_seq_SET(seq, index++, second);
1346
1347
5.64k
            continue;
1348
5.64k
        }
1349
1350
34.2k
        if (item->kind == Constant_kind) {
1351
24.3k
            item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
1352
24.3k
            if (item == NULL) {
1353
7
                return NULL;
1354
7
            }
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
24.3k
            if (PyUnicode_CheckExact(item->v.Constant.value)
1360
24.3k
                && PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1361
432
                continue;
1362
432
            }
1363
24.3k
        }
1364
33.8k
        asdl_seq_SET(seq, index++, item);
1365
33.8k
    }
1366
1367
15.5k
    asdl_expr_seq *resized_exprs;
1368
15.5k
    if (index != total_items) {
1369
432
        resized_exprs = _Py_asdl_expr_seq_new(index, p->arena);
1370
432
        if (resized_exprs == NULL) {
1371
0
            return NULL;
1372
0
        }
1373
868
        for (Py_ssize_t i = 0; i < index; i++) {
1374
436
            asdl_seq_SET(resized_exprs, i, asdl_seq_GET(seq, i));
1375
436
        }
1376
432
    }
1377
15.1k
    else {
1378
15.1k
        resized_exprs = seq;
1379
15.1k
    }
1380
15.5k
    return resized_exprs;
1381
15.5k
}
1382
1383
expr_ty
1384
2.40k
_PyPegen_template_str(Parser *p, Token *a, asdl_expr_seq *raw_expressions, Token *b) {
1385
1386
2.40k
    asdl_expr_seq *resized_exprs = _get_resized_exprs(p, a, raw_expressions, b, TSTRING);
1387
2.40k
    return _PyAST_TemplateStr(resized_exprs, a->lineno, a->col_offset,
1388
2.40k
                              b->end_lineno, b->end_col_offset,
1389
2.40k
                              p->arena);
1390
2.40k
}
1391
1392
expr_ty
1393
13.1k
_PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* raw_expressions, Token*b) {
1394
1395
13.1k
    asdl_expr_seq *resized_exprs = _get_resized_exprs(p, a, raw_expressions, b, FSTRING);
1396
13.1k
    return _PyAST_JoinedStr(resized_exprs, a->lineno, a->col_offset,
1397
13.1k
                            b->end_lineno, b->end_col_offset,
1398
13.1k
                            p->arena);
1399
13.1k
}
1400
1401
9.52k
expr_ty _PyPegen_decoded_constant_from_token(Parser* p, Token* tok) {
1402
9.52k
    Py_ssize_t bsize;
1403
9.52k
    char* bstr;
1404
9.52k
    if (PyBytes_AsStringAndSize(tok->bytes, &bstr, &bsize) == -1) {
1405
0
        return NULL;
1406
0
    }
1407
9.52k
    PyObject* str = _PyPegen_decode_string(p, 0, bstr, bsize, tok);
1408
9.52k
    if (str == NULL) {
1409
2
        return NULL;
1410
2
    }
1411
9.51k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1412
0
        Py_DECREF(str);
1413
0
        return NULL;
1414
0
    }
1415
9.51k
    return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1416
9.51k
                           tok->end_lineno, tok->end_col_offset,
1417
9.51k
                           p->arena);
1418
9.51k
}
1419
1420
32.2k
expr_ty _PyPegen_constant_from_token(Parser* p, Token* tok) {
1421
32.2k
    char* bstr = PyBytes_AsString(tok->bytes);
1422
32.2k
    if (bstr == NULL) {
1423
0
        return NULL;
1424
0
    }
1425
32.2k
    PyObject* str = PyUnicode_FromString(bstr);
1426
32.2k
    if (str == NULL) {
1427
7
        return NULL;
1428
7
    }
1429
32.2k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1430
0
        Py_DECREF(str);
1431
0
        return NULL;
1432
0
    }
1433
32.2k
    return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1434
32.2k
                           tok->end_lineno, tok->end_col_offset,
1435
32.2k
                           p->arena);
1436
32.2k
}
1437
1438
64.9k
expr_ty _PyPegen_constant_from_string(Parser* p, Token* tok) {
1439
64.9k
    char* the_str = PyBytes_AsString(tok->bytes);
1440
64.9k
    if (the_str == NULL) {
1441
0
        return NULL;
1442
0
    }
1443
64.9k
    PyObject *s = _PyPegen_parse_string(p, tok);
1444
64.9k
    if (s == NULL) {
1445
373
        _Pypegen_raise_decode_error(p);
1446
373
        return NULL;
1447
373
    }
1448
64.5k
    if (_PyArena_AddPyObject(p->arena, s) < 0) {
1449
0
        Py_DECREF(s);
1450
0
        return NULL;
1451
0
    }
1452
64.5k
    PyObject *kind = NULL;
1453
64.5k
    if (the_str && the_str[0] == 'u') {
1454
300
        kind = _PyPegen_new_identifier(p, "u");
1455
300
        if (kind == NULL) {
1456
0
            return NULL;
1457
0
        }
1458
300
    }
1459
64.5k
    return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno, tok->end_col_offset, p->arena);
1460
64.5k
}
1461
1462
static int
1463
_get_interpolation_conversion(Parser *p, Token *debug, ResultTokenWithMetadata *conversion,
1464
                              ResultTokenWithMetadata *format)
1465
24.2k
{
1466
24.2k
    if (conversion != NULL) {
1467
1.43k
        expr_ty conversion_expr = (expr_ty) conversion->result;
1468
1.43k
        assert(conversion_expr->kind == Name_kind);
1469
1.43k
        Py_UCS4 first = PyUnicode_READ_CHAR(conversion_expr->v.Name.id, 0);
1470
1.43k
        return Py_SAFE_DOWNCAST(first, Py_UCS4, int);
1471
1.43k
    }
1472
22.8k
    else if (debug && !format) {
1473
        /* If no conversion is specified, use !r for debug expressions */
1474
5.77k
        return (int)'r';
1475
5.77k
    }
1476
17.0k
    return -1;
1477
24.2k
}
1478
1479
static PyObject *
1480
_strip_interpolation_expr(PyObject *exprstr)
1481
4.31k
{
1482
4.31k
    Py_ssize_t len = PyUnicode_GET_LENGTH(exprstr);
1483
1484
12.5k
    for (Py_ssize_t i = len - 1; i >= 0; i--) {
1485
12.5k
        Py_UCS4 c = PyUnicode_READ_CHAR(exprstr, i);
1486
12.5k
        if (_PyUnicode_IsWhitespace(c) || c == '=') {
1487
8.22k
            len--;
1488
8.22k
        }
1489
4.31k
        else {
1490
4.31k
            break;
1491
4.31k
        }
1492
12.5k
    }
1493
1494
4.31k
    return PyUnicode_Substring(exprstr, 0, len);
1495
4.31k
}
1496
1497
expr_ty _PyPegen_interpolation(Parser *p, expr_ty expression, Token *debug, ResultTokenWithMetadata *conversion,
1498
                                 ResultTokenWithMetadata *format, Token *closing_brace, int lineno, int col_offset,
1499
4.31k
                                 int end_lineno, int end_col_offset, PyArena *arena) {
1500
1501
4.31k
    int conversion_val = _get_interpolation_conversion(p, debug, conversion, format);
1502
1503
    /* Find the non whitespace token after the "=" */
1504
4.31k
    int debug_end_line, debug_end_offset;
1505
4.31k
    PyObject *debug_metadata;
1506
4.31k
    constant exprstr;
1507
1508
4.31k
    if (conversion) {
1509
714
        debug_end_line = ((expr_ty) conversion->result)->lineno;
1510
714
        debug_end_offset = ((expr_ty) conversion->result)->col_offset;
1511
714
        debug_metadata = exprstr = conversion->metadata;
1512
714
    }
1513
3.59k
    else if (format) {
1514
666
        debug_end_line = ((expr_ty) format->result)->lineno;
1515
666
        debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1516
666
        debug_metadata = exprstr = format->metadata;
1517
666
    }
1518
2.93k
    else {
1519
2.93k
        debug_end_line = end_lineno;
1520
2.93k
        debug_end_offset = end_col_offset;
1521
2.93k
        debug_metadata = exprstr = closing_brace->metadata;
1522
2.93k
    }
1523
1524
4.31k
    assert(exprstr != NULL);
1525
4.31k
    PyObject *final_exprstr = _strip_interpolation_expr(exprstr);
1526
4.31k
    if (!final_exprstr || _PyArena_AddPyObject(arena, final_exprstr) < 0) {
1527
0
        Py_XDECREF(final_exprstr);
1528
0
        return NULL;
1529
0
    }
1530
1531
4.31k
    expr_ty interpolation = _PyAST_Interpolation(
1532
4.31k
        expression, final_exprstr, conversion_val, format ? (expr_ty) format->result : NULL,
1533
4.31k
        lineno, col_offset, end_lineno,
1534
4.31k
        end_col_offset, arena
1535
4.31k
    );
1536
1537
4.31k
    if (!debug) {
1538
2.93k
        return interpolation;
1539
2.93k
    }
1540
1541
1.38k
    expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1542
1.38k
                                            debug_end_offset - 1, p->arena);
1543
1.38k
    if (!debug_text) {
1544
0
        return NULL;
1545
0
    }
1546
1547
1.38k
    asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1548
1.38k
    asdl_seq_SET(values, 0, debug_text);
1549
1.38k
    asdl_seq_SET(values, 1, interpolation);
1550
1.38k
    return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1551
1.38k
}
1552
1553
expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug, ResultTokenWithMetadata *conversion,
1554
                                 ResultTokenWithMetadata *format, Token *closing_brace, int lineno, int col_offset,
1555
19.9k
                                 int end_lineno, int end_col_offset, PyArena *arena) {
1556
19.9k
    int conversion_val = _get_interpolation_conversion(p, debug, conversion, format);
1557
1558
19.9k
    expr_ty formatted_value = _PyAST_FormattedValue(
1559
19.9k
        expression, conversion_val, format ? (expr_ty) format->result : NULL,
1560
19.9k
        lineno, col_offset, end_lineno,
1561
19.9k
        end_col_offset, arena
1562
19.9k
    );
1563
1564
19.9k
    if (!debug) {
1565
15.0k
        return formatted_value;
1566
15.0k
    }
1567
1568
    /* Find the non whitespace token after the "=" */
1569
4.94k
    int debug_end_line, debug_end_offset;
1570
4.94k
    PyObject *debug_metadata;
1571
1572
4.94k
    if (conversion) {
1573
194
        debug_end_line = ((expr_ty) conversion->result)->lineno;
1574
194
        debug_end_offset = ((expr_ty) conversion->result)->col_offset;
1575
194
        debug_metadata = conversion->metadata;
1576
194
    }
1577
4.75k
    else if (format) {
1578
76
        debug_end_line = ((expr_ty) format->result)->lineno;
1579
76
        debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1580
76
        debug_metadata = format->metadata;
1581
76
    }
1582
4.67k
    else {
1583
4.67k
        debug_end_line = end_lineno;
1584
4.67k
        debug_end_offset = end_col_offset;
1585
4.67k
        debug_metadata = closing_brace->metadata;
1586
4.67k
    }
1587
4.94k
    expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1588
4.94k
                                            debug_end_offset - 1, p->arena);
1589
4.94k
    if (!debug_text) {
1590
3
        return NULL;
1591
3
    }
1592
1593
4.94k
    asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1594
4.94k
    asdl_seq_SET(values, 0, debug_text);
1595
4.94k
    asdl_seq_SET(values, 1, formatted_value);
1596
4.94k
    return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1597
4.94k
}
1598
1599
static expr_ty
1600
_build_concatenated_bytes(Parser *p, asdl_expr_seq *strings, int lineno,
1601
                        int col_offset, int end_lineno, int end_col_offset,
1602
                        PyArena *arena)
1603
698
{
1604
698
    Py_ssize_t len = asdl_seq_LEN(strings);
1605
698
    assert(len > 0);
1606
1607
698
    PyObject* res = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
1608
1609
    /* Bytes literals never get a kind, but just for consistency
1610
        since they are represented as Constant nodes, we'll mirror
1611
        the same behavior as unicode strings for determining the
1612
        kind. */
1613
698
    PyObject* kind = asdl_seq_GET(strings, 0)->v.Constant.kind;
1614
3.84k
    for (Py_ssize_t i = 0; i < len; i++) {
1615
3.14k
        expr_ty elem = asdl_seq_GET(strings, i);
1616
3.14k
        PyBytes_Concat(&res, elem->v.Constant.value);
1617
3.14k
    }
1618
698
    if (!res || _PyArena_AddPyObject(arena, res) < 0) {
1619
0
        Py_XDECREF(res);
1620
0
        return NULL;
1621
0
    }
1622
698
    return _PyAST_Constant(res, kind, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1623
698
}
1624
1625
static expr_ty
1626
_build_concatenated_unicode(Parser *p, asdl_expr_seq *strings, int lineno,
1627
                        int col_offset, int end_lineno, int end_col_offset,
1628
                        PyArena *arena)
1629
1.36k
{
1630
1.36k
    Py_ssize_t len = asdl_seq_LEN(strings);
1631
1.36k
    assert(len > 1);
1632
1633
1.36k
    expr_ty first = asdl_seq_GET(strings, 0);
1634
1635
    /* When a string is getting concatenated, the kind of the string
1636
        is determined by the first string in the concatenation
1637
        sequence.
1638
1639
        u"abc" "def" -> u"abcdef"
1640
        "abc" u"abc" ->  "abcabc" */
1641
1.36k
    PyObject *kind = first->v.Constant.kind;
1642
1643
1.36k
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1644
1.36k
    if (writer == NULL) {
1645
0
        return NULL;
1646
0
    }
1647
1648
22.2k
    for (Py_ssize_t i = 0; i < len; i++) {
1649
20.9k
        expr_ty current_elem = asdl_seq_GET(strings, i);
1650
20.9k
        assert(current_elem->kind == Constant_kind);
1651
1652
20.9k
        if (PyUnicodeWriter_WriteStr(writer,
1653
20.9k
                                     current_elem->v.Constant.value)) {
1654
0
            PyUnicodeWriter_Discard(writer);
1655
0
            return NULL;
1656
0
        }
1657
20.9k
    }
1658
1659
1.36k
    PyObject *final = PyUnicodeWriter_Finish(writer);
1660
1.36k
    if (final == NULL) {
1661
0
        return NULL;
1662
0
    }
1663
1.36k
    if (_PyArena_AddPyObject(p->arena, final) < 0) {
1664
0
        Py_DECREF(final);
1665
0
        return NULL;
1666
0
    }
1667
1.36k
    return _PyAST_Constant(final, kind, lineno, col_offset,
1668
1.36k
                           end_lineno, end_col_offset, arena);
1669
1.36k
}
1670
1671
static asdl_expr_seq *
1672
_build_concatenated_str(Parser *p, asdl_expr_seq *strings,
1673
                               int lineno, int col_offset, int end_lineno,
1674
                               int end_col_offset, PyArena *arena)
1675
11.8k
{
1676
11.8k
    Py_ssize_t len = asdl_seq_LEN(strings);
1677
11.8k
    assert(len > 0);
1678
1679
11.8k
    Py_ssize_t n_flattened_elements = 0;
1680
41.3k
    for (Py_ssize_t i = 0; i < len; i++) {
1681
29.4k
        expr_ty elem = asdl_seq_GET(strings, i);
1682
29.4k
        switch(elem->kind) {
1683
12.9k
            case JoinedStr_kind:
1684
12.9k
                n_flattened_elements += asdl_seq_LEN(elem->v.JoinedStr.values);
1685
12.9k
                break;
1686
2.64k
            case TemplateStr_kind:
1687
2.64k
                n_flattened_elements += asdl_seq_LEN(elem->v.TemplateStr.values);
1688
2.64k
                break;
1689
13.9k
            default:
1690
13.9k
                n_flattened_elements++;
1691
13.9k
                break;
1692
29.4k
        }
1693
29.4k
    }
1694
1695
1696
11.8k
    asdl_expr_seq* flattened = _Py_asdl_expr_seq_new(n_flattened_elements, p->arena);
1697
11.8k
    if (flattened == NULL) {
1698
0
        return NULL;
1699
0
    }
1700
1701
    /* build flattened list */
1702
11.8k
    Py_ssize_t current_pos = 0;
1703
41.3k
    for (Py_ssize_t i = 0; i < len; i++) {
1704
29.4k
        expr_ty elem = asdl_seq_GET(strings, i);
1705
29.4k
        switch(elem->kind) {
1706
12.9k
            case JoinedStr_kind:
1707
50.6k
                for (Py_ssize_t j = 0; j < asdl_seq_LEN(elem->v.JoinedStr.values); j++) {
1708
37.6k
                    expr_ty subvalue = asdl_seq_GET(elem->v.JoinedStr.values, j);
1709
37.6k
                    if (subvalue == NULL) {
1710
0
                        return NULL;
1711
0
                    }
1712
37.6k
                    asdl_seq_SET(flattened, current_pos++, subvalue);
1713
37.6k
                }
1714
12.9k
                break;
1715
12.9k
            case TemplateStr_kind:
1716
9.99k
                for (Py_ssize_t j = 0; j < asdl_seq_LEN(elem->v.TemplateStr.values); j++) {
1717
7.34k
                    expr_ty subvalue = asdl_seq_GET(elem->v.TemplateStr.values, j);
1718
7.34k
                    if (subvalue == NULL) {
1719
0
                        return NULL;
1720
0
                    }
1721
7.34k
                    asdl_seq_SET(flattened, current_pos++, subvalue);
1722
7.34k
                }
1723
2.64k
                break;
1724
13.9k
            default:
1725
13.9k
                asdl_seq_SET(flattened, current_pos++, elem);
1726
13.9k
                break;
1727
29.4k
        }
1728
29.4k
    }
1729
1730
    /* calculate folded element count */
1731
11.8k
    Py_ssize_t n_elements = 0;
1732
11.8k
    int prev_is_constant = 0;
1733
70.8k
    for (Py_ssize_t i = 0; i < n_flattened_elements; i++) {
1734
58.9k
        expr_ty elem = asdl_seq_GET(flattened, i);
1735
1736
        /* The concatenation of a FormattedValue and an empty Constant should
1737
           lead to the FormattedValue itself. Thus, we will not take any empty
1738
           constants into account, just as in `_PyPegen_joined_str` */
1739
58.9k
        if (elem->kind == Constant_kind &&
1740
58.9k
            PyUnicode_CheckExact(elem->v.Constant.value) &&
1741
58.9k
            PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0)
1742
1.89k
            continue;
1743
1744
57.0k
        if (!prev_is_constant || elem->kind != Constant_kind) {
1745
44.2k
            n_elements++;
1746
44.2k
        }
1747
57.0k
        prev_is_constant = elem->kind == Constant_kind;
1748
57.0k
    }
1749
1750
11.8k
    asdl_expr_seq* values = _Py_asdl_expr_seq_new(n_elements, p->arena);
1751
11.8k
    if (values == NULL) {
1752
0
        return NULL;
1753
0
    }
1754
1755
    /* build folded list */
1756
11.8k
    current_pos = 0;
1757
56.4k
    for (Py_ssize_t i = 0; i < n_flattened_elements; i++) {
1758
44.5k
        expr_ty elem = asdl_seq_GET(flattened, i);
1759
1760
        /* if the current elem and the following are constants,
1761
           fold them and all consequent constants */
1762
44.5k
        if (elem->kind == Constant_kind) {
1763
24.7k
            if (i + 1 < n_flattened_elements &&
1764
24.7k
                asdl_seq_GET(flattened, i + 1)->kind == Constant_kind) {
1765
5.39k
                expr_ty first_elem = elem;
1766
1767
                /* When a string is getting concatenated, the kind of the string
1768
                   is determined by the first string in the concatenation
1769
                   sequence.
1770
1771
                   u"abc" "def" -> u"abcdef"
1772
                   "abc" u"abc" ->  "abcabc" */
1773
5.39k
                PyObject *kind = elem->v.Constant.kind;
1774
1775
5.39k
                PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1776
5.39k
                if (writer == NULL) {
1777
0
                    return NULL;
1778
0
                }
1779
5.39k
                expr_ty last_elem = elem;
1780
5.39k
                Py_ssize_t j;
1781
25.1k
                for (j = i; j < n_flattened_elements; j++) {
1782
23.1k
                    expr_ty current_elem = asdl_seq_GET(flattened, j);
1783
23.1k
                    if (current_elem->kind == Constant_kind) {
1784
19.7k
                        if (PyUnicodeWriter_WriteStr(writer,
1785
19.7k
                                                     current_elem->v.Constant.value)) {
1786
0
                            PyUnicodeWriter_Discard(writer);
1787
0
                            return NULL;
1788
0
                        }
1789
19.7k
                        last_elem = current_elem;
1790
19.7k
                    } else {
1791
3.39k
                        break;
1792
3.39k
                    }
1793
23.1k
                }
1794
5.39k
                i = j - 1;
1795
1796
5.39k
                PyObject *concat_str = PyUnicodeWriter_Finish(writer);
1797
5.39k
                if (concat_str == NULL) {
1798
0
                    return NULL;
1799
0
                }
1800
5.39k
                if (_PyArena_AddPyObject(p->arena, concat_str) < 0) {
1801
0
                    Py_DECREF(concat_str);
1802
0
                    return NULL;
1803
0
                }
1804
5.39k
                elem = _PyAST_Constant(concat_str, kind, first_elem->lineno,
1805
5.39k
                                       first_elem->col_offset,
1806
5.39k
                                       last_elem->end_lineno,
1807
5.39k
                                       last_elem->end_col_offset, p->arena);
1808
5.39k
                if (elem == NULL) {
1809
0
                    return NULL;
1810
0
                }
1811
5.39k
            }
1812
1813
            /* Drop all empty contanst strings */
1814
24.7k
            if (PyUnicode_CheckExact(elem->v.Constant.value) &&
1815
24.7k
                PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0) {
1816
300
                continue;
1817
300
            }
1818
24.7k
        }
1819
1820
44.2k
        asdl_seq_SET(values, current_pos++, elem);
1821
44.2k
    }
1822
1823
11.8k
    assert(current_pos == n_elements);
1824
11.8k
    return values;
1825
11.8k
}
1826
1827
static expr_ty
1828
_build_concatenated_joined_str(Parser *p, asdl_expr_seq *strings,
1829
                               int lineno, int col_offset, int end_lineno,
1830
                               int end_col_offset, PyArena *arena)
1831
10.3k
{
1832
10.3k
    asdl_expr_seq *values = _build_concatenated_str(p, strings, lineno,
1833
10.3k
        col_offset, end_lineno, end_col_offset, arena);
1834
10.3k
    return _PyAST_JoinedStr(values, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1835
10.3k
}
1836
1837
static expr_ty
1838
_build_concatenated_template_str(Parser *p, asdl_expr_seq *strings,
1839
                               int lineno, int col_offset, int end_lineno,
1840
                               int end_col_offset, PyArena *arena)
1841
1.50k
{
1842
1.50k
    asdl_expr_seq *values = _build_concatenated_str(p, strings, lineno,
1843
1.50k
        col_offset, end_lineno, end_col_offset, arena);
1844
1.50k
    return _PyAST_TemplateStr(values, lineno, col_offset, end_lineno,
1845
1.50k
        end_col_offset, arena);
1846
1.50k
}
1847
1848
expr_ty
1849
_PyPegen_concatenate_strings(Parser *p, asdl_expr_seq *strings,
1850
                             int lineno, int col_offset, int end_lineno,
1851
                             int end_col_offset, PyArena *arena)
1852
49.0k
{
1853
49.0k
    Py_ssize_t len = asdl_seq_LEN(strings);
1854
49.0k
    assert(len > 0);
1855
1856
49.0k
    int t_string_found = 0;
1857
49.0k
    int f_string_found = 0;
1858
49.0k
    int unicode_string_found = 0;
1859
49.0k
    int bytes_found = 0;
1860
1861
49.0k
    Py_ssize_t i = 0;
1862
137k
    for (i = 0; i < len; i++) {
1863
88.6k
        expr_ty elem = asdl_seq_GET(strings, i);
1864
88.6k
        switch(elem->kind) {
1865
68.8k
            case Constant_kind:
1866
68.8k
                if (PyBytes_CheckExact(elem->v.Constant.value)) {
1867
5.88k
                    bytes_found = 1;
1868
62.9k
                } else {
1869
62.9k
                    unicode_string_found = 1;
1870
62.9k
                }
1871
68.8k
                break;
1872
12.9k
            case JoinedStr_kind:
1873
12.9k
                f_string_found = 1;
1874
12.9k
                break;
1875
2.64k
            case TemplateStr_kind:
1876
2.64k
                t_string_found = 1;
1877
2.64k
                break;
1878
4.25k
            default:
1879
4.25k
                f_string_found = 1;
1880
4.25k
                break;
1881
88.6k
        }
1882
88.6k
    }
1883
1884
    // Cannot mix unicode and bytes
1885
49.0k
    if ((unicode_string_found || f_string_found || t_string_found) && bytes_found) {
1886
4
        RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1887
4
        return NULL;
1888
4
    }
1889
1890
    // If it's only bytes or only unicode string, do a simple concat
1891
49.0k
    if (!f_string_found && !t_string_found) {
1892
37.1k
        if (len == 1) {
1893
35.1k
            return asdl_seq_GET(strings, 0);
1894
35.1k
        }
1895
2.06k
        else if (bytes_found) {
1896
698
            return _build_concatenated_bytes(p, strings, lineno, col_offset,
1897
698
                end_lineno, end_col_offset, arena);
1898
698
        }
1899
1.36k
        else {
1900
1.36k
            return _build_concatenated_unicode(p, strings, lineno, col_offset,
1901
1.36k
                end_lineno, end_col_offset, arena);
1902
1.36k
        }
1903
37.1k
    }
1904
1905
11.8k
    if (t_string_found) {
1906
1.50k
        return _build_concatenated_template_str(p, strings, lineno,
1907
1.50k
            col_offset, end_lineno, end_col_offset, arena);
1908
1.50k
    }
1909
1910
10.3k
    return _build_concatenated_joined_str(p, strings, lineno,
1911
10.3k
        col_offset, end_lineno, end_col_offset, arena);
1912
11.8k
}
1913
1914
stmt_ty
1915
_PyPegen_checked_future_import(Parser *p, identifier module, asdl_alias_seq * names, int level,
1916
                           int lineno, int col_offset, int end_lineno, int end_col_offset,
1917
1.78k
                             PyArena *arena) {
1918
1.78k
    if (level == 0 && PyUnicode_CompareWithASCIIString(module, "__future__") == 0) {
1919
1.47k
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(names); i++) {
1920
889
            alias_ty alias = asdl_seq_GET(names, i);
1921
889
            if (PyUnicode_CompareWithASCIIString(alias->name, "barry_as_FLUFL") == 0) {
1922
73
                p->flags |= PyPARSE_BARRY_AS_BDFL;
1923
73
            }
1924
889
        }
1925
582
    }
1926
1.78k
    return _PyAST_ImportFrom(module, names, level, lineno, col_offset, end_lineno, end_col_offset, arena);
1927
1.78k
}
1928
1929
asdl_stmt_seq*
1930
27.0k
_PyPegen_register_stmts(Parser *p, asdl_stmt_seq* stmts) {
1931
27.0k
    if (!p->call_invalid_rules) {
1932
25.1k
        return stmts;
1933
25.1k
    }
1934
1.92k
    Py_ssize_t len = asdl_seq_LEN(stmts);
1935
1.92k
    if (len == 0) {
1936
0
        return stmts;
1937
0
    }
1938
1.92k
    stmt_ty last_stmt = asdl_seq_GET(stmts, len - 1);
1939
1.92k
    p->last_stmt_location.lineno = last_stmt->lineno;
1940
1.92k
    p->last_stmt_location.col_offset = last_stmt->col_offset;
1941
1.92k
    p->last_stmt_location.end_lineno = last_stmt->end_lineno;
1942
1.92k
    p->last_stmt_location.end_col_offset = last_stmt->end_col_offset;
1943
1.92k
    return stmts;
1944
1.92k
}