Coverage Report

Created: 2025-07-04 06:49

/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.1k
{
13
76.1k
    return &_PyRuntime.parser.dummy_name;
14
76.1k
}
15
16
/* Creates a single-element asdl_seq* that contains a */
17
asdl_seq *
18
_PyPegen_singleton_seq(Parser *p, void *a)
19
184k
{
20
184k
    assert(a != NULL);
21
184k
    asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
22
184k
    if (!seq) {
23
0
        return NULL;
24
0
    }
25
184k
    asdl_seq_SET_UNTYPED(seq, 0, a);
26
184k
    return seq;
27
184k
}
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
395k
{
33
395k
    assert(a != NULL);
34
395k
    if (!seq) {
35
11.2k
        return _PyPegen_singleton_seq(p, a);
36
11.2k
    }
37
38
384k
    asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
39
384k
    if (!new_seq) {
40
0
        return NULL;
41
0
    }
42
43
384k
    asdl_seq_SET_UNTYPED(new_seq, 0, a);
44
695k
    for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
45
310k
        asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
46
310k
    }
47
384k
    return new_seq;
48
384k
}
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.3k
{
74
27.3k
    Py_ssize_t size = 0;
75
142k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
76
114k
        asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
77
114k
        size += asdl_seq_LEN(inner_seq);
78
114k
    }
79
27.3k
    return size;
80
27.3k
}
81
82
/* Flattens an asdl_seq* of asdl_seq*s */
83
asdl_seq *
84
_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
85
27.3k
{
86
27.3k
    Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
87
27.3k
    assert(flattened_seq_size > 0);
88
89
27.3k
    asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
90
27.3k
    if (!flattened_seq) {
91
0
        return NULL;
92
0
    }
93
94
27.3k
    int flattened_seq_idx = 0;
95
142k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
96
114k
        asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
97
236k
        for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
98
122k
            asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
99
122k
        }
100
114k
    }
101
27.3k
    assert(flattened_seq_idx == flattened_seq_size);
102
103
27.3k
    return flattened_seq;
104
27.3k
}
105
106
void *
107
_PyPegen_seq_last_item(asdl_seq *seq)
108
1.25k
{
109
1.25k
    Py_ssize_t len = asdl_seq_LEN(seq);
110
1.25k
    return asdl_seq_GET_UNTYPED(seq, len - 1);
111
1.25k
}
112
113
void *
114
_PyPegen_seq_first_item(asdl_seq *seq)
115
1.23k
{
116
1.23k
    return asdl_seq_GET_UNTYPED(seq, 0);
117
1.23k
}
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
1.94k
{
123
1.94k
    assert(first_name != NULL && second_name != NULL);
124
1.94k
    PyObject *uni = PyUnicode_FromFormat("%U.%U",
125
1.94k
            first_name->v.Name.id, second_name->v.Name.id);
126
1.94k
    if (!uni) {
127
0
        return NULL;
128
0
    }
129
1.94k
    PyInterpreterState *interp = _PyInterpreterState_GET();
130
1.94k
    _PyUnicode_InternImmortal(interp, &uni);
131
1.94k
    if (_PyArena_AddPyObject(p->arena, uni) < 0) {
132
0
        Py_DECREF(uni);
133
0
        return NULL;
134
0
    }
135
136
1.94k
    return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
137
1.94k
}
138
139
/* Counts the total number of dots in seq's tokens */
140
int
141
_PyPegen_seq_count_dots(asdl_seq *seq)
142
2.87k
{
143
2.87k
    int number_of_dots = 0;
144
6.61k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
145
3.74k
        Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
146
3.74k
        switch (current_expr->type) {
147
1.93k
            case ELLIPSIS:
148
1.93k
                number_of_dots += 3;
149
1.93k
                break;
150
1.81k
            case DOT:
151
1.81k
                number_of_dots += 1;
152
1.81k
                break;
153
0
            default:
154
0
                Py_UNREACHABLE();
155
3.74k
        }
156
3.74k
    }
157
158
2.87k
    return number_of_dots;
159
2.87k
}
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
638
                        int end_col_offset, PyArena *arena) {
165
638
    PyObject *str = PyUnicode_InternFromString("*");
166
638
    if (!str) {
167
0
        return NULL;
168
0
    }
169
638
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
170
0
        Py_DECREF(str);
171
0
        return NULL;
172
0
    }
173
638
    return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
174
638
}
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.42k
{
180
2.42k
    Py_ssize_t len = asdl_seq_LEN(seq);
181
2.42k
    assert(len > 0);
182
183
2.42k
    asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
184
2.42k
    if (!new_seq) {
185
0
        return NULL;
186
0
    }
187
8.34k
    for (Py_ssize_t i = 0; i < len; i++) {
188
5.91k
        expr_ty e = asdl_seq_GET(seq, i);
189
5.91k
        asdl_seq_SET(new_seq, i, e->v.Name.id);
190
5.91k
    }
191
2.42k
    return new_seq;
192
2.42k
}
193
194
/* Constructs a CmpopExprPair */
195
CmpopExprPair *
196
_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
197
23.5k
{
198
23.5k
    assert(expr != NULL);
199
23.5k
    CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
200
23.5k
    if (!a) {
201
0
        return NULL;
202
0
    }
203
23.5k
    a->cmpop = cmpop;
204
23.5k
    a->expr = expr;
205
23.5k
    return a;
206
23.5k
}
207
208
asdl_int_seq *
209
_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
210
9.67k
{
211
9.67k
    Py_ssize_t len = asdl_seq_LEN(seq);
212
9.67k
    assert(len > 0);
213
214
9.67k
    asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
215
9.67k
    if (!new_seq) {
216
0
        return NULL;
217
0
    }
218
32.5k
    for (Py_ssize_t i = 0; i < len; i++) {
219
22.9k
        CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
220
22.9k
        asdl_seq_SET(new_seq, i, pair->cmpop);
221
22.9k
    }
222
9.67k
    return new_seq;
223
9.67k
}
224
225
asdl_expr_seq *
226
_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
227
9.67k
{
228
9.67k
    Py_ssize_t len = asdl_seq_LEN(seq);
229
9.67k
    assert(len > 0);
230
231
9.67k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
232
9.67k
    if (!new_seq) {
233
0
        return NULL;
234
0
    }
235
32.5k
    for (Py_ssize_t i = 0; i < len; i++) {
236
22.9k
        CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
237
22.9k
        asdl_seq_SET(new_seq, i, pair->expr);
238
22.9k
    }
239
9.67k
    return new_seq;
240
9.67k
}
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.55k
{
246
6.55k
    Py_ssize_t len = asdl_seq_LEN(seq);
247
6.55k
    if (len == 0) {
248
2.89k
        return NULL;
249
2.89k
    }
250
251
3.65k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
252
3.65k
    if (!new_seq) {
253
0
        return NULL;
254
0
    }
255
10.1k
    for (Py_ssize_t i = 0; i < len; i++) {
256
6.49k
        expr_ty e = asdl_seq_GET(seq, i);
257
6.49k
        asdl_seq_SET(new_seq, i, _PyPegen_set_expr_context(p, e, ctx));
258
6.49k
    }
259
3.65k
    return new_seq;
260
3.65k
}
261
262
static expr_ty
263
_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
264
227k
{
265
227k
    return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
266
227k
}
267
268
static expr_ty
269
_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
270
4.83k
{
271
4.83k
    return _PyAST_Tuple(
272
4.83k
            _set_seq_context(p, e->v.Tuple.elts, ctx),
273
4.83k
            ctx,
274
4.83k
            EXTRA_EXPR(e, e));
275
4.83k
}
276
277
static expr_ty
278
_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
279
1.71k
{
280
1.71k
    return _PyAST_List(
281
1.71k
            _set_seq_context(p, e->v.List.elts, ctx),
282
1.71k
            ctx,
283
1.71k
            EXTRA_EXPR(e, e));
284
1.71k
}
285
286
static expr_ty
287
_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
288
304
{
289
304
    return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
290
304
                            ctx, EXTRA_EXPR(e, e));
291
304
}
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
784
{
303
784
    return _PyAST_Starred(_PyPegen_set_expr_context(p, e->v.Starred.value, ctx),
304
784
                          ctx, EXTRA_EXPR(e, e));
305
784
}
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
235k
{
311
235k
    assert(expr != NULL);
312
313
235k
    expr_ty new = NULL;
314
235k
    switch (expr->kind) {
315
227k
        case Name_kind:
316
227k
            new = _set_name_context(p, expr, ctx);
317
227k
            break;
318
4.83k
        case Tuple_kind:
319
4.83k
            new = _set_tuple_context(p, expr, ctx);
320
4.83k
            break;
321
1.71k
        case List_kind:
322
1.71k
            new = _set_list_context(p, expr, ctx);
323
1.71k
            break;
324
304
        case Subscript_kind:
325
304
            new = _set_subscript_context(p, expr, ctx);
326
304
            break;
327
76
        case Attribute_kind:
328
76
            new = _set_attribute_context(p, expr, ctx);
329
76
            break;
330
784
        case Starred_kind:
331
784
            new = _set_starred_context(p, expr, ctx);
332
784
            break;
333
0
        default:
334
0
            new = expr;
335
235k
    }
336
235k
    return new;
337
235k
}
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
44.3k
{
343
44.3k
    KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
344
44.3k
    if (!a) {
345
0
        return NULL;
346
0
    }
347
44.3k
    a->key = key;
348
44.3k
    a->value = value;
349
44.3k
    return a;
350
44.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
4.97k
{
356
4.97k
    Py_ssize_t len = asdl_seq_LEN(seq);
357
4.97k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
358
4.97k
    if (!new_seq) {
359
0
        return NULL;
360
0
    }
361
39.1k
    for (Py_ssize_t i = 0; i < len; i++) {
362
34.2k
        KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
363
34.2k
        asdl_seq_SET(new_seq, i, pair->key);
364
34.2k
    }
365
4.97k
    return new_seq;
366
4.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
4.97k
{
372
4.97k
    Py_ssize_t len = asdl_seq_LEN(seq);
373
4.97k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
374
4.97k
    if (!new_seq) {
375
0
        return NULL;
376
0
    }
377
39.1k
    for (Py_ssize_t i = 0; i < len; i++) {
378
34.2k
        KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
379
34.2k
        asdl_seq_SET(new_seq, i, pair->value);
380
34.2k
    }
381
4.97k
    return new_seq;
382
4.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.90k
{
401
1.90k
    Py_ssize_t len = asdl_seq_LEN(seq);
402
1.90k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
403
1.90k
    if (!new_seq) {
404
0
        return NULL;
405
0
    }
406
4.82k
    for (Py_ssize_t i = 0; i < len; i++) {
407
2.92k
        KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
408
2.92k
        asdl_seq_SET(new_seq, i, pair->key);
409
2.92k
    }
410
1.90k
    return new_seq;
411
1.90k
}
412
413
/* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
414
asdl_pattern_seq *
415
_PyPegen_get_patterns(Parser *p, asdl_seq *seq)
416
1.90k
{
417
1.90k
    Py_ssize_t len = asdl_seq_LEN(seq);
418
1.90k
    asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
419
1.90k
    if (!new_seq) {
420
0
        return NULL;
421
0
    }
422
4.82k
    for (Py_ssize_t i = 0; i < len; i++) {
423
2.92k
        KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
424
2.92k
        asdl_seq_SET(new_seq, i, pair->pattern);
425
2.92k
    }
426
1.90k
    return new_seq;
427
1.90k
}
428
429
/* Constructs a NameDefaultPair */
430
NameDefaultPair *
431
_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
432
91.9k
{
433
91.9k
    NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
434
91.9k
    if (!a) {
435
0
        return NULL;
436
0
    }
437
91.9k
    a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
438
91.9k
    a->value = value;
439
91.9k
    return a;
440
91.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
7.27k
{
446
7.27k
    SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
447
7.27k
    if (!a) {
448
0
        return NULL;
449
0
    }
450
7.27k
    a->plain_names = plain_names;
451
7.27k
    a->names_with_defaults = names_with_defaults;
452
7.27k
    return a;
453
7.27k
}
454
455
/* Constructs a StarEtc */
456
StarEtc *
457
_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
458
5.83k
{
459
5.83k
    StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
460
5.83k
    if (!a) {
461
0
        return NULL;
462
0
    }
463
5.83k
    a->vararg = vararg;
464
5.83k
    a->kwonlyargs = kwonlyargs;
465
5.83k
    a->kwarg = kwarg;
466
5.83k
    return a;
467
5.83k
}
468
469
asdl_seq *
470
_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
471
14.0k
{
472
14.0k
    Py_ssize_t first_len = asdl_seq_LEN(a);
473
14.0k
    Py_ssize_t second_len = asdl_seq_LEN(b);
474
14.0k
    asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
475
14.0k
    if (!new_seq) {
476
0
        return NULL;
477
0
    }
478
479
14.0k
    int k = 0;
480
38.8k
    for (Py_ssize_t i = 0; i < first_len; i++) {
481
24.7k
        asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
482
24.7k
    }
483
23.6k
    for (Py_ssize_t i = 0; i < second_len; i++) {
484
9.56k
        asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
485
9.56k
    }
486
487
14.0k
    return new_seq;
488
14.0k
}
489
490
static asdl_arg_seq*
491
_get_names(Parser *p, asdl_seq *names_with_defaults)
492
21.6k
{
493
21.6k
    Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
494
21.6k
    asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
495
21.6k
    if (!seq) {
496
0
        return NULL;
497
0
    }
498
37.4k
    for (Py_ssize_t i = 0; i < len; i++) {
499
15.8k
        NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
500
15.8k
        asdl_seq_SET(seq, i, pair->arg);
501
15.8k
    }
502
21.6k
    return seq;
503
21.6k
}
504
505
static asdl_expr_seq *
506
_get_defaults(Parser *p, asdl_seq *names_with_defaults)
507
21.6k
{
508
21.6k
    Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
509
21.6k
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
510
21.6k
    if (!seq) {
511
0
        return NULL;
512
0
    }
513
37.4k
    for (Py_ssize_t i = 0; i < len; i++) {
514
15.8k
        NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
515
15.8k
        asdl_seq_SET(seq, i, pair->value);
516
15.8k
    }
517
21.6k
    return seq;
518
21.6k
}
519
520
static int
521
_make_posonlyargs(Parser *p,
522
                  asdl_arg_seq *slash_without_default,
523
                  SlashWithDefault *slash_with_default,
524
19.4k
                  asdl_arg_seq **posonlyargs) {
525
19.4k
    if (slash_without_default != NULL) {
526
1.49k
        *posonlyargs = slash_without_default;
527
1.49k
    }
528
17.9k
    else if (slash_with_default != NULL) {
529
2.49k
        asdl_arg_seq *slash_with_default_names =
530
2.49k
                _get_names(p, slash_with_default->names_with_defaults);
531
2.49k
        if (!slash_with_default_names) {
532
0
            return -1;
533
0
        }
534
2.49k
        *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
535
2.49k
                p,
536
2.49k
                (asdl_seq*)slash_with_default->plain_names,
537
2.49k
                (asdl_seq*)slash_with_default_names);
538
2.49k
    }
539
15.4k
    else {
540
15.4k
        *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
541
15.4k
    }
542
19.4k
    return *posonlyargs == NULL ? -1 : 0;
543
19.4k
}
544
545
static int
546
_make_posargs(Parser *p,
547
              asdl_arg_seq *plain_names,
548
              asdl_seq *names_with_default,
549
19.4k
              asdl_arg_seq **posargs) {
550
551
19.4k
    if (names_with_default != NULL) {
552
14.3k
        if (plain_names != NULL) {
553
8.76k
            asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
554
8.76k
            if (!names_with_default_names) {
555
0
                return -1;
556
0
            }
557
8.76k
            *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
558
8.76k
                    p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
559
8.76k
        }
560
5.61k
        else {
561
5.61k
            *posargs = _get_names(p, names_with_default);
562
5.61k
        }
563
14.3k
    }
564
5.08k
    else {
565
5.08k
        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.08k
        else {
572
5.08k
            *posargs = _Py_asdl_arg_seq_new(0, p->arena);
573
5.08k
        }
574
5.08k
    }
575
19.4k
    return *posargs == NULL ? -1 : 0;
576
19.4k
}
577
578
static int
579
_make_posdefaults(Parser *p,
580
                  SlashWithDefault *slash_with_default,
581
                  asdl_seq *names_with_default,
582
19.4k
                  asdl_expr_seq **posdefaults) {
583
19.4k
    if (slash_with_default != NULL && names_with_default != NULL) {
584
2.49k
        asdl_expr_seq *slash_with_default_values =
585
2.49k
                _get_defaults(p, slash_with_default->names_with_defaults);
586
2.49k
        if (!slash_with_default_values) {
587
0
            return -1;
588
0
        }
589
2.49k
        asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
590
2.49k
        if (!names_with_default_values) {
591
0
            return -1;
592
0
        }
593
2.49k
        *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
594
2.49k
                p,
595
2.49k
                (asdl_seq*)slash_with_default_values,
596
2.49k
                (asdl_seq*)names_with_default_values);
597
2.49k
    }
598
16.9k
    else if (slash_with_default == NULL && names_with_default != NULL) {
599
11.8k
        *posdefaults = _get_defaults(p, names_with_default);
600
11.8k
    }
601
5.08k
    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.08k
    else {
605
5.08k
        *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
606
5.08k
    }
607
19.4k
    return *posdefaults == NULL ? -1 : 0;
608
19.4k
}
609
610
static int
611
_make_kwargs(Parser *p, StarEtc *star_etc,
612
             asdl_arg_seq **kwonlyargs,
613
19.4k
             asdl_expr_seq **kwdefaults) {
614
19.4k
    if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
615
4.74k
        *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
616
4.74k
    }
617
14.7k
    else {
618
14.7k
        *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
619
14.7k
    }
620
621
19.4k
    if (*kwonlyargs == NULL) {
622
0
        return -1;
623
0
    }
624
625
19.4k
    if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
626
4.74k
        *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
627
4.74k
    }
628
14.7k
    else {
629
14.7k
        *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
630
14.7k
    }
631
632
19.4k
    if (*kwdefaults == NULL) {
633
0
        return -1;
634
0
    }
635
636
19.4k
    return 0;
637
19.4k
}
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.4k
{
645
19.4k
    asdl_arg_seq *posonlyargs;
646
19.4k
    if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
647
0
        return NULL;
648
0
    }
649
650
19.4k
    asdl_arg_seq *posargs;
651
19.4k
    if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
652
0
        return NULL;
653
0
    }
654
655
19.4k
    asdl_expr_seq *posdefaults;
656
19.4k
    if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
657
0
        return NULL;
658
0
    }
659
660
19.4k
    arg_ty vararg = NULL;
661
19.4k
    if (star_etc != NULL && star_etc->vararg != NULL) {
662
3.37k
        vararg = star_etc->vararg;
663
3.37k
    }
664
665
19.4k
    asdl_arg_seq *kwonlyargs;
666
19.4k
    asdl_expr_seq *kwdefaults;
667
19.4k
    if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
668
0
        return NULL;
669
0
    }
670
671
19.4k
    arg_ty kwarg = NULL;
672
19.4k
    if (star_etc != NULL && star_etc->kwarg != NULL) {
673
1.19k
        kwarg = star_etc->kwarg;
674
1.19k
    }
675
676
19.4k
    return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
677
19.4k
                            kwdefaults, kwarg, posdefaults, p->arena);
678
19.4k
}
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.90k
{
686
1.90k
    asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
687
1.90k
    if (!posonlyargs) {
688
0
        return NULL;
689
0
    }
690
1.90k
    asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
691
1.90k
    if (!posargs) {
692
0
        return NULL;
693
0
    }
694
1.90k
    asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
695
1.90k
    if (!posdefaults) {
696
0
        return NULL;
697
0
    }
698
1.90k
    asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
699
1.90k
    if (!kwonlyargs) {
700
0
        return NULL;
701
0
    }
702
1.90k
    asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
703
1.90k
    if (!kwdefaults) {
704
0
        return NULL;
705
0
    }
706
707
1.90k
    return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
708
1.90k
                            kwdefaults, NULL, posdefaults, p->arena);
709
1.90k
}
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
980
{
727
980
    assert(function_def != NULL);
728
980
    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
707
    return _PyAST_FunctionDef(
741
707
        function_def->v.FunctionDef.name,
742
707
        function_def->v.FunctionDef.args,
743
707
        function_def->v.FunctionDef.body, decorators,
744
707
        function_def->v.FunctionDef.returns,
745
707
        function_def->v.FunctionDef.type_comment,
746
707
        function_def->v.FunctionDef.type_params,
747
707
        function_def->lineno, function_def->col_offset,
748
707
        function_def->end_lineno, function_def->end_col_offset, p->arena);
749
980
}
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
517
{
755
517
    assert(class_def != NULL);
756
517
    return _PyAST_ClassDef(
757
517
        class_def->v.ClassDef.name,
758
517
        class_def->v.ClassDef.bases, class_def->v.ClassDef.keywords,
759
517
        class_def->v.ClassDef.body, decorators,
760
517
        class_def->v.ClassDef.type_params,
761
517
        class_def->lineno, class_def->col_offset, class_def->end_lineno,
762
517
        class_def->end_col_offset, p->arena);
763
517
}
764
765
/* Construct a KeywordOrStarred */
766
KeywordOrStarred *
767
_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
768
37.2k
{
769
37.2k
    KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
770
37.2k
    if (!a) {
771
0
        return NULL;
772
0
    }
773
37.2k
    a->element = element;
774
37.2k
    a->is_keyword = is_keyword;
775
37.2k
    return a;
776
37.2k
}
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.9k
{
782
18.9k
    int n = 0;
783
58.3k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
784
39.4k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
785
39.4k
        if (!k->is_keyword) {
786
2.91k
            n++;
787
2.91k
        }
788
39.4k
    }
789
18.9k
    return n;
790
18.9k
}
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.46k
{
796
9.46k
    int new_len = _seq_number_of_starred_exprs(kwargs);
797
9.46k
    if (new_len == 0) {
798
8.80k
        return NULL;
799
8.80k
    }
800
654
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
801
654
    if (!new_seq) {
802
0
        return NULL;
803
0
    }
804
805
654
    int idx = 0;
806
3.33k
    for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
807
2.68k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
808
2.68k
        if (!k->is_keyword) {
809
1.45k
            asdl_seq_SET(new_seq, idx++, k->element);
810
1.45k
        }
811
2.68k
    }
812
654
    return new_seq;
813
654
}
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.46k
{
819
9.46k
    Py_ssize_t len = asdl_seq_LEN(kwargs);
820
9.46k
    Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
821
9.46k
    if (new_len == 0) {
822
0
        return NULL;
823
0
    }
824
9.46k
    asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
825
9.46k
    if (!new_seq) {
826
0
        return NULL;
827
0
    }
828
829
9.46k
    int idx = 0;
830
29.1k
    for (Py_ssize_t i = 0; i < len; i++) {
831
19.7k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
832
19.7k
        if (k->is_keyword) {
833
18.2k
            asdl_seq_SET(new_seq, idx++, k->element);
834
18.2k
        }
835
19.7k
    }
836
9.46k
    return new_seq;
837
9.46k
}
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
6
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
844
6
        return NULL;
845
6
    }
846
1.15k
    return exp;
847
1.15k
}
848
849
expr_ty
850
_PyPegen_ensure_real(Parser *p, expr_ty exp)
851
1.95k
{
852
1.95k
    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.95k
}
858
859
mod_ty
860
7.86k
_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
861
7.86k
    asdl_type_ignore_seq *type_ignores = NULL;
862
7.86k
    Py_ssize_t num = p->type_ignore_comments.num_items;
863
7.86k
    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.86k
    return _PyAST_Module(a, type_ignores, p->arena);
883
7.86k
}
884
885
PyObject *
886
_PyPegen_new_type_comment(Parser *p, const char *s)
887
0
{
888
0
    PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
889
0
    if (res == NULL) {
890
0
        return NULL;
891
0
    }
892
0
    if (_PyArena_AddPyObject(p->arena, res) < 0) {
893
0
        Py_DECREF(res);
894
0
        return NULL;
895
0
    }
896
0
    return res;
897
0
}
898
899
arg_ty
900
_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
901
161k
{
902
161k
    if (tc == NULL) {
903
161k
        return a;
904
161k
    }
905
0
    const char *bytes = PyBytes_AsString(tc->bytes);
906
0
    if (bytes == NULL) {
907
0
        return NULL;
908
0
    }
909
0
    PyObject *tco = _PyPegen_new_type_comment(p, bytes);
910
0
    if (tco == NULL) {
911
0
        return NULL;
912
0
    }
913
0
    return _PyAST_arg(a->arg, a->annotation, tco,
914
0
                      a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
915
0
                      p->arena);
916
0
}
917
918
/* Checks if the NOTEQUAL token is valid given the current parser flags
919
0 indicates success and nonzero indicates failure (an exception may be set) */
920
int
921
1.39k
_PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
922
1.39k
    assert(t->bytes != NULL);
923
1.39k
    assert(t->type == NOTEQUAL);
924
925
1.39k
    const char* tok_str = PyBytes_AS_STRING(t->bytes);
926
1.39k
    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.39k
    if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
931
1.39k
        return strcmp(tok_str, "!=");
932
1.39k
    }
933
0
    return 0;
934
1.39k
}
935
936
int
937
9.16k
_PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
938
9.16k
    if (name->kind != Name_kind) {
939
2.48k
        return 0;
940
2.48k
    }
941
6.68k
    const char* candidates[2] = {"print", "exec"};
942
19.4k
    for (int i=0; i<2; i++) {
943
13.1k
        if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
944
407
            return 1;
945
407
        }
946
13.1k
    }
947
6.27k
    return 0;
948
6.68k
}
949
950
static ResultTokenWithMetadata *
951
result_token_with_metadata(Parser *p, void *result, PyObject *metadata)
952
7.54k
{
953
7.54k
    ResultTokenWithMetadata *res = _PyArena_Malloc(p->arena, sizeof(ResultTokenWithMetadata));
954
7.54k
    if (res == NULL) {
955
0
        return NULL;
956
0
    }
957
7.54k
    res->metadata = metadata;
958
7.54k
    res->result = result;
959
7.54k
    return res;
960
7.54k
}
961
962
ResultTokenWithMetadata *
963
_PyPegen_check_fstring_conversion(Parser *p, Token* conv_token, expr_ty conv)
964
1.51k
{
965
1.51k
    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.50k
    Py_UCS4 first = PyUnicode_READ_CHAR(conv->v.Name.id, 0);
974
1.50k
    if (PyUnicode_GET_LENGTH(conv->v.Name.id) > 1 ||
975
1.50k
            !(first == 's' || first == 'r' || first == 'a')) {
976
10
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conv,
977
10
                                            "%c-string: invalid conversion character %R: expected 's', 'r', or 'a'",
978
10
                                            TOK_GET_STRING_PREFIX(p->tok),
979
10
                                            conv->v.Name.id);
980
10
        return NULL;
981
10
    }
982
983
1.49k
    return result_token_with_metadata(p, conv, conv_token->metadata);
984
1.50k
}
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.04k
{
990
6.04k
    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.04k
    Py_ssize_t n_items = asdl_seq_LEN(spec);
998
6.04k
    Py_ssize_t non_empty_count = 0;
999
19.5k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1000
13.4k
        expr_ty item = asdl_seq_GET(spec, i);
1001
13.4k
        non_empty_count += !(item->kind == Constant_kind &&
1002
13.4k
                             PyUnicode_CheckExact(item->v.Constant.value) &&
1003
13.4k
                             PyUnicode_GET_LENGTH(item->v.Constant.value) == 0);
1004
13.4k
    }
1005
6.04k
    if (non_empty_count != n_items) {
1006
2.37k
        asdl_expr_seq *resized_spec =
1007
2.37k
            _Py_asdl_expr_seq_new(non_empty_count, p->arena);
1008
2.37k
        if (resized_spec == NULL) {
1009
0
            return NULL;
1010
0
        }
1011
2.37k
        Py_ssize_t j = 0;
1012
6.63k
        for (Py_ssize_t i = 0; i < n_items; i++) {
1013
4.26k
            expr_ty item = asdl_seq_GET(spec, i);
1014
4.26k
            if (item->kind == Constant_kind &&
1015
4.26k
                PyUnicode_CheckExact(item->v.Constant.value) &&
1016
4.26k
                PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1017
2.37k
                continue;
1018
2.37k
            }
1019
1.89k
            asdl_seq_SET(resized_spec, j++, item);
1020
1.89k
        }
1021
2.37k
        assert(j == non_empty_count);
1022
2.37k
        spec = resized_spec;
1023
2.37k
    }
1024
6.04k
    expr_ty res;
1025
6.04k
    Py_ssize_t n = asdl_seq_LEN(spec);
1026
6.04k
    if (n == 0 || (n == 1 && asdl_seq_GET(spec, 0)->kind == Constant_kind)) {
1027
4.92k
        res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno,
1028
4.92k
                                    end_col_offset, p->arena);
1029
4.92k
    } else {
1030
1.12k
        res = _PyPegen_concatenate_strings(p, spec,
1031
1.12k
                             lineno, col_offset, end_lineno,
1032
1.12k
                             end_col_offset, arena);
1033
1.12k
    }
1034
6.04k
    if (!res) {
1035
0
        return NULL;
1036
0
    }
1037
6.04k
    return result_token_with_metadata(p, res, colon->metadata);
1038
6.04k
}
1039
1040
const char *
1041
_PyPegen_get_expr_name(expr_ty e)
1042
193
{
1043
193
    assert(e != NULL);
1044
193
    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
8
        case Name_kind:
1052
8
            return "name";
1053
1
        case List_kind:
1054
1
            return "list";
1055
6
        case Tuple_kind:
1056
6
            return "tuple";
1057
2
        case Lambda_kind:
1058
2
            return "lambda";
1059
15
        case Call_kind:
1060
15
            return "function call";
1061
5
        case BoolOp_kind:
1062
22
        case BinOp_kind:
1063
33
        case UnaryOp_kind:
1064
33
            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
9
        case TemplateStr_kind:
1086
9
        case Interpolation_kind:
1087
9
            return "t-string expression";
1088
86
        case Constant_kind: {
1089
86
            PyObject *value = e->v.Constant.value;
1090
86
            if (value == Py_None) {
1091
1
                return "None";
1092
1
            }
1093
85
            if (value == Py_False) {
1094
1
                return "False";
1095
1
            }
1096
84
            if (value == Py_True) {
1097
1
                return "True";
1098
1
            }
1099
83
            if (value == Py_Ellipsis) {
1100
1
                return "ellipsis";
1101
1
            }
1102
82
            return "literal";
1103
83
        }
1104
11
        case Compare_kind:
1105
11
            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
193
    }
1116
193
}
1117
1118
expr_ty
1119
14
_PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
1120
14
    if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
1121
10
        return comprehension->iter;
1122
10
    }
1123
4
    return PyPegen_last_item(comprehension->ifs, expr_ty);
1124
14
}
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.1k
        return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
1134
32.1k
                        end_lineno, end_col_offset, arena);
1135
1136
32.1k
    }
1137
1138
2.43k
    asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
1139
2.43k
    asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
1140
1141
2.43k
    if (starreds) {
1142
296
        total_len += asdl_seq_LEN(starreds);
1143
296
    }
1144
1145
2.43k
    asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
1146
2.43k
    if (args == NULL) {
1147
0
        return NULL;
1148
0
    }
1149
1150
2.43k
    Py_ssize_t i = 0;
1151
5.82k
    for (i = 0; i < args_len; i++) {
1152
3.38k
        asdl_seq_SET(args, i, asdl_seq_GET(a, i));
1153
3.38k
    }
1154
3.24k
    for (; i < total_len; i++) {
1155
806
        asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
1156
806
    }
1157
1158
2.43k
    return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
1159
2.43k
                       col_offset, end_lineno, end_col_offset, arena);
1160
2.43k
}
1161
1162
// AST Error reporting helpers
1163
1164
expr_ty
1165
_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
1166
8.50k
{
1167
8.50k
    if (e == NULL) {
1168
0
        return NULL;
1169
0
    }
1170
1171
8.50k
#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
1172
2.29k
        Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
1173
7.45k
        for (Py_ssize_t i = 0; i < len; i++) {\
1174
5.28k
            expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
1175
5.28k
            expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
1176
5.28k
            if (child != NULL) {\
1177
124
                return child;\
1178
124
            }\
1179
5.28k
        }\
1180
2.29k
    } 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.50k
    switch (e->kind) {
1189
715
        case List_kind:
1190
715
            VISIT_CONTAINER(e, List);
1191
680
            return NULL;
1192
1.57k
        case Tuple_kind:
1193
1.57k
            VISIT_CONTAINER(e, Tuple);
1194
1.49k
            return NULL;
1195
1.39k
        case Starred_kind:
1196
1.39k
            if (targets_type == DEL_TARGETS) {
1197
1
                return e;
1198
1
            }
1199
1.39k
            return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
1200
362
        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
362
            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
11
            return e;
1212
3.32k
        case Name_kind:
1213
3.98k
        case Subscript_kind:
1214
4.32k
        case Attribute_kind:
1215
4.32k
            return NULL;
1216
133
        default:
1217
133
            return e;
1218
8.50k
    }
1219
8.50k
}
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
307
{
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
307
    Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
1251
307
    if (len <= 1) {
1252
305
        return NULL;
1253
305
    }
1254
1255
2
    comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
1256
1257
2
    return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1258
307
        (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
1259
307
        _PyPegen_get_last_comprehension_item(last_comprehension),
1260
307
        "Generator expression must be parenthesized"
1261
307
    );
1262
307
}
1263
1264
// Fstring stuff
1265
1266
static expr_ty
1267
26.3k
_PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant, Token* token) {
1268
26.3k
    assert(PyUnicode_CheckExact(constant->v.Constant.value));
1269
1270
26.3k
    const char* bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
1271
26.3k
    if (bstr == NULL) {
1272
0
        return NULL;
1273
0
    }
1274
1275
26.3k
    size_t len;
1276
26.3k
    if (strcmp(bstr, "{{") == 0 || strcmp(bstr, "}}") == 0) {
1277
0
        len = 1;
1278
26.3k
    } else {
1279
26.3k
        len = strlen(bstr);
1280
26.3k
    }
1281
1282
26.3k
    is_raw = is_raw || strchr(bstr, '\\') == NULL;
1283
26.3k
    PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
1284
26.3k
    if (str == NULL) {
1285
6
        _Pypegen_raise_decode_error(p);
1286
6
        return NULL;
1287
6
    }
1288
26.3k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1289
0
        Py_DECREF(str);
1290
0
        return NULL;
1291
0
    }
1292
26.3k
    return _PyAST_Constant(str, NULL, constant->lineno, constant->col_offset,
1293
26.3k
                           constant->end_lineno, constant->end_col_offset,
1294
26.3k
                           p->arena);
1295
26.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
16.2k
{
1300
16.2k
    Py_ssize_t n_items = asdl_seq_LEN(raw_expressions);
1301
16.2k
    Py_ssize_t total_items = n_items;
1302
59.5k
    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.49k
            total_items += asdl_seq_LEN(item->v.JoinedStr.values) - 1;
1306
5.49k
        }
1307
43.3k
    }
1308
1309
16.2k
    const char* quote_str = PyBytes_AsString(a->bytes);
1310
16.2k
    if (quote_str == NULL) {
1311
0
        return NULL;
1312
0
    }
1313
16.2k
    int is_raw = strpbrk(quote_str, "rR") != NULL;
1314
1315
16.2k
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(total_items, p->arena);
1316
16.2k
    if (seq == NULL) {
1317
0
        return NULL;
1318
0
    }
1319
1320
16.2k
    Py_ssize_t index = 0;
1321
59.5k
    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.49k
            asdl_expr_seq *values = item->v.JoinedStr.values;
1330
5.49k
            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.49k
            expr_ty first = asdl_seq_GET(values, 0);
1340
5.49k
            assert(first->kind == Constant_kind);
1341
5.49k
            asdl_seq_SET(seq, index++, first);
1342
1343
5.49k
            expr_ty second = asdl_seq_GET(values, 1);
1344
5.49k
            assert((string_kind == TSTRING && second->kind == Interpolation_kind) || second->kind == FormattedValue_kind);
1345
5.49k
            asdl_seq_SET(seq, index++, second);
1346
1347
5.49k
            continue;
1348
5.49k
        }
1349
1350
37.8k
        if (item->kind == Constant_kind) {
1351
26.3k
            item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
1352
26.3k
            if (item == NULL) {
1353
6
                return NULL;
1354
6
            }
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
26.3k
            if (PyUnicode_CheckExact(item->v.Constant.value)
1360
26.3k
                && PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1361
435
                continue;
1362
435
            }
1363
26.3k
        }
1364
37.4k
        asdl_seq_SET(seq, index++, item);
1365
37.4k
    }
1366
1367
16.2k
    asdl_expr_seq *resized_exprs;
1368
16.2k
    if (index != total_items) {
1369
435
        resized_exprs = _Py_asdl_expr_seq_new(index, p->arena);
1370
435
        if (resized_exprs == NULL) {
1371
0
            return NULL;
1372
0
        }
1373
871
        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
435
    }
1377
15.7k
    else {
1378
15.7k
        resized_exprs = seq;
1379
15.7k
    }
1380
16.2k
    return resized_exprs;
1381
16.2k
}
1382
1383
expr_ty
1384
3.19k
_PyPegen_template_str(Parser *p, Token *a, asdl_expr_seq *raw_expressions, Token *b) {
1385
1386
3.19k
    asdl_expr_seq *resized_exprs = _get_resized_exprs(p, a, raw_expressions, b, TSTRING);
1387
3.19k
    return _PyAST_TemplateStr(resized_exprs, a->lineno, a->col_offset,
1388
3.19k
                              b->end_lineno, b->end_col_offset,
1389
3.19k
                              p->arena);
1390
3.19k
}
1391
1392
expr_ty
1393
13.0k
_PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* raw_expressions, Token*b) {
1394
1395
13.0k
    asdl_expr_seq *resized_exprs = _get_resized_exprs(p, a, raw_expressions, b, FSTRING);
1396
13.0k
    return _PyAST_JoinedStr(resized_exprs, a->lineno, a->col_offset,
1397
13.0k
                            b->end_lineno, b->end_col_offset,
1398
13.0k
                            p->arena);
1399
13.0k
}
1400
1401
9.79k
expr_ty _PyPegen_decoded_constant_from_token(Parser* p, Token* tok) {
1402
9.79k
    Py_ssize_t bsize;
1403
9.79k
    char* bstr;
1404
9.79k
    if (PyBytes_AsStringAndSize(tok->bytes, &bstr, &bsize) == -1) {
1405
0
        return NULL;
1406
0
    }
1407
9.79k
    PyObject* str = _PyPegen_decode_string(p, 0, bstr, bsize, tok);
1408
9.79k
    if (str == NULL) {
1409
2
        return NULL;
1410
2
    }
1411
9.79k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1412
0
        Py_DECREF(str);
1413
0
        return NULL;
1414
0
    }
1415
9.79k
    return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1416
9.79k
                           tok->end_lineno, tok->end_col_offset,
1417
9.79k
                           p->arena);
1418
9.79k
}
1419
1420
33.5k
expr_ty _PyPegen_constant_from_token(Parser* p, Token* tok) {
1421
33.5k
    char* bstr = PyBytes_AsString(tok->bytes);
1422
33.5k
    if (bstr == NULL) {
1423
0
        return NULL;
1424
0
    }
1425
33.5k
    PyObject* str = PyUnicode_FromString(bstr);
1426
33.5k
    if (str == NULL) {
1427
7
        return NULL;
1428
7
    }
1429
33.5k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1430
0
        Py_DECREF(str);
1431
0
        return NULL;
1432
0
    }
1433
33.5k
    return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1434
33.5k
                           tok->end_lineno, tok->end_col_offset,
1435
33.5k
                           p->arena);
1436
33.5k
}
1437
1438
63.3k
expr_ty _PyPegen_constant_from_string(Parser* p, Token* tok) {
1439
63.3k
    char* the_str = PyBytes_AsString(tok->bytes);
1440
63.3k
    if (the_str == NULL) {
1441
0
        return NULL;
1442
0
    }
1443
63.3k
    PyObject *s = _PyPegen_parse_string(p, tok);
1444
63.3k
    if (s == NULL) {
1445
383
        _Pypegen_raise_decode_error(p);
1446
383
        return NULL;
1447
383
    }
1448
62.9k
    if (_PyArena_AddPyObject(p->arena, s) < 0) {
1449
0
        Py_DECREF(s);
1450
0
        return NULL;
1451
0
    }
1452
62.9k
    PyObject *kind = NULL;
1453
62.9k
    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
62.9k
    return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno, tok->end_col_offset, p->arena);
1460
62.9k
}
1461
1462
static int
1463
_get_interpolation_conversion(Parser *p, Token *debug, ResultTokenWithMetadata *conversion,
1464
                              ResultTokenWithMetadata *format)
1465
25.1k
{
1466
25.1k
    if (conversion != NULL) {
1467
1.47k
        expr_ty conversion_expr = (expr_ty) conversion->result;
1468
1.47k
        assert(conversion_expr->kind == Name_kind);
1469
1.47k
        Py_UCS4 first = PyUnicode_READ_CHAR(conversion_expr->v.Name.id, 0);
1470
1.47k
        return Py_SAFE_DOWNCAST(first, Py_UCS4, int);
1471
1.47k
    }
1472
23.6k
    else if (debug && !format) {
1473
        /* If no conversion is specified, use !r for debug expressions */
1474
5.65k
        return (int)'r';
1475
5.65k
    }
1476
18.0k
    return -1;
1477
25.1k
}
1478
1479
static PyObject *
1480
_strip_interpolation_expr(PyObject *exprstr)
1481
4.35k
{
1482
4.35k
    Py_ssize_t len = PyUnicode_GET_LENGTH(exprstr);
1483
1484
12.7k
    for (Py_ssize_t i = len - 1; i >= 0; i--) {
1485
12.7k
        Py_UCS4 c = PyUnicode_READ_CHAR(exprstr, i);
1486
12.7k
        if (_PyUnicode_IsWhitespace(c) || c == '=') {
1487
8.37k
            len--;
1488
8.37k
        }
1489
4.35k
        else {
1490
4.35k
            break;
1491
4.35k
        }
1492
12.7k
    }
1493
1494
4.35k
    return PyUnicode_Substring(exprstr, 0, len);
1495
4.35k
}
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.35k
                                 int end_lineno, int end_col_offset, PyArena *arena) {
1500
1501
4.35k
    int conversion_val = _get_interpolation_conversion(p, debug, conversion, format);
1502
1503
    /* Find the non whitespace token after the "=" */
1504
4.35k
    int debug_end_line, debug_end_offset;
1505
4.35k
    PyObject *debug_metadata;
1506
4.35k
    constant exprstr;
1507
1508
4.35k
    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.64k
    else if (format) {
1514
726
        debug_end_line = ((expr_ty) format->result)->lineno;
1515
726
        debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1516
726
        debug_metadata = exprstr = format->metadata;
1517
726
    }
1518
2.91k
    else {
1519
2.91k
        debug_end_line = end_lineno;
1520
2.91k
        debug_end_offset = end_col_offset;
1521
2.91k
        debug_metadata = exprstr = closing_brace->metadata;
1522
2.91k
    }
1523
1524
4.35k
    assert(exprstr != NULL);
1525
4.35k
    PyObject *final_exprstr = _strip_interpolation_expr(exprstr);
1526
4.35k
    if (!final_exprstr || _PyArena_AddPyObject(arena, final_exprstr) < 0) {
1527
0
        Py_XDECREF(final_exprstr);
1528
0
        return NULL;
1529
0
    }
1530
1531
4.35k
    expr_ty interpolation = _PyAST_Interpolation(
1532
4.35k
        expression, final_exprstr, conversion_val, format ? (expr_ty) format->result : NULL,
1533
4.35k
        lineno, col_offset, end_lineno,
1534
4.35k
        end_col_offset, arena
1535
4.35k
    );
1536
1537
4.35k
    if (!debug) {
1538
2.94k
        return interpolation;
1539
2.94k
    }
1540
1541
1.41k
    expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1542
1.41k
                                            debug_end_offset - 1, p->arena);
1543
1.41k
    if (!debug_text) {
1544
0
        return NULL;
1545
0
    }
1546
1547
1.41k
    asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1548
1.41k
    asdl_seq_SET(values, 0, debug_text);
1549
1.41k
    asdl_seq_SET(values, 1, interpolation);
1550
1.41k
    return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1551
1.41k
}
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
20.7k
                                 int end_lineno, int end_col_offset, PyArena *arena) {
1556
20.7k
    int conversion_val = _get_interpolation_conversion(p, debug, conversion, format);
1557
1558
20.7k
    expr_ty formatted_value = _PyAST_FormattedValue(
1559
20.7k
        expression, conversion_val, format ? (expr_ty) format->result : NULL,
1560
20.7k
        lineno, col_offset, end_lineno,
1561
20.7k
        end_col_offset, arena
1562
20.7k
    );
1563
1564
20.7k
    if (!debug) {
1565
15.9k
        return formatted_value;
1566
15.9k
    }
1567
1568
    /* Find the non whitespace token after the "=" */
1569
4.79k
    int debug_end_line, debug_end_offset;
1570
4.79k
    PyObject *debug_metadata;
1571
1572
4.79k
    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.60k
    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.52k
    else {
1583
4.52k
        debug_end_line = end_lineno;
1584
4.52k
        debug_end_offset = end_col_offset;
1585
4.52k
        debug_metadata = closing_brace->metadata;
1586
4.52k
    }
1587
4.79k
    expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1588
4.79k
                                            debug_end_offset - 1, p->arena);
1589
4.79k
    if (!debug_text) {
1590
3
        return NULL;
1591
3
    }
1592
1593
4.79k
    asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1594
4.79k
    asdl_seq_SET(values, 0, debug_text);
1595
4.79k
    asdl_seq_SET(values, 1, formatted_value);
1596
4.79k
    return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1597
4.79k
}
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
586
{
1604
586
    Py_ssize_t len = asdl_seq_LEN(strings);
1605
586
    assert(len > 0);
1606
1607
586
    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
586
    PyObject* kind = asdl_seq_GET(strings, 0)->v.Constant.kind;
1614
3.55k
    for (Py_ssize_t i = 0; i < len; i++) {
1615
2.96k
        expr_ty elem = asdl_seq_GET(strings, i);
1616
2.96k
        PyBytes_Concat(&res, elem->v.Constant.value);
1617
2.96k
    }
1618
586
    if (!res || _PyArena_AddPyObject(arena, res) < 0) {
1619
0
        Py_XDECREF(res);
1620
0
        return NULL;
1621
0
    }
1622
586
    return _PyAST_Constant(res, kind, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1623
586
}
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.35k
{
1630
1.35k
    Py_ssize_t len = asdl_seq_LEN(strings);
1631
1.35k
    assert(len > 1);
1632
1633
1.35k
    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.35k
    PyObject *kind = first->v.Constant.kind;
1642
1643
1.35k
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1644
1.35k
    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.35k
    PyObject *final = PyUnicodeWriter_Finish(writer);
1660
1.35k
    if (final == NULL) {
1661
0
        return NULL;
1662
0
    }
1663
1.35k
    if (_PyArena_AddPyObject(p->arena, final) < 0) {
1664
0
        Py_DECREF(final);
1665
0
        return NULL;
1666
0
    }
1667
1.35k
    return _PyAST_Constant(final, kind, lineno, col_offset,
1668
1.35k
                           end_lineno, end_col_offset, arena);
1669
1.35k
}
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.7k
{
1676
11.7k
    Py_ssize_t len = asdl_seq_LEN(strings);
1677
11.7k
    assert(len > 0);
1678
1679
11.7k
    Py_ssize_t n_flattened_elements = 0;
1680
41.7k
    for (Py_ssize_t i = 0; i < len; i++) {
1681
29.9k
        expr_ty elem = asdl_seq_GET(strings, i);
1682
29.9k
        switch(elem->kind) {
1683
12.7k
            case JoinedStr_kind:
1684
12.7k
                n_flattened_elements += asdl_seq_LEN(elem->v.JoinedStr.values);
1685
12.7k
                break;
1686
3.34k
            case TemplateStr_kind:
1687
3.34k
                n_flattened_elements += asdl_seq_LEN(elem->v.TemplateStr.values);
1688
3.34k
                break;
1689
13.8k
            default:
1690
13.8k
                n_flattened_elements++;
1691
13.8k
                break;
1692
29.9k
        }
1693
29.9k
    }
1694
1695
1696
11.7k
    asdl_expr_seq* flattened = _Py_asdl_expr_seq_new(n_flattened_elements, p->arena);
1697
11.7k
    if (flattened == NULL) {
1698
0
        return NULL;
1699
0
    }
1700
1701
    /* build flattened list */
1702
11.7k
    Py_ssize_t current_pos = 0;
1703
41.7k
    for (Py_ssize_t i = 0; i < len; i++) {
1704
29.9k
        expr_ty elem = asdl_seq_GET(strings, i);
1705
29.9k
        switch(elem->kind) {
1706
12.7k
            case JoinedStr_kind:
1707
52.8k
                for (Py_ssize_t j = 0; j < asdl_seq_LEN(elem->v.JoinedStr.values); j++) {
1708
40.0k
                    expr_ty subvalue = asdl_seq_GET(elem->v.JoinedStr.values, j);
1709
40.0k
                    if (subvalue == NULL) {
1710
0
                        return NULL;
1711
0
                    }
1712
40.0k
                    asdl_seq_SET(flattened, current_pos++, subvalue);
1713
40.0k
                }
1714
12.7k
                break;
1715
12.7k
            case TemplateStr_kind:
1716
11.4k
                for (Py_ssize_t j = 0; j < asdl_seq_LEN(elem->v.TemplateStr.values); j++) {
1717
8.14k
                    expr_ty subvalue = asdl_seq_GET(elem->v.TemplateStr.values, j);
1718
8.14k
                    if (subvalue == NULL) {
1719
0
                        return NULL;
1720
0
                    }
1721
8.14k
                    asdl_seq_SET(flattened, current_pos++, subvalue);
1722
8.14k
                }
1723
3.34k
                break;
1724
13.8k
            default:
1725
13.8k
                asdl_seq_SET(flattened, current_pos++, elem);
1726
13.8k
                break;
1727
29.9k
        }
1728
29.9k
    }
1729
1730
    /* calculate folded element count */
1731
11.7k
    Py_ssize_t n_elements = 0;
1732
11.7k
    int prev_is_constant = 0;
1733
73.8k
    for (Py_ssize_t i = 0; i < n_flattened_elements; i++) {
1734
62.0k
        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
62.0k
        if (elem->kind == Constant_kind &&
1740
62.0k
            PyUnicode_CheckExact(elem->v.Constant.value) &&
1741
62.0k
            PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0)
1742
1.74k
            continue;
1743
1744
60.2k
        if (!prev_is_constant || elem->kind != Constant_kind) {
1745
47.1k
            n_elements++;
1746
47.1k
        }
1747
60.2k
        prev_is_constant = elem->kind == Constant_kind;
1748
60.2k
    }
1749
1750
11.7k
    asdl_expr_seq* values = _Py_asdl_expr_seq_new(n_elements, p->arena);
1751
11.7k
    if (values == NULL) {
1752
0
        return NULL;
1753
0
    }
1754
1755
    /* build folded list */
1756
11.7k
    current_pos = 0;
1757
59.2k
    for (Py_ssize_t i = 0; i < n_flattened_elements; i++) {
1758
47.4k
        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
47.4k
        if (elem->kind == Constant_kind) {
1763
26.0k
            if (i + 1 < n_flattened_elements &&
1764
26.0k
                asdl_seq_GET(flattened, i + 1)->kind == Constant_kind) {
1765
5.26k
                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.26k
                PyObject *kind = elem->v.Constant.kind;
1774
1775
5.26k
                PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1776
5.26k
                if (writer == NULL) {
1777
0
                    return NULL;
1778
0
                }
1779
5.26k
                expr_ty last_elem = elem;
1780
5.26k
                Py_ssize_t j;
1781
25.0k
                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.8k
                        if (PyUnicodeWriter_WriteStr(writer,
1785
19.8k
                                                     current_elem->v.Constant.value)) {
1786
0
                            PyUnicodeWriter_Discard(writer);
1787
0
                            return NULL;
1788
0
                        }
1789
19.8k
                        last_elem = current_elem;
1790
19.8k
                    } else {
1791
3.29k
                        break;
1792
3.29k
                    }
1793
23.1k
                }
1794
5.26k
                i = j - 1;
1795
1796
5.26k
                PyObject *concat_str = PyUnicodeWriter_Finish(writer);
1797
5.26k
                if (concat_str == NULL) {
1798
0
                    return NULL;
1799
0
                }
1800
5.26k
                if (_PyArena_AddPyObject(p->arena, concat_str) < 0) {
1801
0
                    Py_DECREF(concat_str);
1802
0
                    return NULL;
1803
0
                }
1804
5.26k
                elem = _PyAST_Constant(concat_str, kind, first_elem->lineno,
1805
5.26k
                                       first_elem->col_offset,
1806
5.26k
                                       last_elem->end_lineno,
1807
5.26k
                                       last_elem->end_col_offset, p->arena);
1808
5.26k
                if (elem == NULL) {
1809
0
                    return NULL;
1810
0
                }
1811
5.26k
            }
1812
1813
            /* Drop all empty contanst strings */
1814
26.0k
            if (PyUnicode_CheckExact(elem->v.Constant.value) &&
1815
26.0k
                PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0) {
1816
296
                continue;
1817
296
            }
1818
26.0k
        }
1819
1820
47.1k
        asdl_seq_SET(values, current_pos++, elem);
1821
47.1k
    }
1822
1823
11.7k
    assert(current_pos == n_elements);
1824
11.7k
    return values;
1825
11.7k
}
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.2k
{
1832
10.2k
    asdl_expr_seq *values = _build_concatenated_str(p, strings, lineno,
1833
10.2k
        col_offset, end_lineno, end_col_offset, arena);
1834
10.2k
    return _PyAST_JoinedStr(values, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1835
10.2k
}
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.51k
{
1842
1.51k
    asdl_expr_seq *values = _build_concatenated_str(p, strings, lineno,
1843
1.51k
        col_offset, end_lineno, end_col_offset, arena);
1844
1.51k
    return _PyAST_TemplateStr(values, lineno, col_offset, end_lineno,
1845
1.51k
        end_col_offset, arena);
1846
1.51k
}
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
47.6k
{
1853
47.6k
    Py_ssize_t len = asdl_seq_LEN(strings);
1854
47.6k
    assert(len > 0);
1855
1856
47.6k
    int t_string_found = 0;
1857
47.6k
    int f_string_found = 0;
1858
47.6k
    int unicode_string_found = 0;
1859
47.6k
    int bytes_found = 0;
1860
1861
47.6k
    Py_ssize_t i = 0;
1862
135k
    for (i = 0; i < len; i++) {
1863
87.8k
        expr_ty elem = asdl_seq_GET(strings, i);
1864
87.8k
        switch(elem->kind) {
1865
67.3k
            case Constant_kind:
1866
67.3k
                if (PyBytes_CheckExact(elem->v.Constant.value)) {
1867
5.73k
                    bytes_found = 1;
1868
61.6k
                } else {
1869
61.6k
                    unicode_string_found = 1;
1870
61.6k
                }
1871
67.3k
                break;
1872
12.7k
            case JoinedStr_kind:
1873
12.7k
                f_string_found = 1;
1874
12.7k
                break;
1875
3.34k
            case TemplateStr_kind:
1876
3.34k
                t_string_found = 1;
1877
3.34k
                break;
1878
4.36k
            default:
1879
4.36k
                f_string_found = 1;
1880
4.36k
                break;
1881
87.8k
        }
1882
87.8k
    }
1883
1884
    // Cannot mix unicode and bytes
1885
47.6k
    if ((unicode_string_found || f_string_found || t_string_found) && bytes_found) {
1886
6
        RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
1887
6
        return NULL;
1888
6
    }
1889
1890
    // If it's only bytes or only unicode string, do a simple concat
1891
47.5k
    if (!f_string_found && !t_string_found) {
1892
35.8k
        if (len == 1) {
1893
33.8k
            return asdl_seq_GET(strings, 0);
1894
33.8k
        }
1895
1.93k
        else if (bytes_found) {
1896
586
            return _build_concatenated_bytes(p, strings, lineno, col_offset,
1897
586
                end_lineno, end_col_offset, arena);
1898
586
        }
1899
1.35k
        else {
1900
1.35k
            return _build_concatenated_unicode(p, strings, lineno, col_offset,
1901
1.35k
                end_lineno, end_col_offset, arena);
1902
1.35k
        }
1903
35.8k
    }
1904
1905
11.7k
    if (t_string_found) {
1906
1.51k
        return _build_concatenated_template_str(p, strings, lineno,
1907
1.51k
            col_offset, end_lineno, end_col_offset, arena);
1908
1.51k
    }
1909
1910
10.2k
    return _build_concatenated_joined_str(p, strings, lineno,
1911
10.2k
        col_offset, end_lineno, end_col_offset, arena);
1912
11.7k
}
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.83k
                             PyArena *arena) {
1918
1.83k
    if (level == 0 && PyUnicode_CompareWithASCIIString(module, "__future__") == 0) {
1919
1.48k
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(names); i++) {
1920
894
            alias_ty alias = asdl_seq_GET(names, i);
1921
894
            if (PyUnicode_CompareWithASCIIString(alias->name, "barry_as_FLUFL") == 0) {
1922
73
                p->flags |= PyPARSE_BARRY_AS_BDFL;
1923
73
            }
1924
894
        }
1925
587
    }
1926
1.83k
    return _PyAST_ImportFrom(module, names, level, lineno, col_offset, end_lineno, end_col_offset, arena);
1927
1.83k
}
1928
1929
asdl_stmt_seq*
1930
27.3k
_PyPegen_register_stmts(Parser *p, asdl_stmt_seq* stmts) {
1931
27.3k
    if (!p->call_invalid_rules) {
1932
25.4k
        return stmts;
1933
25.4k
    }
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
}