Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Parser/action_helpers.c
Line
Count
Source
1
#include <Python.h>
2
#include "pycore_pystate.h"         // _PyInterpreterState_GET()
3
#include "pycore_runtime.h"         // _PyRuntime
4
#include "pycore_unicodeobject.h"   // _PyUnicode_InternImmortal()
5
#include "pycore_pyerrors.h"        // _PyErr_EmitSyntaxWarning()
6
7
#include "pegen.h"
8
#include "string_parser.h"          // _PyPegen_decode_string()
9
#include "lexer/state.h"            // tok_state
10
11
12
void *
13
_PyPegen_dummy_name(Parser *p, ...)
14
69.4k
{
15
69.4k
    return &_PyRuntime.parser.dummy_name;
16
69.4k
}
17
18
/* Creates a single-element asdl_seq* that contains a */
19
asdl_seq *
20
_PyPegen_singleton_seq(Parser *p, void *a)
21
141k
{
22
141k
    assert(a != NULL);
23
141k
    asdl_seq *seq = (asdl_seq*)_Py_asdl_generic_seq_new(1, p->arena);
24
141k
    if (!seq) {
25
0
        return NULL;
26
0
    }
27
141k
    asdl_seq_SET_UNTYPED(seq, 0, a);
28
141k
    return seq;
29
141k
}
30
31
/* Creates a copy of seq and prepends a to it */
32
asdl_seq *
33
_PyPegen_seq_insert_in_front(Parser *p, void *a, asdl_seq *seq)
34
331k
{
35
331k
    assert(a != NULL);
36
331k
    if (!seq) {
37
6.03k
        return _PyPegen_singleton_seq(p, a);
38
6.03k
    }
39
40
325k
    asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
41
325k
    if (!new_seq) {
42
0
        return NULL;
43
0
    }
44
45
325k
    asdl_seq_SET_UNTYPED(new_seq, 0, a);
46
555k
    for (Py_ssize_t i = 1, l = asdl_seq_LEN(new_seq); i < l; i++) {
47
230k
        asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i - 1));
48
230k
    }
49
325k
    return new_seq;
50
325k
}
51
52
/* Creates a copy of seq and appends a to it */
53
asdl_seq *
54
_PyPegen_seq_append_to_end(Parser *p, asdl_seq *seq, void *a)
55
0
{
56
0
    assert(a != NULL);
57
0
    if (!seq) {
58
0
        return _PyPegen_singleton_seq(p, a);
59
0
    }
60
61
0
    asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(asdl_seq_LEN(seq) + 1, p->arena);
62
0
    if (!new_seq) {
63
0
        return NULL;
64
0
    }
65
66
0
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(new_seq); i + 1 < l; i++) {
67
0
        asdl_seq_SET_UNTYPED(new_seq, i, asdl_seq_GET_UNTYPED(seq, i));
68
0
    }
69
0
    asdl_seq_SET_UNTYPED(new_seq, asdl_seq_LEN(new_seq) - 1, a);
70
0
    return new_seq;
71
0
}
72
73
static Py_ssize_t
74
_get_flattened_seq_size(asdl_seq *seqs)
75
19.4k
{
76
19.4k
    Py_ssize_t size = 0;
77
109k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
78
89.9k
        asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
79
89.9k
        size += asdl_seq_LEN(inner_seq);
80
89.9k
    }
81
19.4k
    return size;
82
19.4k
}
83
84
/* Flattens an asdl_seq* of asdl_seq*s */
85
asdl_seq *
86
_PyPegen_seq_flatten(Parser *p, asdl_seq *seqs)
87
19.4k
{
88
19.4k
    Py_ssize_t flattened_seq_size = _get_flattened_seq_size(seqs);
89
19.4k
    assert(flattened_seq_size > 0);
90
91
19.4k
    asdl_seq *flattened_seq = (asdl_seq*)_Py_asdl_generic_seq_new(flattened_seq_size, p->arena);
92
19.4k
    if (!flattened_seq) {
93
0
        return NULL;
94
0
    }
95
96
19.4k
    int flattened_seq_idx = 0;
97
109k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seqs); i < l; i++) {
98
89.9k
        asdl_seq *inner_seq = asdl_seq_GET_UNTYPED(seqs, i);
99
196k
        for (Py_ssize_t j = 0, li = asdl_seq_LEN(inner_seq); j < li; j++) {
100
106k
            asdl_seq_SET_UNTYPED(flattened_seq, flattened_seq_idx++, asdl_seq_GET_UNTYPED(inner_seq, j));
101
106k
        }
102
89.9k
    }
103
19.4k
    assert(flattened_seq_idx == flattened_seq_size);
104
105
19.4k
    return flattened_seq;
106
19.4k
}
107
108
void *
109
_PyPegen_seq_last_item(asdl_seq *seq)
110
66
{
111
66
    Py_ssize_t len = asdl_seq_LEN(seq);
112
66
    return asdl_seq_GET_UNTYPED(seq, len - 1);
113
66
}
114
115
void *
116
_PyPegen_seq_first_item(asdl_seq *seq)
117
34
{
118
34
    return asdl_seq_GET_UNTYPED(seq, 0);
119
34
}
120
121
/* Creates a new name of the form <first_name>.<second_name> */
122
expr_ty
123
_PyPegen_join_names_with_dot(Parser *p, expr_ty first_name, expr_ty second_name)
124
12.0k
{
125
12.0k
    assert(first_name != NULL && second_name != NULL);
126
12.0k
    PyObject *uni = PyUnicode_FromFormat("%U.%U",
127
12.0k
            first_name->v.Name.id, second_name->v.Name.id);
128
12.0k
    if (!uni) {
129
0
        return NULL;
130
0
    }
131
12.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
132
12.0k
    _PyUnicode_InternImmortal(interp, &uni);
133
12.0k
    if (_PyArena_AddPyObject(p->arena, uni) < 0) {
134
0
        Py_DECREF(uni);
135
0
        return NULL;
136
0
    }
137
138
12.0k
    return _PyAST_Name(uni, Load, EXTRA_EXPR(first_name, second_name));
139
12.0k
}
140
141
/* Counts the total number of dots in seq's tokens */
142
int
143
_PyPegen_seq_count_dots(asdl_seq *seq)
144
6.78k
{
145
6.78k
    int number_of_dots = 0;
146
20.8k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
147
14.0k
        Token *current_expr = asdl_seq_GET_UNTYPED(seq, i);
148
14.0k
        switch (current_expr->type) {
149
6.07k
            case ELLIPSIS:
150
6.07k
                number_of_dots += 3;
151
6.07k
                break;
152
7.96k
            case DOT:
153
7.96k
                number_of_dots += 1;
154
7.96k
                break;
155
0
            default:
156
0
                Py_UNREACHABLE();
157
14.0k
        }
158
14.0k
    }
159
160
6.78k
    return number_of_dots;
161
6.78k
}
162
163
/* Creates an alias with '*' as the identifier name */
164
alias_ty
165
_PyPegen_alias_for_star(Parser *p, int lineno, int col_offset, int end_lineno,
166
2.12k
                        int end_col_offset, PyArena *arena) {
167
2.12k
    PyObject *str = PyUnicode_InternFromString("*");
168
2.12k
    if (!str) {
169
0
        return NULL;
170
0
    }
171
2.12k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
172
0
        Py_DECREF(str);
173
0
        return NULL;
174
0
    }
175
2.12k
    return _PyAST_alias(str, NULL, lineno, col_offset, end_lineno, end_col_offset, arena);
176
2.12k
}
177
178
/* Creates a new asdl_seq* with the identifiers of all the names in seq */
179
asdl_identifier_seq *
180
_PyPegen_map_names_to_ids(Parser *p, asdl_expr_seq *seq)
181
2.03k
{
182
2.03k
    Py_ssize_t len = asdl_seq_LEN(seq);
183
2.03k
    assert(len > 0);
184
185
2.03k
    asdl_identifier_seq *new_seq = _Py_asdl_identifier_seq_new(len, p->arena);
186
2.03k
    if (!new_seq) {
187
0
        return NULL;
188
0
    }
189
6.31k
    for (Py_ssize_t i = 0; i < len; i++) {
190
4.27k
        expr_ty e = asdl_seq_GET(seq, i);
191
4.27k
        asdl_seq_SET(new_seq, i, e->v.Name.id);
192
4.27k
    }
193
2.03k
    return new_seq;
194
2.03k
}
195
196
/* Constructs a CmpopExprPair */
197
CmpopExprPair *
198
_PyPegen_cmpop_expr_pair(Parser *p, cmpop_ty cmpop, expr_ty expr)
199
23.6k
{
200
23.6k
    assert(expr != NULL);
201
23.6k
    CmpopExprPair *a = _PyArena_Malloc(p->arena, sizeof(CmpopExprPair));
202
23.6k
    if (!a) {
203
0
        return NULL;
204
0
    }
205
23.6k
    a->cmpop = cmpop;
206
23.6k
    a->expr = expr;
207
23.6k
    return a;
208
23.6k
}
209
210
asdl_int_seq *
211
_PyPegen_get_cmpops(Parser *p, asdl_seq *seq)
212
8.41k
{
213
8.41k
    Py_ssize_t len = asdl_seq_LEN(seq);
214
8.41k
    assert(len > 0);
215
216
8.41k
    asdl_int_seq *new_seq = _Py_asdl_int_seq_new(len, p->arena);
217
8.41k
    if (!new_seq) {
218
0
        return NULL;
219
0
    }
220
31.2k
    for (Py_ssize_t i = 0; i < len; i++) {
221
22.8k
        CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
222
22.8k
        asdl_seq_SET(new_seq, i, pair->cmpop);
223
22.8k
    }
224
8.41k
    return new_seq;
225
8.41k
}
226
227
asdl_expr_seq *
228
_PyPegen_get_exprs(Parser *p, asdl_seq *seq)
229
8.41k
{
230
8.41k
    Py_ssize_t len = asdl_seq_LEN(seq);
231
8.41k
    assert(len > 0);
232
233
8.41k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
234
8.41k
    if (!new_seq) {
235
0
        return NULL;
236
0
    }
237
31.2k
    for (Py_ssize_t i = 0; i < len; i++) {
238
22.8k
        CmpopExprPair *pair = asdl_seq_GET_UNTYPED(seq, i);
239
22.8k
        asdl_seq_SET(new_seq, i, pair->expr);
240
22.8k
    }
241
8.41k
    return new_seq;
242
8.41k
}
243
244
/* Creates an asdl_seq* where all the elements have been changed to have ctx as context */
245
static asdl_expr_seq *
246
_set_seq_context(Parser *p, asdl_expr_seq *seq, expr_context_ty ctx)
247
6.42k
{
248
6.42k
    Py_ssize_t len = asdl_seq_LEN(seq);
249
6.42k
    if (len == 0) {
250
5.04k
        return NULL;
251
5.04k
    }
252
253
1.37k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
254
1.37k
    if (!new_seq) {
255
0
        return NULL;
256
0
    }
257
3.58k
    for (Py_ssize_t i = 0; i < len; i++) {
258
2.20k
        expr_ty e = asdl_seq_GET(seq, i);
259
2.20k
        expr_ty new_e = _PyPegen_set_expr_context(p, e, ctx);
260
2.20k
        if (!new_e) {
261
0
            return NULL;
262
0
        }
263
2.20k
        asdl_seq_SET(new_seq, i, new_e);
264
2.20k
    }
265
1.37k
    return new_seq;
266
1.37k
}
267
268
static expr_ty
269
_set_name_context(Parser *p, expr_ty e, expr_context_ty ctx)
270
190k
{
271
190k
    return _PyAST_Name(e->v.Name.id, ctx, EXTRA_EXPR(e, e));
272
190k
}
273
274
static expr_ty
275
_set_tuple_context(Parser *p, expr_ty e, expr_context_ty ctx)
276
5.03k
{
277
5.03k
    asdl_expr_seq *seq = _set_seq_context(p, e->v.Tuple.elts, ctx);
278
5.03k
    if (!seq && PyErr_Occurred()) {
279
0
        return NULL;
280
0
    }
281
5.03k
    return _PyAST_Tuple(seq, ctx, EXTRA_EXPR(e, e));
282
5.03k
}
283
284
static expr_ty
285
_set_list_context(Parser *p, expr_ty e, expr_context_ty ctx)
286
1.38k
{
287
1.38k
    asdl_expr_seq *seq = _set_seq_context(p, e->v.List.elts, ctx);
288
1.38k
    if (!seq && PyErr_Occurred()) {
289
0
        return NULL;
290
0
    }
291
1.38k
    return _PyAST_List(seq, ctx, EXTRA_EXPR(e, e));
292
1.38k
}
293
294
static expr_ty
295
_set_subscript_context(Parser *p, expr_ty e, expr_context_ty ctx)
296
1.58k
{
297
1.58k
    return _PyAST_Subscript(e->v.Subscript.value, e->v.Subscript.slice,
298
1.58k
                            ctx, EXTRA_EXPR(e, e));
299
1.58k
}
300
301
static expr_ty
302
_set_attribute_context(Parser *p, expr_ty e, expr_context_ty ctx)
303
5.86k
{
304
5.86k
    return _PyAST_Attribute(e->v.Attribute.value, e->v.Attribute.attr,
305
5.86k
                            ctx, EXTRA_EXPR(e, e));
306
5.86k
}
307
308
static expr_ty
309
_set_starred_context(Parser *p, expr_ty e, expr_context_ty ctx)
310
236
{
311
236
    expr_ty inner = _PyPegen_set_expr_context(p, e->v.Starred.value, ctx);
312
236
    if (!inner) {
313
0
        return NULL;
314
0
    }
315
236
    return _PyAST_Starred(inner, ctx, EXTRA_EXPR(e, e));
316
236
}
317
318
/* Creates an `expr_ty` equivalent to `expr` but with `ctx` as context */
319
expr_ty
320
_PyPegen_set_expr_context(Parser *p, expr_ty expr, expr_context_ty ctx)
321
204k
{
322
204k
    assert(expr != NULL);
323
324
204k
    expr_ty new = NULL;
325
204k
    switch (expr->kind) {
326
190k
        case Name_kind:
327
190k
            new = _set_name_context(p, expr, ctx);
328
190k
            break;
329
5.03k
        case Tuple_kind:
330
5.03k
            new = _set_tuple_context(p, expr, ctx);
331
5.03k
            break;
332
1.38k
        case List_kind:
333
1.38k
            new = _set_list_context(p, expr, ctx);
334
1.38k
            break;
335
1.58k
        case Subscript_kind:
336
1.58k
            new = _set_subscript_context(p, expr, ctx);
337
1.58k
            break;
338
5.86k
        case Attribute_kind:
339
5.86k
            new = _set_attribute_context(p, expr, ctx);
340
5.86k
            break;
341
236
        case Starred_kind:
342
236
            new = _set_starred_context(p, expr, ctx);
343
236
            break;
344
0
        default:
345
0
            new = expr;
346
204k
    }
347
204k
    return new;
348
204k
}
349
350
/* Invalid targets return NULL without raising, allowing parsing to backtrack.
351
   Copy valid targets to preserve the memoized expression's context. */
352
expr_ty
353
_PyPegen_make_target(Parser *p, expr_ty expr, TARGETS_TYPE targets_type)
354
375k
{
355
375k
    assert(expr != NULL);
356
375k
    assert(targets_type != FOR_TARGETS);
357
375k
    if (_PyPegen_get_invalid_target(expr, targets_type) != NULL) {
358
195k
        return NULL;
359
195k
    }
360
179k
    return _PyPegen_set_expr_context(
361
179k
        p, expr, targets_type == DEL_TARGETS ? Del : Store);
362
375k
}
363
364
/* Constructs a KeyValuePair that is used when parsing a dict's key value pairs */
365
KeyValuePair *
366
_PyPegen_key_value_pair(Parser *p, expr_ty key, expr_ty value)
367
30.0k
{
368
30.0k
    KeyValuePair *a = _PyArena_Malloc(p->arena, sizeof(KeyValuePair));
369
30.0k
    if (!a) {
370
0
        return NULL;
371
0
    }
372
30.0k
    a->key = key;
373
30.0k
    a->value = value;
374
30.0k
    return a;
375
30.0k
}
376
377
/* Extracts all keys from an asdl_seq* of KeyValuePair*'s */
378
asdl_expr_seq *
379
_PyPegen_get_keys(Parser *p, asdl_seq *seq)
380
4.18k
{
381
4.18k
    Py_ssize_t len = asdl_seq_LEN(seq);
382
4.18k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
383
4.18k
    if (!new_seq) {
384
0
        return NULL;
385
0
    }
386
19.7k
    for (Py_ssize_t i = 0; i < len; i++) {
387
15.5k
        KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
388
15.5k
        asdl_seq_SET(new_seq, i, pair->key);
389
15.5k
    }
390
4.18k
    return new_seq;
391
4.18k
}
392
393
/* Extracts all values from an asdl_seq* of KeyValuePair*'s */
394
asdl_expr_seq *
395
_PyPegen_get_values(Parser *p, asdl_seq *seq)
396
4.18k
{
397
4.18k
    Py_ssize_t len = asdl_seq_LEN(seq);
398
4.18k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
399
4.18k
    if (!new_seq) {
400
0
        return NULL;
401
0
    }
402
19.7k
    for (Py_ssize_t i = 0; i < len; i++) {
403
15.5k
        KeyValuePair *pair = asdl_seq_GET_UNTYPED(seq, i);
404
15.5k
        asdl_seq_SET(new_seq, i, pair->value);
405
15.5k
    }
406
4.18k
    return new_seq;
407
4.18k
}
408
409
/* Constructs a KeyPatternPair that is used when parsing mapping & class patterns */
410
KeyPatternPair *
411
_PyPegen_key_pattern_pair(Parser *p, expr_ty key, pattern_ty pattern)
412
13.3k
{
413
13.3k
    KeyPatternPair *a = _PyArena_Malloc(p->arena, sizeof(KeyPatternPair));
414
13.3k
    if (!a) {
415
0
        return NULL;
416
0
    }
417
13.3k
    a->key = key;
418
13.3k
    a->pattern = pattern;
419
13.3k
    return a;
420
13.3k
}
421
422
/* Extracts all keys from an asdl_seq* of KeyPatternPair*'s */
423
asdl_expr_seq *
424
_PyPegen_get_pattern_keys(Parser *p, asdl_seq *seq)
425
1.61k
{
426
1.61k
    Py_ssize_t len = asdl_seq_LEN(seq);
427
1.61k
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(len, p->arena);
428
1.61k
    if (!new_seq) {
429
0
        return NULL;
430
0
    }
431
4.20k
    for (Py_ssize_t i = 0; i < len; i++) {
432
2.58k
        KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
433
2.58k
        asdl_seq_SET(new_seq, i, pair->key);
434
2.58k
    }
435
1.61k
    return new_seq;
436
1.61k
}
437
438
/* Extracts all patterns from an asdl_seq* of KeyPatternPair*'s */
439
asdl_pattern_seq *
440
_PyPegen_get_patterns(Parser *p, asdl_seq *seq)
441
1.61k
{
442
1.61k
    Py_ssize_t len = asdl_seq_LEN(seq);
443
1.61k
    asdl_pattern_seq *new_seq = _Py_asdl_pattern_seq_new(len, p->arena);
444
1.61k
    if (!new_seq) {
445
0
        return NULL;
446
0
    }
447
4.20k
    for (Py_ssize_t i = 0; i < len; i++) {
448
2.58k
        KeyPatternPair *pair = asdl_seq_GET_UNTYPED(seq, i);
449
2.58k
        asdl_seq_SET(new_seq, i, pair->pattern);
450
2.58k
    }
451
1.61k
    return new_seq;
452
1.61k
}
453
454
/* Constructs a NameDefaultPair */
455
NameDefaultPair *
456
_PyPegen_name_default_pair(Parser *p, arg_ty arg, expr_ty value, Token *tc)
457
359k
{
458
359k
    NameDefaultPair *a = _PyArena_Malloc(p->arena, sizeof(NameDefaultPair));
459
359k
    if (!a) {
460
0
        return NULL;
461
0
    }
462
359k
    a->arg = _PyPegen_add_type_comment_to_arg(p, arg, tc);
463
359k
    if (!a->arg) {
464
0
        return NULL;
465
0
    }
466
359k
    a->value = value;
467
359k
    return a;
468
359k
}
469
470
/* Constructs a SlashWithDefault */
471
SlashWithDefault *
472
_PyPegen_slash_with_default(Parser *p, asdl_arg_seq *plain_names, asdl_seq *names_with_defaults)
473
6.26k
{
474
6.26k
    SlashWithDefault *a = _PyArena_Malloc(p->arena, sizeof(SlashWithDefault));
475
6.26k
    if (!a) {
476
0
        return NULL;
477
0
    }
478
6.26k
    a->plain_names = plain_names;
479
6.26k
    a->names_with_defaults = names_with_defaults;
480
6.26k
    return a;
481
6.26k
}
482
483
/* Constructs a StarEtc */
484
StarEtc *
485
_PyPegen_star_etc(Parser *p, arg_ty vararg, asdl_seq *kwonlyargs, arg_ty kwarg)
486
7.15k
{
487
7.15k
    StarEtc *a = _PyArena_Malloc(p->arena, sizeof(StarEtc));
488
7.15k
    if (!a) {
489
0
        return NULL;
490
0
    }
491
7.15k
    a->vararg = vararg;
492
7.15k
    a->kwonlyargs = kwonlyargs;
493
7.15k
    a->kwarg = kwarg;
494
7.15k
    return a;
495
7.15k
}
496
497
asdl_seq *
498
_PyPegen_join_sequences(Parser *p, asdl_seq *a, asdl_seq *b)
499
181k
{
500
181k
    Py_ssize_t first_len = asdl_seq_LEN(a);
501
181k
    Py_ssize_t second_len = asdl_seq_LEN(b);
502
181k
    asdl_seq *new_seq = (asdl_seq*)_Py_asdl_generic_seq_new(first_len + second_len, p->arena);
503
181k
    if (!new_seq) {
504
0
        return NULL;
505
0
    }
506
507
181k
    int k = 0;
508
373k
    for (Py_ssize_t i = 0; i < first_len; i++) {
509
191k
        asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(a, i));
510
191k
    }
511
193k
    for (Py_ssize_t i = 0; i < second_len; i++) {
512
11.3k
        asdl_seq_SET_UNTYPED(new_seq, k++, asdl_seq_GET_UNTYPED(b, i));
513
11.3k
    }
514
515
181k
    return new_seq;
516
181k
}
517
518
static asdl_arg_seq*
519
_get_names(Parser *p, asdl_seq *names_with_defaults)
520
189k
{
521
189k
    Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
522
189k
    asdl_arg_seq *seq = _Py_asdl_arg_seq_new(len, p->arena);
523
189k
    if (!seq) {
524
0
        return NULL;
525
0
    }
526
212k
    for (Py_ssize_t i = 0; i < len; i++) {
527
22.9k
        NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
528
22.9k
        asdl_seq_SET(seq, i, pair->arg);
529
22.9k
    }
530
189k
    return seq;
531
189k
}
532
533
static asdl_expr_seq *
534
_get_defaults(Parser *p, asdl_seq *names_with_defaults)
535
189k
{
536
189k
    Py_ssize_t len = asdl_seq_LEN(names_with_defaults);
537
189k
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(len, p->arena);
538
189k
    if (!seq) {
539
0
        return NULL;
540
0
    }
541
212k
    for (Py_ssize_t i = 0; i < len; i++) {
542
22.9k
        NameDefaultPair *pair = asdl_seq_GET_UNTYPED(names_with_defaults, i);
543
22.9k
        asdl_seq_SET(seq, i, pair->value);
544
22.9k
    }
545
189k
    return seq;
546
189k
}
547
548
static int
549
_make_posonlyargs(Parser *p,
550
                  asdl_arg_seq *slash_without_default,
551
                  SlashWithDefault *slash_with_default,
552
188k
                  asdl_arg_seq **posonlyargs) {
553
188k
    if (slash_without_default != NULL) {
554
1.35k
        *posonlyargs = slash_without_default;
555
1.35k
    }
556
186k
    else if (slash_with_default != NULL) {
557
1.98k
        asdl_arg_seq *slash_with_default_names =
558
1.98k
                _get_names(p, slash_with_default->names_with_defaults);
559
1.98k
        if (!slash_with_default_names) {
560
0
            return -1;
561
0
        }
562
1.98k
        *posonlyargs = (asdl_arg_seq*)_PyPegen_join_sequences(
563
1.98k
                p,
564
1.98k
                (asdl_seq*)slash_with_default->plain_names,
565
1.98k
                (asdl_seq*)slash_with_default_names);
566
1.98k
    }
567
184k
    else {
568
184k
        *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
569
184k
    }
570
188k
    return *posonlyargs == NULL ? -1 : 0;
571
188k
}
572
573
static int
574
_make_posargs(Parser *p,
575
              asdl_arg_seq *plain_names,
576
              asdl_seq *names_with_default,
577
188k
              asdl_arg_seq **posargs) {
578
579
188k
    if (names_with_default != NULL) {
580
181k
        if (plain_names != NULL) {
581
177k
            asdl_arg_seq *names_with_default_names = _get_names(p, names_with_default);
582
177k
            if (!names_with_default_names) {
583
0
                return -1;
584
0
            }
585
177k
            *posargs = (asdl_arg_seq*)_PyPegen_join_sequences(
586
177k
                    p,(asdl_seq*)plain_names, (asdl_seq*)names_with_default_names);
587
177k
        }
588
4.48k
        else {
589
4.48k
            *posargs = _get_names(p, names_with_default);
590
4.48k
        }
591
181k
    }
592
6.33k
    else {
593
6.33k
        if (plain_names != NULL) {
594
            // With the current grammar, we never get here.
595
            // If that has changed, remove the assert, and test thoroughly.
596
0
            assert(0);
597
0
            *posargs = plain_names;
598
0
        }
599
6.33k
        else {
600
6.33k
            *posargs = _Py_asdl_arg_seq_new(0, p->arena);
601
6.33k
        }
602
6.33k
    }
603
188k
    return *posargs == NULL ? -1 : 0;
604
188k
}
605
606
static int
607
_make_posdefaults(Parser *p,
608
                  SlashWithDefault *slash_with_default,
609
                  asdl_seq *names_with_default,
610
188k
                  asdl_expr_seq **posdefaults) {
611
188k
    if (slash_with_default != NULL && names_with_default != NULL) {
612
1.98k
        asdl_expr_seq *slash_with_default_values =
613
1.98k
                _get_defaults(p, slash_with_default->names_with_defaults);
614
1.98k
        if (!slash_with_default_values) {
615
0
            return -1;
616
0
        }
617
1.98k
        asdl_expr_seq *names_with_default_values = _get_defaults(p, names_with_default);
618
1.98k
        if (!names_with_default_values) {
619
0
            return -1;
620
0
        }
621
1.98k
        *posdefaults = (asdl_expr_seq*)_PyPegen_join_sequences(
622
1.98k
                p,
623
1.98k
                (asdl_seq*)slash_with_default_values,
624
1.98k
                (asdl_seq*)names_with_default_values);
625
1.98k
    }
626
186k
    else if (slash_with_default == NULL && names_with_default != NULL) {
627
179k
        *posdefaults = _get_defaults(p, names_with_default);
628
179k
    }
629
6.33k
    else if (slash_with_default != NULL && names_with_default == NULL) {
630
0
        *posdefaults = _get_defaults(p, slash_with_default->names_with_defaults);
631
0
    }
632
6.33k
    else {
633
6.33k
        *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
634
6.33k
    }
635
188k
    return *posdefaults == NULL ? -1 : 0;
636
188k
}
637
638
static int
639
_make_kwargs(Parser *p, StarEtc *star_etc,
640
             asdl_arg_seq **kwonlyargs,
641
188k
             asdl_expr_seq **kwdefaults) {
642
188k
    if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
643
5.48k
        *kwonlyargs = _get_names(p, star_etc->kwonlyargs);
644
5.48k
    }
645
182k
    else {
646
182k
        *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
647
182k
    }
648
649
188k
    if (*kwonlyargs == NULL) {
650
0
        return -1;
651
0
    }
652
653
188k
    if (star_etc != NULL && star_etc->kwonlyargs != NULL) {
654
5.48k
        *kwdefaults = _get_defaults(p, star_etc->kwonlyargs);
655
5.48k
    }
656
182k
    else {
657
182k
        *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
658
182k
    }
659
660
188k
    if (*kwdefaults == NULL) {
661
0
        return -1;
662
0
    }
663
664
188k
    return 0;
665
188k
}
666
667
/* Constructs an arguments_ty object out of all the parsed constructs in the parameters rule */
668
arguments_ty
669
_PyPegen_make_arguments(Parser *p, asdl_arg_seq *slash_without_default,
670
                        SlashWithDefault *slash_with_default, asdl_arg_seq *plain_names,
671
                        asdl_seq *names_with_default, StarEtc *star_etc)
672
188k
{
673
188k
    asdl_arg_seq *posonlyargs;
674
188k
    if (_make_posonlyargs(p, slash_without_default, slash_with_default, &posonlyargs) == -1) {
675
0
        return NULL;
676
0
    }
677
678
188k
    asdl_arg_seq *posargs;
679
188k
    if (_make_posargs(p, plain_names, names_with_default, &posargs) == -1) {
680
0
        return NULL;
681
0
    }
682
683
188k
    asdl_expr_seq *posdefaults;
684
188k
    if (_make_posdefaults(p,slash_with_default, names_with_default, &posdefaults) == -1) {
685
0
        return NULL;
686
0
    }
687
688
188k
    arg_ty vararg = NULL;
689
188k
    if (star_etc != NULL && star_etc->vararg != NULL) {
690
4.16k
        vararg = star_etc->vararg;
691
4.16k
    }
692
693
188k
    asdl_arg_seq *kwonlyargs;
694
188k
    asdl_expr_seq *kwdefaults;
695
188k
    if (_make_kwargs(p, star_etc, &kwonlyargs, &kwdefaults) == -1) {
696
0
        return NULL;
697
0
    }
698
699
188k
    arg_ty kwarg = NULL;
700
188k
    if (star_etc != NULL && star_etc->kwarg != NULL) {
701
1.68k
        kwarg = star_etc->kwarg;
702
1.68k
    }
703
704
188k
    return _PyAST_arguments(posonlyargs, posargs, vararg, kwonlyargs,
705
188k
                            kwdefaults, kwarg, posdefaults, p->arena);
706
188k
}
707
708
709
/* Constructs an empty arguments_ty object, that gets used when a function accepts no
710
 * arguments. */
711
arguments_ty
712
_PyPegen_empty_arguments(Parser *p)
713
2.56k
{
714
2.56k
    asdl_arg_seq *posonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
715
2.56k
    if (!posonlyargs) {
716
0
        return NULL;
717
0
    }
718
2.56k
    asdl_arg_seq *posargs = _Py_asdl_arg_seq_new(0, p->arena);
719
2.56k
    if (!posargs) {
720
0
        return NULL;
721
0
    }
722
2.56k
    asdl_expr_seq *posdefaults = _Py_asdl_expr_seq_new(0, p->arena);
723
2.56k
    if (!posdefaults) {
724
0
        return NULL;
725
0
    }
726
2.56k
    asdl_arg_seq *kwonlyargs = _Py_asdl_arg_seq_new(0, p->arena);
727
2.56k
    if (!kwonlyargs) {
728
0
        return NULL;
729
0
    }
730
2.56k
    asdl_expr_seq *kwdefaults = _Py_asdl_expr_seq_new(0, p->arena);
731
2.56k
    if (!kwdefaults) {
732
0
        return NULL;
733
0
    }
734
735
2.56k
    return _PyAST_arguments(posonlyargs, posargs, NULL, kwonlyargs,
736
2.56k
                            kwdefaults, NULL, posdefaults, p->arena);
737
2.56k
}
738
739
/* Encapsulates the value of an operator_ty into an AugOperator struct */
740
AugOperator *
741
_PyPegen_augoperator(Parser *p, operator_ty kind)
742
3.19k
{
743
3.19k
    AugOperator *a = _PyArena_Malloc(p->arena, sizeof(AugOperator));
744
3.19k
    if (!a) {
745
0
        return NULL;
746
0
    }
747
3.19k
    a->kind = kind;
748
3.19k
    return a;
749
3.19k
}
750
751
/* Construct a FunctionDef equivalent to function_def, but with decorators */
752
stmt_ty
753
_PyPegen_function_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty function_def)
754
675
{
755
675
    assert(function_def != NULL);
756
675
    if (function_def->kind == AsyncFunctionDef_kind) {
757
381
        return _PyAST_AsyncFunctionDef(
758
381
            function_def->v.AsyncFunctionDef.name,
759
381
            function_def->v.AsyncFunctionDef.args,
760
381
            function_def->v.AsyncFunctionDef.body, decorators,
761
381
            function_def->v.AsyncFunctionDef.returns,
762
381
            function_def->v.AsyncFunctionDef.type_comment,
763
381
            function_def->v.AsyncFunctionDef.type_params,
764
381
            function_def->lineno, function_def->col_offset,
765
381
            function_def->end_lineno, function_def->end_col_offset, p->arena);
766
381
    }
767
768
294
    return _PyAST_FunctionDef(
769
294
        function_def->v.FunctionDef.name,
770
294
        function_def->v.FunctionDef.args,
771
294
        function_def->v.FunctionDef.body, decorators,
772
294
        function_def->v.FunctionDef.returns,
773
294
        function_def->v.FunctionDef.type_comment,
774
294
        function_def->v.FunctionDef.type_params,
775
294
        function_def->lineno, function_def->col_offset,
776
294
        function_def->end_lineno, function_def->end_col_offset, p->arena);
777
675
}
778
779
/* Construct a ClassDef equivalent to class_def, but with decorators */
780
stmt_ty
781
_PyPegen_class_def_decorators(Parser *p, asdl_expr_seq *decorators, stmt_ty class_def)
782
312
{
783
312
    assert(class_def != NULL);
784
312
    return _PyAST_ClassDef(
785
312
        class_def->v.ClassDef.name,
786
312
        class_def->v.ClassDef.bases, class_def->v.ClassDef.keywords,
787
312
        class_def->v.ClassDef.body, decorators,
788
312
        class_def->v.ClassDef.type_params,
789
312
        class_def->lineno, class_def->col_offset, class_def->end_lineno,
790
312
        class_def->end_col_offset, p->arena);
791
312
}
792
793
/* Construct a KeywordOrStarred */
794
KeywordOrStarred *
795
_PyPegen_keyword_or_starred(Parser *p, void *element, int is_keyword)
796
28.1k
{
797
28.1k
    KeywordOrStarred *a = _PyArena_Malloc(p->arena, sizeof(KeywordOrStarred));
798
28.1k
    if (!a) {
799
0
        return NULL;
800
0
    }
801
28.1k
    a->element = element;
802
28.1k
    a->is_keyword = is_keyword;
803
28.1k
    return a;
804
28.1k
}
805
806
/* Get the number of starred expressions in an asdl_seq* of KeywordOrStarred*s */
807
static int
808
_seq_number_of_starred_exprs(asdl_seq *seq)
809
21.4k
{
810
21.4k
    int n = 0;
811
66.7k
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(seq); i < l; i++) {
812
45.2k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(seq, i);
813
45.2k
        if (!k->is_keyword) {
814
3.47k
            n++;
815
3.47k
        }
816
45.2k
    }
817
21.4k
    return n;
818
21.4k
}
819
820
/* Extract the starred expressions of an asdl_seq* of KeywordOrStarred*s */
821
asdl_expr_seq *
822
_PyPegen_seq_extract_starred_exprs(Parser *p, asdl_seq *kwargs)
823
10.7k
{
824
10.7k
    int new_len = _seq_number_of_starred_exprs(kwargs);
825
10.7k
    if (new_len == 0) {
826
10.0k
        return NULL;
827
10.0k
    }
828
684
    asdl_expr_seq *new_seq = _Py_asdl_expr_seq_new(new_len, p->arena);
829
684
    if (!new_seq) {
830
0
        return NULL;
831
0
    }
832
833
684
    int idx = 0;
834
3.55k
    for (Py_ssize_t i = 0, len = asdl_seq_LEN(kwargs); i < len; i++) {
835
2.87k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
836
2.87k
        if (!k->is_keyword) {
837
1.73k
            asdl_seq_SET(new_seq, idx++, k->element);
838
1.73k
        }
839
2.87k
    }
840
684
    return new_seq;
841
684
}
842
843
/* Return a new asdl_seq* with only the keywords in kwargs */
844
asdl_keyword_seq*
845
_PyPegen_seq_delete_starred_exprs(Parser *p, asdl_seq *kwargs)
846
10.7k
{
847
10.7k
    Py_ssize_t len = asdl_seq_LEN(kwargs);
848
10.7k
    Py_ssize_t new_len = len - _seq_number_of_starred_exprs(kwargs);
849
10.7k
    if (new_len == 0) {
850
0
        return NULL;
851
0
    }
852
10.7k
    asdl_keyword_seq *new_seq = _Py_asdl_keyword_seq_new(new_len, p->arena);
853
10.7k
    if (!new_seq) {
854
0
        return NULL;
855
0
    }
856
857
10.7k
    int idx = 0;
858
33.3k
    for (Py_ssize_t i = 0; i < len; i++) {
859
22.6k
        KeywordOrStarred *k = asdl_seq_GET_UNTYPED(kwargs, i);
860
22.6k
        if (k->is_keyword) {
861
20.9k
            asdl_seq_SET(new_seq, idx++, k->element);
862
20.9k
        }
863
22.6k
    }
864
10.7k
    return new_seq;
865
10.7k
}
866
867
expr_ty
868
_PyPegen_ensure_imaginary(Parser *p, expr_ty exp)
869
1.58k
{
870
1.58k
    if (exp->kind != Constant_kind || !PyComplex_CheckExact(exp->v.Constant.value)) {
871
6
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "imaginary number required in complex literal");
872
6
        return NULL;
873
6
    }
874
1.57k
    return exp;
875
1.58k
}
876
877
expr_ty
878
_PyPegen_ensure_real(Parser *p, expr_ty exp)
879
3.82k
{
880
3.82k
    if (exp->kind != Constant_kind || PyComplex_CheckExact(exp->v.Constant.value)) {
881
4
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(exp, "real number required in complex literal");
882
4
        return NULL;
883
4
    }
884
3.81k
    return exp;
885
3.82k
}
886
887
mod_ty
888
8.87k
_PyPegen_make_module(Parser *p, asdl_stmt_seq *a) {
889
8.87k
    asdl_type_ignore_seq *type_ignores = NULL;
890
8.87k
    Py_ssize_t num = p->type_ignore_comments.num_items;
891
8.87k
    if (num > 0) {
892
        // Turn the raw (comment, lineno) pairs into TypeIgnore objects in the arena
893
0
        type_ignores = _Py_asdl_type_ignore_seq_new(num, p->arena);
894
0
        if (type_ignores == NULL) {
895
0
            return NULL;
896
0
        }
897
0
        for (Py_ssize_t i = 0; i < num; i++) {
898
0
            PyObject *tag = _PyPegen_new_type_comment(p, p->type_ignore_comments.items[i].comment);
899
0
            if (tag == NULL) {
900
0
                return NULL;
901
0
            }
902
0
            type_ignore_ty ti = _PyAST_TypeIgnore(p->type_ignore_comments.items[i].lineno,
903
0
                                                  tag, p->arena);
904
0
            if (ti == NULL) {
905
0
                return NULL;
906
0
            }
907
0
            asdl_seq_SET(type_ignores, i, ti);
908
0
        }
909
0
    }
910
8.87k
    return _PyAST_Module(a, type_ignores, p->arena);
911
8.87k
}
912
913
PyObject *
914
_PyPegen_new_type_comment(Parser *p, const char *s)
915
0
{
916
0
    PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
917
0
    if (res == NULL) {
918
0
        return NULL;
919
0
    }
920
0
    if (_PyArena_AddPyObject(p->arena, res) < 0) {
921
0
        Py_DECREF(res);
922
0
        return NULL;
923
0
    }
924
0
    return res;
925
0
}
926
927
arg_ty
928
_PyPegen_add_type_comment_to_arg(Parser *p, arg_ty a, Token *tc)
929
431k
{
930
431k
    if (tc == NULL) {
931
431k
        return a;
932
431k
    }
933
0
    const char *bytes = PyBytes_AsString(tc->bytes);
934
0
    if (bytes == NULL) {
935
0
        return NULL;
936
0
    }
937
0
    PyObject *tco = _PyPegen_new_type_comment(p, bytes);
938
0
    if (tco == NULL) {
939
0
        return NULL;
940
0
    }
941
0
    return _PyAST_arg(a->arg, a->annotation, tco,
942
0
                      a->lineno, a->col_offset, a->end_lineno, a->end_col_offset,
943
0
                      p->arena);
944
0
}
945
946
/* Checks if the NOTEQUAL token is valid given the current parser flags
947
0 indicates success and nonzero indicates failure (an exception may be set) */
948
int
949
1.08k
_PyPegen_check_barry_as_flufl(Parser *p, Token* t) {
950
1.08k
    assert(t->bytes != NULL);
951
1.08k
    assert(t->type == NOTEQUAL);
952
953
1.08k
    const char* tok_str = PyBytes_AS_STRING(t->bytes);
954
1.08k
    if (p->flags & PyPARSE_BARRY_AS_BDFL && strcmp(tok_str, "<>") != 0) {
955
1
        RAISE_SYNTAX_ERROR("with Barry as BDFL, use '<>' instead of '!='");
956
1
        return -1;
957
1
    }
958
1.08k
    if (!(p->flags & PyPARSE_BARRY_AS_BDFL)) {
959
890
        return strcmp(tok_str, "!=");
960
890
    }
961
194
    return 0;
962
1.08k
}
963
964
int
965
11.5k
_PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
966
11.5k
    if (name->kind != Name_kind) {
967
3.28k
        return 0;
968
3.28k
    }
969
8.24k
    const char* candidates[2] = {"print", "exec"};
970
24.5k
    for (int i=0; i<2; i++) {
971
16.4k
        if (PyUnicode_CompareWithASCIIString(name->v.Name.id, candidates[i]) == 0) {
972
212
            return 1;
973
212
        }
974
16.4k
    }
975
8.03k
    return 0;
976
8.24k
}
977
978
void *
979
_PyPegen_raise_error_for_missing_comma(Parser *p, expr_ty a, expr_ty b)
980
5.33k
{
981
    // Don't raise for legacy statements like "print x" or "exec x"
982
5.33k
    if (_PyPegen_check_legacy_stmt(p, a)) {
983
201
        return NULL;
984
201
    }
985
    // Only raise inside parentheses/brackets (level > 0)
986
5.13k
    if (p->tokens[p->mark - 1]->level == 0) {
987
5.00k
        return NULL;
988
5.00k
    }
989
    // For multi-line expressions (like string concatenations), point to the
990
    // last line instead of the first for a more helpful error message.
991
    // Use a->col_offset as the starting column since all strings in the
992
    // concatenation typically share the same indentation.
993
124
    if (a->end_lineno > a->lineno) {
994
5
        return RAISE_ERROR_KNOWN_LOCATION(
995
5
            p, PyExc_SyntaxError, a->end_lineno, a->col_offset,
996
5
            a->end_lineno, a->end_col_offset,
997
5
            "invalid syntax. Perhaps you forgot a comma?"
998
5
        );
999
5
    }
1000
119
    return RAISE_ERROR_KNOWN_LOCATION(
1001
119
        p, PyExc_SyntaxError, a->lineno, a->col_offset,
1002
119
        b->end_lineno, b->end_col_offset,
1003
119
        "invalid syntax. Perhaps you forgot a comma?"
1004
119
    );
1005
124
}
1006
1007
static ResultTokenWithMetadata *
1008
result_token_with_metadata(Parser *p, void *result, PyObject *metadata)
1009
10.1k
{
1010
10.1k
    ResultTokenWithMetadata *res = _PyArena_Malloc(p->arena, sizeof(ResultTokenWithMetadata));
1011
10.1k
    if (res == NULL) {
1012
0
        return NULL;
1013
0
    }
1014
10.1k
    res->metadata = metadata;
1015
10.1k
    res->result = result;
1016
10.1k
    return res;
1017
10.1k
}
1018
1019
static char
1020
formatted_string_prefix(const Parser *p)
1021
74
{
1022
74
    int nested = 0;
1023
8.34k
    for (int i = p->mark - 1; i >= 0; i--) {
1024
8.34k
        int type = p->tokens[i]->type;
1025
8.34k
        if (type == FSTRING_END || type == TSTRING_END) {
1026
568
            nested++;
1027
568
        }
1028
7.77k
        else if (type == FSTRING_START || type == TSTRING_START) {
1029
642
            if (nested == 0) {
1030
74
                return type == TSTRING_START ? 't' : 'f';
1031
74
            }
1032
568
            nested--;
1033
568
        }
1034
8.34k
    }
1035
74
    Py_UNREACHABLE();
1036
74
}
1037
1038
ResultTokenWithMetadata *
1039
_PyPegen_check_fstring_conversion(Parser *p, Token* conv_token, expr_ty conv)
1040
2.69k
{
1041
2.69k
    if (conv_token->lineno != conv->lineno || conv_token->end_col_offset != conv->col_offset) {
1042
28
        return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1043
28
            conv_token, conv,
1044
28
            "%c-string: conversion type must come right after the exclamation mark",
1045
28
            formatted_string_prefix(p)
1046
28
        );
1047
28
    }
1048
1049
2.66k
    Py_UCS4 first = PyUnicode_READ_CHAR(conv->v.Name.id, 0);
1050
2.66k
    if (PyUnicode_GET_LENGTH(conv->v.Name.id) > 1 ||
1051
2.65k
            !(first == 's' || first == 'r' || first == 'a')) {
1052
46
        RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conv,
1053
46
                                            "%c-string: invalid conversion character %R: expected 's', 'r', or 'a'",
1054
46
                                            formatted_string_prefix(p),
1055
46
                                            conv->v.Name.id);
1056
46
        return NULL;
1057
46
    }
1058
1059
2.62k
    return result_token_with_metadata(p, conv, conv_token->metadata);
1060
2.66k
}
1061
1062
ResultTokenWithMetadata *
1063
_PyPegen_setup_full_format_spec(Parser *p, Token *colon, asdl_expr_seq *spec, int lineno, int col_offset,
1064
                                int end_lineno, int end_col_offset, PyArena *arena)
1065
7.55k
{
1066
7.55k
    if (!spec) {
1067
0
        return NULL;
1068
0
    }
1069
1070
    // This is needed to keep compatibility with 3.11, where an empty format
1071
    // spec is parsed as an *empty* JoinedStr node, instead of having an empty
1072
    // constant in it.
1073
7.55k
    Py_ssize_t n_items = asdl_seq_LEN(spec);
1074
7.55k
    Py_ssize_t non_empty_count = 0;
1075
20.9k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1076
13.3k
        expr_ty item = asdl_seq_GET(spec, i);
1077
13.3k
        non_empty_count += !(item->kind == Constant_kind &&
1078
13.3k
                             PyUnicode_CheckExact(item->v.Constant.value) &&
1079
8.81k
                             PyUnicode_GET_LENGTH(item->v.Constant.value) == 0);
1080
13.3k
    }
1081
7.55k
    if (non_empty_count != n_items) {
1082
3.34k
        asdl_expr_seq *resized_spec =
1083
3.34k
            _Py_asdl_expr_seq_new(non_empty_count, p->arena);
1084
3.34k
        if (resized_spec == NULL) {
1085
0
            return NULL;
1086
0
        }
1087
3.34k
        Py_ssize_t j = 0;
1088
8.14k
        for (Py_ssize_t i = 0; i < n_items; i++) {
1089
4.79k
            expr_ty item = asdl_seq_GET(spec, i);
1090
4.79k
            if (item->kind == Constant_kind &&
1091
4.79k
                PyUnicode_CheckExact(item->v.Constant.value) &&
1092
3.90k
                PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1093
3.34k
                continue;
1094
3.34k
            }
1095
1.45k
            asdl_seq_SET(resized_spec, j++, item);
1096
1.45k
        }
1097
3.34k
        assert(j == non_empty_count);
1098
3.34k
        spec = resized_spec;
1099
3.34k
    }
1100
7.55k
    expr_ty res;
1101
7.55k
    Py_ssize_t n = asdl_seq_LEN(spec);
1102
7.55k
    if (n == 0 || (n == 1 && asdl_seq_GET(spec, 0)->kind == Constant_kind)) {
1103
6.51k
        res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno,
1104
6.51k
                                    end_col_offset, p->arena);
1105
6.51k
    } else {
1106
1.04k
        res = _PyPegen_concatenate_strings(p, spec,
1107
1.04k
                             lineno, col_offset, end_lineno,
1108
1.04k
                             end_col_offset, arena);
1109
1.04k
    }
1110
7.55k
    if (!res) {
1111
0
        return NULL;
1112
0
    }
1113
7.55k
    return result_token_with_metadata(p, res, colon->metadata);
1114
7.55k
}
1115
1116
const char *
1117
_PyPegen_get_expr_name(expr_ty e)
1118
259
{
1119
259
    assert(e != NULL);
1120
259
    switch (e->kind) {
1121
1
        case Attribute_kind:
1122
1
            return "attribute";
1123
1
        case Subscript_kind:
1124
1
            return "subscript";
1125
3
        case Starred_kind:
1126
3
            return "starred";
1127
8
        case Name_kind:
1128
8
            return "name";
1129
2
        case List_kind:
1130
2
            return "list";
1131
7
        case Tuple_kind:
1132
7
            return "tuple";
1133
3
        case Lambda_kind:
1134
3
            return "lambda";
1135
8
        case Call_kind:
1136
8
            return "function call";
1137
4
        case BoolOp_kind:
1138
36
        case BinOp_kind:
1139
44
        case UnaryOp_kind:
1140
44
            return "expression";
1141
1
        case GeneratorExp_kind:
1142
1
            return "generator expression";
1143
2
        case Yield_kind:
1144
3
        case YieldFrom_kind:
1145
3
            return "yield expression";
1146
1
        case Await_kind:
1147
1
            return "await expression";
1148
1
        case ListComp_kind:
1149
1
            return "list comprehension";
1150
1
        case SetComp_kind:
1151
1
            return "set comprehension";
1152
1
        case DictComp_kind:
1153
1
            return "dict comprehension";
1154
2
        case Dict_kind:
1155
2
            return "dict literal";
1156
3
        case Set_kind:
1157
3
            return "set display";
1158
18
        case JoinedStr_kind:
1159
18
        case FormattedValue_kind:
1160
18
            return "f-string expression";
1161
5
        case TemplateStr_kind:
1162
5
        case Interpolation_kind:
1163
5
            return "t-string expression";
1164
122
        case Constant_kind: {
1165
122
            PyObject *value = e->v.Constant.value;
1166
122
            if (value == Py_None) {
1167
1
                return "None";
1168
1
            }
1169
121
            if (value == Py_False) {
1170
1
                return "False";
1171
1
            }
1172
120
            if (value == Py_True) {
1173
1
                return "True";
1174
1
            }
1175
119
            if (value == Py_Ellipsis) {
1176
1
                return "ellipsis";
1177
1
            }
1178
118
            return "literal";
1179
119
        }
1180
22
        case Compare_kind:
1181
22
            return "comparison";
1182
1
        case IfExp_kind:
1183
1
            return "conditional expression";
1184
1
        case NamedExpr_kind:
1185
1
            return "named expression";
1186
0
        default:
1187
0
            PyErr_Format(PyExc_SystemError,
1188
0
                         "unexpected expression in assignment %d (line %d)",
1189
0
                         e->kind, e->lineno);
1190
0
            return NULL;
1191
259
    }
1192
259
}
1193
1194
expr_ty
1195
14
_PyPegen_get_last_comprehension_item(comprehension_ty comprehension) {
1196
14
    if (comprehension->ifs == NULL || asdl_seq_LEN(comprehension->ifs) == 0) {
1197
10
        return comprehension->iter;
1198
10
    }
1199
4
    return PyPegen_last_item(comprehension->ifs, expr_ty);
1200
14
}
1201
1202
expr_ty _PyPegen_collect_call_seqs(Parser *p, asdl_expr_seq *a, asdl_seq *b,
1203
                     int lineno, int col_offset, int end_lineno,
1204
28.7k
                     int end_col_offset, PyArena *arena) {
1205
28.7k
    Py_ssize_t args_len = asdl_seq_LEN(a);
1206
28.7k
    Py_ssize_t total_len = args_len;
1207
1208
28.7k
    if (b == NULL) {
1209
26.7k
        return _PyAST_Call(_PyPegen_dummy_name(p), a, NULL, lineno, col_offset,
1210
26.7k
                        end_lineno, end_col_offset, arena);
1211
1212
26.7k
    }
1213
1214
1.97k
    asdl_expr_seq *starreds = _PyPegen_seq_extract_starred_exprs(p, b);
1215
1.97k
    if (!starreds && PyErr_Occurred()) {
1216
0
        return NULL;
1217
0
    }
1218
1219
1.97k
    asdl_keyword_seq *keywords = _PyPegen_seq_delete_starred_exprs(p, b);
1220
1.97k
    if (!keywords && PyErr_Occurred()) {
1221
0
        return NULL;
1222
0
    }
1223
1224
1.97k
    if (starreds) {
1225
297
        total_len += asdl_seq_LEN(starreds);
1226
297
    }
1227
1228
1.97k
    asdl_expr_seq *args = _Py_asdl_expr_seq_new(total_len, arena);
1229
1.97k
    if (args == NULL) {
1230
0
        return NULL;
1231
0
    }
1232
1233
1.97k
    Py_ssize_t i = 0;
1234
4.25k
    for (i = 0; i < args_len; i++) {
1235
2.28k
        asdl_seq_SET(args, i, asdl_seq_GET(a, i));
1236
2.28k
    }
1237
2.60k
    for (; i < total_len; i++) {
1238
631
        asdl_seq_SET(args, i, asdl_seq_GET(starreds, i - args_len));
1239
631
    }
1240
1241
1.97k
    return _PyAST_Call(_PyPegen_dummy_name(p), args, keywords, lineno,
1242
1.97k
                       col_offset, end_lineno, end_col_offset, arena);
1243
1.97k
}
1244
1245
// AST Error reporting helpers
1246
1247
expr_ty
1248
_PyPegen_get_invalid_target(expr_ty e, TARGETS_TYPE targets_type)
1249
383k
{
1250
383k
    if (e == NULL) {
1251
0
        return NULL;
1252
0
    }
1253
1254
383k
    if (targets_type == SINGLE_TARGETS ||
1255
265k
        targets_type == ATTRIBUTE_OR_SUBSCRIPT_TARGETS) {
1256
236k
        if (targets_type == SINGLE_TARGETS && e->kind == Name_kind) {
1257
75.8k
            return NULL;
1258
75.8k
        }
1259
160k
        return e->kind == Attribute_kind || e->kind == Subscript_kind ? NULL : e;
1260
236k
    }
1261
1262
146k
#define VISIT_CONTAINER(CONTAINER, TYPE) do { \
1263
7.88k
        Py_ssize_t len = asdl_seq_LEN((CONTAINER)->v.TYPE.elts);\
1264
12.1k
        for (Py_ssize_t i = 0; i < len; i++) {\
1265
4.81k
            expr_ty other = asdl_seq_GET((CONTAINER)->v.TYPE.elts, i);\
1266
4.81k
            expr_ty child = _PyPegen_get_invalid_target(other, targets_type);\
1267
4.81k
            if (child != NULL) {\
1268
565
                return child;\
1269
565
            }\
1270
4.81k
        }\
1271
7.88k
    } while (0)
1272
1273
    // We only need to visit List and Tuple nodes recursively as those
1274
    // are the only ones that can contain valid names in targets when
1275
    // they are parsed as expressions. Any other kind of expression
1276
    // that is a container (like Sets or Dicts) is directly invalid and
1277
    // we don't need to visit it recursively.
1278
1279
146k
    switch (e->kind) {
1280
1.70k
        case List_kind:
1281
1.70k
            VISIT_CONTAINER(e, List);
1282
1.42k
            return NULL;
1283
6.17k
        case Tuple_kind:
1284
6.17k
            VISIT_CONTAINER(e, Tuple);
1285
5.89k
            return NULL;
1286
1.26k
        case Starred_kind:
1287
1.26k
            if (targets_type == DEL_TARGETS) {
1288
6
                return e;
1289
6
            }
1290
1.25k
            return _PyPegen_get_invalid_target(e->v.Starred.value, targets_type);
1291
995
        case Compare_kind:
1292
            // This is needed, because the `a in b` in `for a in b` gets parsed
1293
            // as a comparison, and so we need to search the left side of the comparison
1294
            // for invalid targets.
1295
995
            if (targets_type == FOR_TARGETS) {
1296
862
                cmpop_ty cmpop = (cmpop_ty) asdl_seq_GET(e->v.Compare.ops, 0);
1297
862
                if (cmpop == In) {
1298
274
                    return _PyPegen_get_invalid_target(e->v.Compare.left, targets_type);
1299
274
                }
1300
588
                return NULL;
1301
862
            }
1302
133
            return e;
1303
93.6k
        case Name_kind:
1304
94.9k
        case Subscript_kind:
1305
97.0k
        case Attribute_kind:
1306
97.0k
            return NULL;
1307
39.7k
        default:
1308
39.7k
            return e;
1309
146k
    }
1310
146k
}
1311
1312
31
void *_PyPegen_arguments_parsing_error(Parser *p, expr_ty e) {
1313
31
    int kwarg_unpacking = 0;
1314
921
    for (Py_ssize_t i = 0, l = asdl_seq_LEN(e->v.Call.keywords); i < l; i++) {
1315
890
        keyword_ty keyword = asdl_seq_GET(e->v.Call.keywords, i);
1316
890
        if (!keyword->arg) {
1317
538
            kwarg_unpacking = 1;
1318
538
        }
1319
890
    }
1320
1321
31
    const char *msg = NULL;
1322
31
    if (kwarg_unpacking) {
1323
17
        msg = "positional argument follows keyword argument unpacking";
1324
17
    } else {
1325
14
        msg = "positional argument follows keyword argument";
1326
14
    }
1327
1328
31
    return RAISE_SYNTAX_ERROR(msg);
1329
31
}
1330
1331
void *
1332
_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions)
1333
250
{
1334
    /* The rule that calls this function is 'args for_if_clauses'.
1335
       For the input f(L, x for x in y), L and x are in args and
1336
       the for is parsed as a for_if_clause. We have to check if
1337
       len <= 1, so that input like dict((a, b) for a, b in x)
1338
       gets successfully parsed and then we pass the last
1339
       argument (x in the above example) as the location of the
1340
       error */
1341
250
    Py_ssize_t len = asdl_seq_LEN(args->v.Call.args);
1342
250
    if (len <= 1) {
1343
248
        return NULL;
1344
248
    }
1345
1346
2
    comprehension_ty last_comprehension = PyPegen_last_item(comprehensions, comprehension_ty);
1347
1348
2
    return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1349
250
        (expr_ty) asdl_seq_GET(args->v.Call.args, len - 1),
1350
250
        _PyPegen_get_last_comprehension_item(last_comprehension),
1351
250
        "Generator expression must be parenthesized"
1352
250
    );
1353
250
}
1354
1355
// Fstring stuff
1356
1357
static expr_ty
1358
30.4k
_PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant, Token* token) {
1359
30.4k
    assert(PyUnicode_CheckExact(constant->v.Constant.value));
1360
1361
30.4k
    const char* bstr = PyUnicode_AsUTF8(constant->v.Constant.value);
1362
30.4k
    if (bstr == NULL) {
1363
0
        return NULL;
1364
0
    }
1365
1366
30.4k
    size_t len;
1367
30.4k
    if (strcmp(bstr, "{{") == 0 || strcmp(bstr, "}}") == 0) {
1368
0
        len = 1;
1369
30.4k
    } else {
1370
30.4k
        len = strlen(bstr);
1371
30.4k
    }
1372
1373
30.4k
    is_raw = is_raw || strchr(bstr, '\\') == NULL;
1374
30.4k
    PyObject *str = _PyPegen_decode_string(p, is_raw, bstr, len, token);
1375
30.4k
    if (str == NULL) {
1376
8
        _Pypegen_raise_decode_error_known_location(p, constant);
1377
8
        return NULL;
1378
8
    }
1379
30.4k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1380
0
        Py_DECREF(str);
1381
0
        return NULL;
1382
0
    }
1383
30.4k
    return _PyAST_Constant(str, NULL, constant->lineno, constant->col_offset,
1384
30.4k
                           constant->end_lineno, constant->end_col_offset,
1385
30.4k
                           p->arena);
1386
30.4k
}
1387
1388
static asdl_expr_seq *
1389
_get_resized_exprs(Parser *p, Token *a, asdl_expr_seq *raw_expressions,
1390
                   Token *b, int is_tstring)
1391
22.2k
{
1392
22.2k
    Py_ssize_t n_items = asdl_seq_LEN(raw_expressions);
1393
22.2k
    Py_ssize_t total_items = n_items;
1394
75.0k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1395
52.8k
        expr_ty item = asdl_seq_GET(raw_expressions, i);
1396
52.8k
        if (item->kind == JoinedStr_kind) {
1397
8.60k
            total_items += asdl_seq_LEN(item->v.JoinedStr.values) - 1;
1398
8.60k
        }
1399
52.8k
    }
1400
1401
22.2k
    const char* quote_str = PyBytes_AsString(a->bytes);
1402
22.2k
    if (quote_str == NULL) {
1403
0
        return NULL;
1404
0
    }
1405
22.2k
    int is_raw = strpbrk(quote_str, "rR") != NULL;
1406
1407
22.2k
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(total_items, p->arena);
1408
22.2k
    if (seq == NULL) {
1409
0
        return NULL;
1410
0
    }
1411
1412
22.2k
    Py_ssize_t index = 0;
1413
75.0k
    for (Py_ssize_t i = 0; i < n_items; i++) {
1414
52.8k
        expr_ty item = asdl_seq_GET(raw_expressions, i);
1415
1416
        /* Debug expressions arrive as JoinedStr(text, value); flatten them
1417
           into the surrounding string. */
1418
52.8k
        if (item->kind == JoinedStr_kind) {
1419
8.60k
            asdl_expr_seq *values = item->v.JoinedStr.values;
1420
8.60k
            if (asdl_seq_LEN(values) != 2) {
1421
0
                PyErr_Format(PyExc_SystemError,
1422
0
                             is_tstring
1423
0
                             ? "unexpected TemplateStr node without debug data in t-string at line %d"
1424
0
                             : "unexpected JoinedStr node without debug data in f-string at line %d",
1425
0
                             item->lineno);
1426
0
                return NULL;
1427
0
            }
1428
1429
8.60k
            expr_ty first = asdl_seq_GET(values, 0);
1430
8.60k
            assert(first->kind == Constant_kind);
1431
8.60k
            asdl_seq_SET(seq, index++, first);
1432
1433
8.60k
            expr_ty second = asdl_seq_GET(values, 1);
1434
8.60k
            assert((is_tstring &&
1435
8.60k
                    second->kind == Interpolation_kind) ||
1436
8.60k
                   second->kind == FormattedValue_kind);
1437
8.60k
            asdl_seq_SET(seq, index++, second);
1438
1439
8.60k
            continue;
1440
8.60k
        }
1441
1442
44.2k
        if (item->kind == Constant_kind) {
1443
30.4k
            item = _PyPegen_decode_fstring_part(p, is_raw, item, b);
1444
30.4k
            if (item == NULL) {
1445
8
                return NULL;
1446
8
            }
1447
1448
            /* Tokenizer emits string parts even when the underlying string
1449
            might become an empty value (e.g. FSTRING_MIDDLE with the value \\n)
1450
            so we need to check for them and simplify it here. */
1451
30.4k
            if (PyUnicode_CheckExact(item->v.Constant.value)
1452
30.4k
                && PyUnicode_GET_LENGTH(item->v.Constant.value) == 0) {
1453
598
                continue;
1454
598
            }
1455
30.4k
        }
1456
43.5k
        asdl_seq_SET(seq, index++, item);
1457
43.5k
    }
1458
1459
22.2k
    asdl_expr_seq *resized_exprs;
1460
22.2k
    if (index != total_items) {
1461
598
        resized_exprs = _Py_asdl_expr_seq_new(index, p->arena);
1462
598
        if (resized_exprs == NULL) {
1463
0
            return NULL;
1464
0
        }
1465
2.39k
        for (Py_ssize_t i = 0; i < index; i++) {
1466
1.79k
            asdl_seq_SET(resized_exprs, i, asdl_seq_GET(seq, i));
1467
1.79k
        }
1468
598
    }
1469
21.6k
    else {
1470
21.6k
        resized_exprs = seq;
1471
21.6k
    }
1472
22.2k
    return resized_exprs;
1473
22.2k
}
1474
1475
expr_ty
1476
4.03k
_PyPegen_template_str(Parser *p, Token *a, asdl_expr_seq *raw_expressions, Token *b) {
1477
1478
4.03k
    asdl_expr_seq *resized_exprs = _get_resized_exprs(p, a, raw_expressions, b, 1);
1479
4.03k
    if (resized_exprs == NULL) {
1480
3
        return NULL;
1481
3
    }
1482
4.02k
    return _PyAST_TemplateStr(resized_exprs, a->lineno, a->col_offset,
1483
4.02k
                              b->end_lineno, b->end_col_offset,
1484
4.02k
                              p->arena);
1485
4.03k
}
1486
1487
expr_ty
1488
18.2k
_PyPegen_joined_str(Parser *p, Token* a, asdl_expr_seq* raw_expressions, Token*b) {
1489
1490
18.2k
    asdl_expr_seq *resized_exprs = _get_resized_exprs(p, a, raw_expressions, b, 0);
1491
18.2k
    if (resized_exprs == NULL) {
1492
5
        return NULL;
1493
5
    }
1494
18.2k
    return _PyAST_JoinedStr(resized_exprs, a->lineno, a->col_offset,
1495
18.2k
                            b->end_lineno, b->end_col_offset,
1496
18.2k
                            p->arena);
1497
18.2k
}
1498
1499
9.19k
expr_ty _PyPegen_decoded_constant_from_token(Parser* p, Token* tok) {
1500
9.19k
    if (tok->bytes == NULL) {
1501
0
        return _PyPegen_raise_incomplete_input(p);
1502
0
    }
1503
9.19k
    Py_ssize_t bsize = PyBytes_GET_SIZE(tok->bytes);
1504
9.19k
    const char *bstr = PyBytes_AS_STRING(tok->bytes);
1505
1506
9.19k
    int is_raw = tok->is_raw;
1507
1508
9.19k
    PyObject* str = _PyPegen_decode_string(p, is_raw, bstr, bsize, tok);
1509
9.19k
    if (str == NULL) {
1510
3
        if ((p->flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) || tok->is_incomplete) {
1511
0
            _Pypegen_raise_decode_error(p);
1512
0
        }
1513
3
        return NULL;
1514
3
    }
1515
9.18k
    if (tok->is_incomplete) {
1516
0
        Py_DECREF(str);
1517
0
        return _PyPegen_raise_incomplete_input(p);
1518
0
    }
1519
9.18k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1520
0
        Py_DECREF(str);
1521
0
        return NULL;
1522
0
    }
1523
9.18k
    return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1524
9.18k
                           tok->end_lineno, tok->end_col_offset,
1525
9.18k
                           p->arena);
1526
9.18k
}
1527
1528
34.9k
expr_ty _PyPegen_constant_from_token(Parser* p, Token* tok) {
1529
34.9k
    if (tok->bytes == NULL) {
1530
0
        return _PyPegen_raise_incomplete_input(p);
1531
0
    }
1532
34.9k
    const char *bstr = PyBytes_AS_STRING(tok->bytes);
1533
34.9k
    Py_ssize_t bsize = PyBytes_GET_SIZE(tok->bytes);
1534
34.9k
    if (((p->flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) || tok->is_incomplete) &&
1535
0
        !tok->is_raw && memchr(bstr, '\\', bsize) != NULL) {
1536
        // Check escapes before the string is complete, without emitting warnings.
1537
0
        PyObject *decoded = _PyPegen_decode_string(
1538
0
            p, 0, bstr, bsize, tok->is_incomplete ? tok : NULL);
1539
0
        if (decoded == NULL) {
1540
0
            _Pypegen_raise_decode_error(p);
1541
0
            return NULL;
1542
0
        }
1543
0
        Py_DECREF(decoded);
1544
0
    }
1545
34.9k
    if (tok->is_incomplete) {
1546
0
        return _PyPegen_raise_incomplete_input(p);
1547
0
    }
1548
34.9k
    PyObject* str = PyUnicode_FromString(bstr);
1549
34.9k
    if (str == NULL) {
1550
0
        return NULL;
1551
0
    }
1552
34.9k
    if (_PyArena_AddPyObject(p->arena, str) < 0) {
1553
0
        Py_DECREF(str);
1554
0
        return NULL;
1555
0
    }
1556
34.9k
    return _PyAST_Constant(str, NULL, tok->lineno, tok->col_offset,
1557
34.9k
                           tok->end_lineno, tok->end_col_offset,
1558
34.9k
                           p->arena);
1559
34.9k
}
1560
1561
53.3k
expr_ty _PyPegen_constant_from_string(Parser* p, Token* tok) {
1562
53.3k
    if (tok->bytes == NULL) {
1563
0
        return _PyPegen_raise_incomplete_input(p);
1564
0
    }
1565
53.3k
    const char *the_str = PyBytes_AS_STRING(tok->bytes);
1566
53.3k
    PyObject *s = _PyPegen_parse_string(p, tok);
1567
53.3k
    if (s == NULL) {
1568
123
        _Pypegen_raise_decode_error(p);
1569
123
        return NULL;
1570
123
    }
1571
53.1k
    if (_PyArena_AddPyObject(p->arena, s) < 0) {
1572
0
        Py_DECREF(s);
1573
0
        return NULL;
1574
0
    }
1575
53.1k
    PyObject *kind = NULL;
1576
53.1k
    if (the_str && the_str[0] == 'u') {
1577
2.00k
        kind = _PyPegen_new_identifier(p, "u");
1578
2.00k
        if (kind == NULL) {
1579
0
            return NULL;
1580
0
        }
1581
2.00k
    }
1582
53.1k
    return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno, tok->end_col_offset, p->arena);
1583
53.1k
}
1584
1585
static int
1586
_get_interpolation_conversion(Parser *p, Token *debug, ResultTokenWithMetadata *conversion,
1587
                              ResultTokenWithMetadata *format)
1588
30.9k
{
1589
30.9k
    if (conversion != NULL) {
1590
2.59k
        expr_ty conversion_expr = (expr_ty) conversion->result;
1591
2.59k
        assert(conversion_expr->kind == Name_kind);
1592
2.59k
        Py_UCS4 first = PyUnicode_READ_CHAR(conversion_expr->v.Name.id, 0);
1593
2.59k
        return Py_SAFE_DOWNCAST(first, Py_UCS4, int);
1594
2.59k
    }
1595
28.3k
    else if (debug && !format) {
1596
        /* If no conversion is specified, use !r for debug expressions */
1597
9.34k
        return (int)'r';
1598
9.34k
    }
1599
19.0k
    return -1;
1600
30.9k
}
1601
1602
static PyObject *
1603
_strip_interpolation_debug_expr(PyObject *exprstr)
1604
1.69k
{
1605
1.69k
    Py_ssize_t len = PyUnicode_GET_LENGTH(exprstr);
1606
1607
    /* Discard whitespace and explicit line continuations after the debug "="
1608
       but preserve whitespace before it. */
1609
2.13k
    while (len > 0) {
1610
2.13k
        int has_newline = 0;
1611
5.21k
        while (len > 0) {
1612
5.21k
            Py_UCS4 c = PyUnicode_READ_CHAR(exprstr, len - 1);
1613
5.21k
            if (!_PyUnicode_IsWhitespace(c)) {
1614
2.13k
                break;
1615
2.13k
            }
1616
3.07k
            if (c == '\r' || c == '\n') {
1617
1.92k
                has_newline = 1;
1618
1.92k
            }
1619
3.07k
            len--;
1620
3.07k
        }
1621
2.13k
        if (!has_newline || len == 0 ||
1622
905
            PyUnicode_READ_CHAR(exprstr, len - 1) != '\\')
1623
1.69k
        {
1624
1.69k
            break;
1625
1.69k
        }
1626
439
        len--;
1627
439
    }
1628
1629
    /* Preserve unexpected metadata instead of dropping source text. */
1630
1.69k
    if (len == 0 || PyUnicode_READ_CHAR(exprstr, len - 1) != '=') {
1631
0
        return Py_NewRef(exprstr);
1632
0
    }
1633
1634
1.69k
    return PyUnicode_Substring(exprstr, 0, len - 1);
1635
1.69k
}
1636
1637
expr_ty _PyPegen_interpolation(Parser *p, expr_ty expression, Token *debug, ResultTokenWithMetadata *conversion,
1638
                                 ResultTokenWithMetadata *format, Token *closing_brace, int lineno, int col_offset,
1639
6.40k
                                 int end_lineno, int end_col_offset, PyArena *arena) {
1640
1641
6.40k
    int conversion_val = _get_interpolation_conversion(p, debug, conversion, format);
1642
1643
    /* Find the non whitespace token after the "=" */
1644
6.40k
    int debug_end_line, debug_end_offset;
1645
6.40k
    PyObject *debug_metadata;
1646
6.40k
    constant exprstr;
1647
1648
6.40k
    if (conversion) {
1649
592
        debug_end_line = ((expr_ty) conversion->result)->lineno;
1650
592
        debug_end_offset = ((expr_ty) conversion->result)->col_offset;
1651
592
        debug_metadata = exprstr = conversion->metadata;
1652
592
    }
1653
5.81k
    else if (format) {
1654
1.57k
        debug_end_line = ((expr_ty) format->result)->lineno;
1655
1.57k
        debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1656
1.57k
        debug_metadata = exprstr = format->metadata;
1657
1.57k
    }
1658
4.24k
    else {
1659
4.24k
        debug_end_line = end_lineno;
1660
4.24k
        debug_end_offset = end_col_offset;
1661
4.24k
        debug_metadata = exprstr = closing_brace->metadata;
1662
4.24k
    }
1663
1664
6.40k
    assert(exprstr != NULL);
1665
6.40k
    PyObject *final_exprstr = debug
1666
6.40k
        ? _strip_interpolation_debug_expr(exprstr)
1667
6.40k
        : Py_NewRef(exprstr);
1668
6.40k
    if (!final_exprstr || _PyArena_AddPyObject(arena, final_exprstr) < 0) {
1669
0
        Py_XDECREF(final_exprstr);
1670
0
        return NULL;
1671
0
    }
1672
1673
6.40k
    expr_ty interpolation = _PyAST_Interpolation(
1674
6.40k
        expression, final_exprstr, conversion_val, format ? (expr_ty) format->result : NULL,
1675
6.40k
        lineno, col_offset, end_lineno,
1676
6.40k
        end_col_offset, arena
1677
6.40k
    );
1678
1679
6.40k
    if (!interpolation || !debug) {
1680
4.71k
        return interpolation;
1681
4.71k
    }
1682
1683
1.69k
    expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1684
1.69k
                                            debug_end_offset - 1, p->arena);
1685
1.69k
    if (!debug_text) {
1686
0
        return NULL;
1687
0
    }
1688
1689
1.69k
    asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1690
1.69k
    if (!values) {
1691
0
        return NULL;
1692
0
    }
1693
1.69k
    asdl_seq_SET(values, 0, debug_text);
1694
1.69k
    asdl_seq_SET(values, 1, interpolation);
1695
1.69k
    return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1696
1.69k
}
1697
1698
expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug, ResultTokenWithMetadata *conversion,
1699
                                 ResultTokenWithMetadata *format, Token *closing_brace, int lineno, int col_offset,
1700
24.5k
                                 int end_lineno, int end_col_offset, PyArena *arena) {
1701
24.5k
    int conversion_val = _get_interpolation_conversion(p, debug, conversion, format);
1702
1703
24.5k
    expr_ty formatted_value = _PyAST_FormattedValue(
1704
24.5k
        expression, conversion_val, format ? (expr_ty) format->result : NULL,
1705
24.5k
        lineno, col_offset, end_lineno,
1706
24.5k
        end_col_offset, arena
1707
24.5k
    );
1708
1709
24.5k
    if (!formatted_value || !debug) {
1710
15.8k
        return formatted_value;
1711
15.8k
    }
1712
1713
    /* Find the non whitespace token after the "=" */
1714
8.77k
    int debug_end_line, debug_end_offset;
1715
8.77k
    PyObject *debug_metadata;
1716
1717
8.77k
    if (conversion) {
1718
198
        debug_end_line = ((expr_ty) conversion->result)->lineno;
1719
198
        debug_end_offset = ((expr_ty) conversion->result)->col_offset;
1720
198
        debug_metadata = conversion->metadata;
1721
198
    }
1722
8.57k
    else if (format) {
1723
259
        debug_end_line = ((expr_ty) format->result)->lineno;
1724
259
        debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1725
259
        debug_metadata = format->metadata;
1726
259
    }
1727
8.31k
    else {
1728
8.31k
        debug_end_line = end_lineno;
1729
8.31k
        debug_end_offset = end_col_offset;
1730
8.31k
        debug_metadata = closing_brace->metadata;
1731
8.31k
    }
1732
8.77k
    expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1733
8.77k
                                            debug_end_offset - 1, p->arena);
1734
8.77k
    if (!debug_text) {
1735
0
        return NULL;
1736
0
    }
1737
1738
8.77k
    asdl_expr_seq *values = _Py_asdl_expr_seq_new(2, arena);
1739
8.77k
    if (!values) {
1740
0
        return NULL;
1741
0
    }
1742
8.77k
    asdl_seq_SET(values, 0, debug_text);
1743
8.77k
    asdl_seq_SET(values, 1, formatted_value);
1744
8.77k
    return _PyAST_JoinedStr(values, lineno, col_offset, debug_end_line, debug_end_offset, p->arena);
1745
8.77k
}
1746
1747
static expr_ty
1748
_build_concatenated_bytes(Parser *p, asdl_expr_seq *strings, int lineno,
1749
                        int col_offset, int end_lineno, int end_col_offset,
1750
                        PyArena *arena)
1751
770
{
1752
770
    Py_ssize_t len = asdl_seq_LEN(strings);
1753
770
    assert(len > 0);
1754
1755
    /* Bytes literals never get a kind, but just for consistency
1756
        since they are represented as Constant nodes, we'll mirror
1757
        the same behavior as unicode strings for determining the
1758
        kind. */
1759
770
    PyObject *kind = asdl_seq_GET(strings, 0)->v.Constant.kind;
1760
1761
770
    Py_ssize_t total = 0;
1762
4.69k
    for (Py_ssize_t i = 0; i < len; i++) {
1763
3.92k
        expr_ty elem = asdl_seq_GET(strings, i);
1764
3.92k
        PyObject *bytes = elem->v.Constant.value;
1765
3.92k
        Py_ssize_t part = PyBytes_GET_SIZE(bytes);
1766
3.92k
        if (part > PY_SSIZE_T_MAX - total) {
1767
0
            PyErr_NoMemory();
1768
0
            return NULL;
1769
0
        }
1770
3.92k
        total += part;
1771
3.92k
    }
1772
1773
770
    PyBytesWriter *writer = PyBytesWriter_Create(total);
1774
770
    if (writer == NULL) {
1775
0
        return NULL;
1776
0
    }
1777
770
    char *out = PyBytesWriter_GetData(writer);
1778
1779
4.69k
    for (Py_ssize_t i = 0; i < len; i++) {
1780
3.92k
        expr_ty elem = asdl_seq_GET(strings, i);
1781
3.92k
        PyObject *bytes = elem->v.Constant.value;
1782
3.92k
        Py_ssize_t part = PyBytes_GET_SIZE(bytes);
1783
3.92k
        if (part > 0) {
1784
2.10k
            memcpy(out, PyBytes_AS_STRING(bytes), part);
1785
2.10k
            out += part;
1786
2.10k
        }
1787
3.92k
    }
1788
1789
770
    PyObject *res = PyBytesWriter_Finish(writer);
1790
770
    if (res == NULL) {
1791
0
        return NULL;
1792
0
    }
1793
770
    if (_PyArena_AddPyObject(arena, res) < 0) {
1794
0
        Py_DECREF(res);
1795
0
        return NULL;
1796
0
    }
1797
770
    return _PyAST_Constant(res, kind, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1798
770
}
1799
1800
static expr_ty
1801
_build_concatenated_unicode(Parser *p, asdl_expr_seq *strings, int lineno,
1802
                        int col_offset, int end_lineno, int end_col_offset,
1803
                        PyArena *arena)
1804
1.41k
{
1805
1.41k
    Py_ssize_t len = asdl_seq_LEN(strings);
1806
1.41k
    assert(len > 1);
1807
1808
1.41k
    expr_ty first = asdl_seq_GET(strings, 0);
1809
1810
    /* When a string is getting concatenated, the kind of the string
1811
        is determined by the first string in the concatenation
1812
        sequence.
1813
1814
        u"abc" "def" -> u"abcdef"
1815
        "abc" u"abc" ->  "abcabc" */
1816
1.41k
    PyObject *kind = first->v.Constant.kind;
1817
1818
1.41k
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1819
1.41k
    if (writer == NULL) {
1820
0
        return NULL;
1821
0
    }
1822
1823
23.6k
    for (Py_ssize_t i = 0; i < len; i++) {
1824
22.2k
        expr_ty current_elem = asdl_seq_GET(strings, i);
1825
22.2k
        assert(current_elem->kind == Constant_kind);
1826
1827
22.2k
        if (PyUnicodeWriter_WriteStr(writer,
1828
22.2k
                                     current_elem->v.Constant.value)) {
1829
0
            PyUnicodeWriter_Discard(writer);
1830
0
            return NULL;
1831
0
        }
1832
22.2k
    }
1833
1834
1.41k
    PyObject *final = PyUnicodeWriter_Finish(writer);
1835
1.41k
    if (final == NULL) {
1836
0
        return NULL;
1837
0
    }
1838
1.41k
    if (_PyArena_AddPyObject(p->arena, final) < 0) {
1839
0
        Py_DECREF(final);
1840
0
        return NULL;
1841
0
    }
1842
1.41k
    return _PyAST_Constant(final, kind, lineno, col_offset,
1843
1.41k
                           end_lineno, end_col_offset, arena);
1844
1.41k
}
1845
1846
static asdl_expr_seq *
1847
_build_concatenated_str(Parser *p, asdl_expr_seq *strings,
1848
                               int lineno, int col_offset, int end_lineno,
1849
                               int end_col_offset, PyArena *arena)
1850
14.9k
{
1851
14.9k
    Py_ssize_t len = asdl_seq_LEN(strings);
1852
14.9k
    assert(len > 0);
1853
1854
14.9k
    Py_ssize_t n_flattened_elements = 0;
1855
45.6k
    for (Py_ssize_t i = 0; i < len; i++) {
1856
30.7k
        expr_ty elem = asdl_seq_GET(strings, i);
1857
30.7k
        switch(elem->kind) {
1858
15.6k
            case JoinedStr_kind:
1859
15.6k
                n_flattened_elements += asdl_seq_LEN(elem->v.JoinedStr.values);
1860
15.6k
                break;
1861
3.38k
            case TemplateStr_kind:
1862
3.38k
                n_flattened_elements += asdl_seq_LEN(elem->v.TemplateStr.values);
1863
3.38k
                break;
1864
11.6k
            default:
1865
11.6k
                n_flattened_elements++;
1866
11.6k
                break;
1867
30.7k
        }
1868
30.7k
    }
1869
1870
1871
14.9k
    asdl_expr_seq* flattened = _Py_asdl_expr_seq_new(n_flattened_elements, p->arena);
1872
14.9k
    if (flattened == NULL) {
1873
0
        return NULL;
1874
0
    }
1875
1876
    /* build flattened list */
1877
14.9k
    Py_ssize_t current_pos = 0;
1878
45.6k
    for (Py_ssize_t i = 0; i < len; i++) {
1879
30.7k
        expr_ty elem = asdl_seq_GET(strings, i);
1880
30.7k
        switch(elem->kind) {
1881
15.6k
            case JoinedStr_kind:
1882
62.4k
                for (Py_ssize_t j = 0; j < asdl_seq_LEN(elem->v.JoinedStr.values); j++) {
1883
46.7k
                    expr_ty subvalue = asdl_seq_GET(elem->v.JoinedStr.values, j);
1884
46.7k
                    if (subvalue == NULL) {
1885
0
                        return NULL;
1886
0
                    }
1887
46.7k
                    asdl_seq_SET(flattened, current_pos++, subvalue);
1888
46.7k
                }
1889
15.6k
                break;
1890
15.6k
            case TemplateStr_kind:
1891
12.1k
                for (Py_ssize_t j = 0; j < asdl_seq_LEN(elem->v.TemplateStr.values); j++) {
1892
8.71k
                    expr_ty subvalue = asdl_seq_GET(elem->v.TemplateStr.values, j);
1893
8.71k
                    if (subvalue == NULL) {
1894
0
                        return NULL;
1895
0
                    }
1896
8.71k
                    asdl_seq_SET(flattened, current_pos++, subvalue);
1897
8.71k
                }
1898
3.38k
                break;
1899
11.6k
            default:
1900
11.6k
                asdl_seq_SET(flattened, current_pos++, elem);
1901
11.6k
                break;
1902
30.7k
        }
1903
30.7k
    }
1904
1905
    /* calculate folded element count */
1906
14.9k
    Py_ssize_t n_elements = 0;
1907
14.9k
    int prev_is_constant = 0;
1908
82.0k
    for (Py_ssize_t i = 0; i < n_flattened_elements; i++) {
1909
67.1k
        expr_ty elem = asdl_seq_GET(flattened, i);
1910
1911
        /* The concatenation of a FormattedValue and an empty Constant should
1912
           lead to the FormattedValue itself. Thus, we will not take any empty
1913
           constants into account, just as in `_PyPegen_joined_str` */
1914
67.1k
        if (elem->kind == Constant_kind &&
1915
67.1k
            PyUnicode_CheckExact(elem->v.Constant.value) &&
1916
41.5k
            PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0)
1917
1.70k
            continue;
1918
1919
65.4k
        if (!prev_is_constant || elem->kind != Constant_kind) {
1920
53.2k
            n_elements++;
1921
53.2k
        }
1922
65.4k
        prev_is_constant = elem->kind == Constant_kind;
1923
65.4k
    }
1924
1925
14.9k
    asdl_expr_seq* values = _Py_asdl_expr_seq_new(n_elements, p->arena);
1926
14.9k
    if (values == NULL) {
1927
0
        return NULL;
1928
0
    }
1929
1930
    /* build folded list */
1931
14.9k
    current_pos = 0;
1932
68.5k
    for (Py_ssize_t i = 0; i < n_flattened_elements; i++) {
1933
53.6k
        expr_ty elem = asdl_seq_GET(flattened, i);
1934
1935
        /* if the current elem and the following are constants,
1936
           fold them and all consequent constants */
1937
53.6k
        if (elem->kind == Constant_kind) {
1938
28.0k
            if (i + 1 < n_flattened_elements &&
1939
23.4k
                asdl_seq_GET(flattened, i + 1)->kind == Constant_kind) {
1940
4.31k
                expr_ty first_elem = elem;
1941
1942
                /* When a string is getting concatenated, the kind of the string
1943
                   is determined by the first string in the concatenation
1944
                   sequence.
1945
1946
                   u"abc" "def" -> u"abcdef"
1947
                   "abc" u"abc" ->  "abcabc" */
1948
4.31k
                PyObject *kind = elem->v.Constant.kind;
1949
1950
4.31k
                PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
1951
4.31k
                if (writer == NULL) {
1952
0
                    return NULL;
1953
0
                }
1954
4.31k
                expr_ty last_elem = elem;
1955
4.31k
                Py_ssize_t j;
1956
22.2k
                for (j = i; j < n_flattened_elements; j++) {
1957
20.2k
                    expr_ty current_elem = asdl_seq_GET(flattened, j);
1958
20.2k
                    if (current_elem->kind == Constant_kind) {
1959
17.8k
                        if (PyUnicodeWriter_WriteStr(writer,
1960
17.8k
                                                     current_elem->v.Constant.value)) {
1961
0
                            PyUnicodeWriter_Discard(writer);
1962
0
                            return NULL;
1963
0
                        }
1964
17.8k
                        last_elem = current_elem;
1965
17.8k
                    } else {
1966
2.34k
                        break;
1967
2.34k
                    }
1968
20.2k
                }
1969
4.31k
                i = j - 1;
1970
1971
4.31k
                PyObject *concat_str = PyUnicodeWriter_Finish(writer);
1972
4.31k
                if (concat_str == NULL) {
1973
0
                    return NULL;
1974
0
                }
1975
4.31k
                if (_PyArena_AddPyObject(p->arena, concat_str) < 0) {
1976
0
                    Py_DECREF(concat_str);
1977
0
                    return NULL;
1978
0
                }
1979
4.31k
                elem = _PyAST_Constant(concat_str, kind, first_elem->lineno,
1980
4.31k
                                       first_elem->col_offset,
1981
4.31k
                                       last_elem->end_lineno,
1982
4.31k
                                       last_elem->end_col_offset, p->arena);
1983
4.31k
                if (elem == NULL) {
1984
0
                    return NULL;
1985
0
                }
1986
4.31k
            }
1987
1988
            /* Drop all empty contanst strings */
1989
28.0k
            if (PyUnicode_CheckExact(elem->v.Constant.value) &&
1990
28.0k
                PyUnicode_GET_LENGTH(elem->v.Constant.value) == 0) {
1991
364
                continue;
1992
364
            }
1993
28.0k
        }
1994
1995
53.2k
        asdl_seq_SET(values, current_pos++, elem);
1996
53.2k
    }
1997
1998
14.9k
    assert(current_pos == n_elements);
1999
14.9k
    return values;
2000
14.9k
}
2001
2002
static expr_ty
2003
_build_concatenated_joined_str(Parser *p, asdl_expr_seq *strings,
2004
                               int lineno, int col_offset, int end_lineno,
2005
                               int end_col_offset, PyArena *arena)
2006
13.1k
{
2007
13.1k
    asdl_expr_seq *values = _build_concatenated_str(p, strings, lineno,
2008
13.1k
        col_offset, end_lineno, end_col_offset, arena);
2009
13.1k
    if (!values) {
2010
0
        return NULL;
2011
0
    }
2012
13.1k
    return _PyAST_JoinedStr(values, lineno, col_offset, end_lineno, end_col_offset, p->arena);
2013
13.1k
}
2014
2015
expr_ty
2016
_PyPegen_concatenate_tstrings(Parser *p, asdl_expr_seq *strings,
2017
                               int lineno, int col_offset, int end_lineno,
2018
                               int end_col_offset, PyArena *arena)
2019
1.79k
{
2020
1.79k
    asdl_expr_seq *values = _build_concatenated_str(p, strings, lineno,
2021
1.79k
        col_offset, end_lineno, end_col_offset, arena);
2022
1.79k
    if (!values) {
2023
0
        return NULL;
2024
0
    }
2025
1.79k
    return _PyAST_TemplateStr(values, lineno, col_offset, end_lineno,
2026
1.79k
        end_col_offset, arena);
2027
1.79k
}
2028
2029
expr_ty
2030
_PyPegen_concatenate_strings(Parser *p, asdl_expr_seq *strings,
2031
                             int lineno, int col_offset, int end_lineno,
2032
                             int end_col_offset, PyArena *arena)
2033
29.3k
{
2034
29.3k
    Py_ssize_t len = asdl_seq_LEN(strings);
2035
29.3k
    assert(len > 0);
2036
2037
29.3k
    int f_string_found = 0;
2038
29.3k
    int unicode_string_found = 0;
2039
29.3k
    int bytes_found = 0;
2040
2041
29.3k
    Py_ssize_t i = 0;
2042
96.9k
    for (i = 0; i < len; i++) {
2043
67.5k
        expr_ty elem = asdl_seq_GET(strings, i);
2044
67.5k
        switch(elem->kind) {
2045
47.7k
            case Constant_kind:
2046
47.7k
                if (PyBytes_CheckExact(elem->v.Constant.value)) {
2047
5.44k
                    bytes_found = 1;
2048
42.3k
                } else {
2049
42.3k
                    unicode_string_found = 1;
2050
42.3k
                }
2051
47.7k
                break;
2052
15.6k
            case JoinedStr_kind:
2053
15.6k
                f_string_found = 1;
2054
15.6k
                break;
2055
0
            case TemplateStr_kind:
2056
                // python.gram handles this; we should never get here
2057
0
                assert(0);
2058
0
                break;
2059
4.13k
            default:
2060
4.13k
                f_string_found = 1;
2061
4.13k
                break;
2062
67.5k
        }
2063
67.5k
    }
2064
2065
    // Cannot mix unicode and bytes
2066
29.3k
    if ((unicode_string_found || f_string_found) && bytes_found) {
2067
2
        RAISE_SYNTAX_ERROR("cannot mix bytes and nonbytes literals");
2068
2
        return NULL;
2069
2
    }
2070
2071
    // If it's only bytes or only unicode string, do a simple concat
2072
29.3k
    if (!f_string_found) {
2073
16.2k
        if (len == 1) {
2074
14.0k
            return asdl_seq_GET(strings, 0);
2075
14.0k
        }
2076
2.18k
        else if (bytes_found) {
2077
770
            return _build_concatenated_bytes(p, strings, lineno, col_offset,
2078
770
                end_lineno, end_col_offset, arena);
2079
770
        }
2080
1.41k
        else {
2081
1.41k
            return _build_concatenated_unicode(p, strings, lineno, col_offset,
2082
1.41k
                end_lineno, end_col_offset, arena);
2083
1.41k
        }
2084
16.2k
    }
2085
2086
13.1k
    return _build_concatenated_joined_str(p, strings, lineno,
2087
13.1k
        col_offset, end_lineno, end_col_offset, arena);
2088
29.3k
}
2089
2090
static int
2091
_warn_relative_import_of_lazy(Parser *p, asdl_seq *dots, expr_ty module)
2092
1.10k
{
2093
    // Warn about `from . lazy import x`: the whitespace between the dots and
2094
    // the module name is insignificant, so this is parsed exactly like
2095
    // `from .lazy import x` (an import of the relative module "lazy"), but it
2096
    // is most likely a transposition of `lazy from . import x` (PEP 810).
2097
1.10k
    if (p->call_invalid_rules) {
2098
437
        return 0;
2099
437
    }
2100
2101
    // Only fire if there is whitespace between the last dot and the name,
2102
    // i.e. not for the common `from .lazy import x` spelling.
2103
669
    Token *last_dot = asdl_seq_GET_UNTYPED(dots, asdl_seq_LEN(dots) - 1);
2104
669
    if (
2105
669
        last_dot->end_lineno == module->lineno
2106
669
        && last_dot->end_col_offset == module->col_offset
2107
669
    ) {
2108
158
        return 0;
2109
158
    }
2110
2111
511
    int count = _PyPegen_seq_count_dots(dots);
2112
511
    char *buf = PyMem_RawMalloc(count + 1);
2113
511
    if (buf == NULL) {
2114
0
        PyErr_NoMemory();
2115
0
        return -1;
2116
0
    }
2117
511
    memset(buf, '.', count);
2118
511
    buf[count] = '\0';
2119
2120
511
    PyObject *msg = PyUnicode_FromFormat(
2121
511
        "'from %s lazy import' is the same as 'from %slazy import'; "
2122
511
        "did you mean 'lazy from %s import'?",
2123
511
        buf, buf, buf);
2124
511
    PyMem_RawFree(buf);
2125
511
    if (msg == NULL) {
2126
0
        return -1;
2127
0
    }
2128
2129
511
    _PyTokenizer_Info info = _PyTokenizer_GetInfo(p->tok);
2130
511
    int res = _PyErr_EmitSyntaxWarning(msg,
2131
511
                                       info.filename,
2132
511
                                       module->lineno,
2133
511
                                       module->col_offset + 1,
2134
511
                                       module->end_lineno,
2135
511
                                       module->end_col_offset + 1,
2136
511
                                       info.module);
2137
511
    Py_DECREF(msg);
2138
511
    return res;
2139
511
}
2140
2141
stmt_ty
2142
_PyPegen_checked_from_import(Parser *p, asdl_seq *dots, expr_ty module_name,
2143
                             asdl_alias_seq *names, expr_ty lazy_token, int lineno,
2144
                             int col_offset, int end_lineno, int end_col_offset,
2145
                             PyArena *arena)
2146
4.30k
{
2147
4.30k
    identifier module = module_name->v.Name.id;
2148
4.30k
    int level = _PyPegen_seq_count_dots(dots);
2149
4.30k
    if (level == 0 && PyUnicode_CompareWithASCIIString(module, "__future__") == 0) {
2150
956
        if (lazy_token) {
2151
1
            RAISE_SYNTAX_ERROR_KNOWN_LOCATION(lazy_token,
2152
1
                "lazy from __future__ import is not allowed");
2153
1
            return NULL;
2154
1
        }
2155
2.16k
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(names); i++) {
2156
1.21k
            alias_ty alias = asdl_seq_GET(names, i);
2157
1.21k
            if (PyUnicode_CompareWithASCIIString(alias->name, "barry_as_FLUFL") == 0) {
2158
341
                p->flags |= PyPARSE_BARRY_AS_BDFL;
2159
341
                p->tok->barry_as_bdfl = 1;
2160
341
            }
2161
1.21k
        }
2162
955
    }
2163
3.34k
    else if (
2164
3.34k
        level > 0
2165
2.38k
        && lazy_token == NULL
2166
2.35k
        && PyUnicode_CompareWithASCIIString(module, "lazy") == 0
2167
3.34k
    ) {
2168
1.10k
        if (_warn_relative_import_of_lazy(p, dots, module_name) < 0) {
2169
0
            return NULL;
2170
0
        }
2171
1.10k
    }
2172
4.30k
    return _PyAST_ImportFrom(module, names, level, lazy_token ? 1 : 0, lineno,
2173
4.30k
                             col_offset, end_lineno, end_col_offset, arena);
2174
4.30k
}
2175
2176
asdl_stmt_seq*
2177
28.7k
_PyPegen_register_stmts(Parser *p, asdl_stmt_seq* stmts) {
2178
28.7k
    if (!p->call_invalid_rules) {
2179
19.8k
        return stmts;
2180
19.8k
    }
2181
8.87k
    Py_ssize_t len = asdl_seq_LEN(stmts);
2182
8.87k
    if (len == 0) {
2183
0
        return stmts;
2184
0
    }
2185
8.87k
    stmt_ty last_stmt = asdl_seq_GET(stmts, len - 1);
2186
8.87k
    if (p->last_stmt_location.lineno > last_stmt->lineno) {
2187
222
        return stmts;
2188
222
    }
2189
8.65k
    p->last_stmt_location.lineno = last_stmt->lineno;
2190
8.65k
    p->last_stmt_location.col_offset = last_stmt->col_offset;
2191
8.65k
    p->last_stmt_location.end_lineno = last_stmt->end_lineno;
2192
8.65k
    p->last_stmt_location.end_col_offset = last_stmt->end_col_offset;
2193
8.65k
    return stmts;
2194
8.87k
}