Coverage Report

Created: 2026-01-17 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/ast_preprocess.c
Line
Count
Source
1
/* AST pre-processing */
2
#include "Python.h"
3
#include "pycore_ast.h"           // _PyAST_GetDocString()
4
#include "pycore_c_array.h"       // _Py_CArray_EnsureCapacity()
5
#include "pycore_format.h"        // F_LJUST
6
#include "pycore_runtime.h"       // _Py_STR()
7
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString()
8
9
10
/* See PEP 765 */
11
typedef struct {
12
    bool in_finally;
13
    bool in_funcdef;
14
    bool in_loop;
15
} ControlFlowInFinallyContext;
16
17
typedef struct {
18
    PyObject *filename;
19
    PyObject *module;
20
    int optimize;
21
    int ff_features;
22
    int syntax_check_only;
23
    int enable_warnings;
24
25
    _Py_c_array_t cf_finally;       /* context for PEP 765 check */
26
    int cf_finally_used;
27
} _PyASTPreprocessState;
28
29
606k
#define ENTER_RECURSIVE() \
30
606k
if (Py_EnterRecursiveCall(" during compilation")) { \
31
0
    return 0; \
32
0
}
33
34
606k
#define LEAVE_RECURSIVE() Py_LeaveRecursiveCall();
35
36
static ControlFlowInFinallyContext*
37
get_cf_finally_top(_PyASTPreprocessState *state)
38
19.4k
{
39
19.4k
    int idx = state->cf_finally_used;
40
19.4k
    return ((ControlFlowInFinallyContext*)state->cf_finally.array) + idx;
41
19.4k
}
42
43
static int
44
push_cf_context(_PyASTPreprocessState *state, stmt_ty node, bool finally, bool funcdef, bool loop)
45
12.0k
{
46
12.0k
    if (_Py_CArray_EnsureCapacity(&state->cf_finally, state->cf_finally_used+1) < 0) {
47
0
        return 0;
48
0
    }
49
50
12.0k
    state->cf_finally_used++;
51
12.0k
    ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
52
53
12.0k
    ctx->in_finally = finally;
54
12.0k
    ctx->in_funcdef = funcdef;
55
12.0k
    ctx->in_loop = loop;
56
12.0k
    return 1;
57
12.0k
}
58
59
static void
60
pop_cf_context(_PyASTPreprocessState *state)
61
12.0k
{
62
12.0k
    assert(state->cf_finally_used > 0);
63
12.0k
    state->cf_finally_used--;
64
12.0k
}
65
66
static int
67
control_flow_in_finally_warning(const char *kw, stmt_ty n, _PyASTPreprocessState *state)
68
0
{
69
0
    PyObject *msg = PyUnicode_FromFormat("'%s' in a 'finally' block", kw);
70
0
    if (msg == NULL) {
71
0
        return 0;
72
0
    }
73
0
    int ret = _PyErr_EmitSyntaxWarning(msg, state->filename, n->lineno,
74
0
                                       n->col_offset + 1, n->end_lineno,
75
0
                                       n->end_col_offset + 1,
76
0
                                       state->module);
77
0
    Py_DECREF(msg);
78
0
    return ret < 0 ? 0 : 1;
79
0
}
80
81
static int
82
before_return(_PyASTPreprocessState *state, stmt_ty node_)
83
7.18k
{
84
7.18k
    if (state->enable_warnings && state->cf_finally_used > 0) {
85
6.60k
        ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
86
6.60k
        if (ctx->in_finally && ! ctx->in_funcdef) {
87
0
            if (!control_flow_in_finally_warning("return", node_, state)) {
88
0
                return 0;
89
0
            }
90
0
        }
91
6.60k
    }
92
7.18k
    return 1;
93
7.18k
}
94
95
static int
96
before_loop_exit(_PyASTPreprocessState *state, stmt_ty node_, const char *kw)
97
1.57k
{
98
1.57k
    if (state->enable_warnings && state->cf_finally_used > 0) {
99
766
        ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
100
766
        if (ctx->in_finally && ! ctx->in_loop) {
101
0
            if (!control_flow_in_finally_warning(kw, node_, state)) {
102
0
                return 0;
103
0
            }
104
0
        }
105
766
    }
106
1.57k
    return 1;
107
1.57k
}
108
109
#define PUSH_CONTEXT(S, N, FINALLY, FUNCDEF, LOOP) \
110
12.0k
    if (!push_cf_context((S), (N), (FINALLY), (FUNCDEF), (LOOP))) { \
111
0
        return 0; \
112
0
    }
113
114
12.0k
#define POP_CONTEXT(S) pop_cf_context(S)
115
116
1.86k
#define BEFORE_FINALLY(S, N)    PUSH_CONTEXT((S), (N), true, false, false)
117
1.86k
#define AFTER_FINALLY(S)        POP_CONTEXT(S)
118
7.89k
#define BEFORE_FUNC_BODY(S, N)  PUSH_CONTEXT((S), (N), false, true, false)
119
7.89k
#define AFTER_FUNC_BODY(S)      POP_CONTEXT(S)
120
2.34k
#define BEFORE_LOOP_BODY(S, N)  PUSH_CONTEXT((S), (N), false, false, true)
121
2.34k
#define AFTER_LOOP_BODY(S)      POP_CONTEXT(S)
122
123
#define BEFORE_RETURN(S, N) \
124
7.18k
    if (!before_return((S), (N))) { \
125
0
        return 0; \
126
0
    }
127
128
#define BEFORE_LOOP_EXIT(S, N, KW) \
129
1.57k
    if (!before_loop_exit((S), (N), (KW))) { \
130
0
        return 0; \
131
0
    }
132
133
static int
134
make_const(expr_ty node, PyObject *val, PyArena *arena)
135
0
{
136
    // Even if no new value was calculated, make_const may still
137
    // need to clear an error (e.g. for division by zero)
138
0
    if (val == NULL) {
139
0
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) {
140
0
            return 0;
141
0
        }
142
0
        PyErr_Clear();
143
0
        return 1;
144
0
    }
145
0
    if (_PyArena_AddPyObject(arena, val) < 0) {
146
0
        Py_DECREF(val);
147
0
        return 0;
148
0
    }
149
0
    node->kind = Constant_kind;
150
0
    node->v.Constant.kind = NULL;
151
0
    node->v.Constant.value = val;
152
0
    return 1;
153
0
}
154
155
491
#define COPY_NODE(TO, FROM) (memcpy((TO), (FROM), sizeof(struct _expr)))
156
157
static int
158
has_starred(asdl_expr_seq *elts)
159
608
{
160
608
    Py_ssize_t n = asdl_seq_LEN(elts);
161
1.86k
    for (Py_ssize_t i = 0; i < n; i++) {
162
1.25k
        expr_ty e = (expr_ty)asdl_seq_GET(elts, i);
163
1.25k
        if (e->kind == Starred_kind) {
164
0
            return 1;
165
0
        }
166
1.25k
    }
167
608
    return 0;
168
608
}
169
170
static expr_ty
171
parse_literal(PyObject *fmt, Py_ssize_t *ppos, PyArena *arena)
172
1.62k
{
173
1.62k
    const void *data = PyUnicode_DATA(fmt);
174
1.62k
    int kind = PyUnicode_KIND(fmt);
175
1.62k
    Py_ssize_t size = PyUnicode_GET_LENGTH(fmt);
176
1.62k
    Py_ssize_t start, pos;
177
1.62k
    int has_percents = 0;
178
1.62k
    start = pos = *ppos;
179
11.9k
    while (pos < size) {
180
11.4k
        if (PyUnicode_READ(kind, data, pos) != '%') {
181
10.2k
            pos++;
182
10.2k
        }
183
1.13k
        else if (pos+1 < size && PyUnicode_READ(kind, data, pos+1) == '%') {
184
4
            has_percents = 1;
185
4
            pos += 2;
186
4
        }
187
1.13k
        else {
188
1.13k
            break;
189
1.13k
        }
190
11.4k
    }
191
1.62k
    *ppos = pos;
192
1.62k
    if (pos == start) {
193
671
        return NULL;
194
671
    }
195
953
    PyObject *str = PyUnicode_Substring(fmt, start, pos);
196
    /* str = str.replace('%%', '%') */
197
953
    if (str && has_percents) {
198
3
        _Py_DECLARE_STR(dbl_percent, "%%");
199
3
        Py_SETREF(str, PyUnicode_Replace(str, &_Py_STR(dbl_percent),
200
3
                                         _Py_LATIN1_CHR('%'), -1));
201
3
    }
202
953
    if (!str) {
203
0
        return NULL;
204
0
    }
205
206
953
    if (_PyArena_AddPyObject(arena, str) < 0) {
207
0
        Py_DECREF(str);
208
0
        return NULL;
209
0
    }
210
953
    return _PyAST_Constant(str, NULL, -1, -1, -1, -1, arena);
211
953
}
212
213
61
#define MAXDIGITS 3
214
215
static int
216
simple_format_arg_parse(PyObject *fmt, Py_ssize_t *ppos,
217
                        int *spec, int *flags, int *width, int *prec)
218
1.13k
{
219
1.13k
    Py_ssize_t pos = *ppos, len = PyUnicode_GET_LENGTH(fmt);
220
1.13k
    Py_UCS4 ch;
221
222
1.24k
#define NEXTC do {                      \
223
1.24k
    if (pos >= len) {                   \
224
0
        return 0;                       \
225
0
    }                                   \
226
1.24k
    ch = PyUnicode_READ_CHAR(fmt, pos); \
227
1.24k
    pos++;                              \
228
1.24k
} while (0)
229
230
1.13k
    *flags = 0;
231
1.19k
    while (1) {
232
1.19k
        NEXTC;
233
1.19k
        switch (ch) {
234
9
            case '-': *flags |= F_LJUST; continue;
235
0
            case '+': *flags |= F_SIGN; continue;
236
0
            case ' ': *flags |= F_BLANK; continue;
237
25
            case '#': *flags |= F_ALT; continue;
238
23
            case '0': *flags |= F_ZERO; continue;
239
1.19k
        }
240
1.13k
        break;
241
1.19k
    }
242
1.13k
    if ('0' <= ch && ch <= '9') {
243
31
        *width = 0;
244
31
        int digits = 0;
245
76
        while ('0' <= ch && ch <= '9') {
246
47
            *width = *width * 10 + (ch - '0');
247
47
            NEXTC;
248
47
            if (++digits >= MAXDIGITS) {
249
2
                return 0;
250
2
            }
251
47
        }
252
31
    }
253
254
1.13k
    if (ch == '.') {
255
1
        NEXTC;
256
1
        *prec = 0;
257
1
        if ('0' <= ch && ch <= '9') {
258
1
            int digits = 0;
259
3
            while ('0' <= ch && ch <= '9') {
260
2
                *prec = *prec * 10 + (ch - '0');
261
2
                NEXTC;
262
2
                if (++digits >= MAXDIGITS) {
263
0
                    return 0;
264
0
                }
265
2
            }
266
1
        }
267
1
    }
268
1.13k
    *spec = ch;
269
1.13k
    *ppos = pos;
270
1.13k
    return 1;
271
272
1.13k
#undef NEXTC
273
1.13k
}
274
275
static expr_ty
276
parse_format(PyObject *fmt, Py_ssize_t *ppos, expr_ty arg, PyArena *arena)
277
1.13k
{
278
1.13k
    int spec, flags, width = -1, prec = -1;
279
1.13k
    if (!simple_format_arg_parse(fmt, ppos, &spec, &flags, &width, &prec)) {
280
        // Unsupported format.
281
2
        return NULL;
282
2
    }
283
1.13k
    if (spec == 's' || spec == 'r' || spec == 'a') {
284
1.01k
        char buf[1 + MAXDIGITS + 1 + MAXDIGITS + 1], *p = buf;
285
1.01k
        if (!(flags & F_LJUST) && width > 0) {
286
2
            *p++ = '>';
287
2
        }
288
1.01k
        if (width >= 0) {
289
11
            p += snprintf(p, MAXDIGITS + 1, "%d", width);
290
11
        }
291
1.01k
        if (prec >= 0) {
292
1
            p += snprintf(p, MAXDIGITS + 2, ".%d", prec);
293
1
        }
294
1.01k
        expr_ty format_spec = NULL;
295
1.01k
        if (p != buf) {
296
12
            PyObject *str = PyUnicode_FromString(buf);
297
12
            if (str == NULL) {
298
0
                return NULL;
299
0
            }
300
12
            if (_PyArena_AddPyObject(arena, str) < 0) {
301
0
                Py_DECREF(str);
302
0
                return NULL;
303
0
            }
304
12
            format_spec = _PyAST_Constant(str, NULL, -1, -1, -1, -1, arena);
305
12
            if (format_spec == NULL) {
306
0
                return NULL;
307
0
            }
308
12
        }
309
1.01k
        return _PyAST_FormattedValue(arg, spec, format_spec,
310
1.01k
                                     arg->lineno, arg->col_offset,
311
1.01k
                                     arg->end_lineno, arg->end_col_offset,
312
1.01k
                                     arena);
313
1.01k
    }
314
    // Unsupported format.
315
115
    return NULL;
316
1.13k
}
317
318
static int
319
optimize_format(expr_ty node, PyObject *fmt, asdl_expr_seq *elts, PyArena *arena)
320
608
{
321
608
    Py_ssize_t pos = 0;
322
608
    Py_ssize_t cnt = 0;
323
608
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(asdl_seq_LEN(elts) * 2 + 1, arena);
324
608
    if (!seq) {
325
0
        return 0;
326
0
    }
327
608
    seq->size = 0;
328
329
1.62k
    while (1) {
330
1.62k
        expr_ty lit = parse_literal(fmt, &pos, arena);
331
1.62k
        if (lit) {
332
953
            asdl_seq_SET(seq, seq->size++, lit);
333
953
        }
334
671
        else if (PyErr_Occurred()) {
335
0
            return 0;
336
0
        }
337
338
1.62k
        if (pos >= PyUnicode_GET_LENGTH(fmt)) {
339
491
            break;
340
491
        }
341
1.13k
        if (cnt >= asdl_seq_LEN(elts)) {
342
            // More format units than items.
343
0
            return 1;
344
0
        }
345
1.13k
        assert(PyUnicode_READ_CHAR(fmt, pos) == '%');
346
1.13k
        pos++;
347
1.13k
        expr_ty expr = parse_format(fmt, &pos, asdl_seq_GET(elts, cnt), arena);
348
1.13k
        cnt++;
349
1.13k
        if (!expr) {
350
117
            return !PyErr_Occurred();
351
117
        }
352
1.01k
        asdl_seq_SET(seq, seq->size++, expr);
353
1.01k
    }
354
491
    if (cnt < asdl_seq_LEN(elts)) {
355
        // More items than format units.
356
0
        return 1;
357
0
    }
358
491
    expr_ty res = _PyAST_JoinedStr(seq,
359
491
                                   node->lineno, node->col_offset,
360
491
                                   node->end_lineno, node->end_col_offset,
361
491
                                   arena);
362
491
    if (!res) {
363
0
        return 0;
364
0
    }
365
491
    COPY_NODE(node, res);
366
//     PySys_FormatStderr("format = %R\n", fmt);
367
491
    return 1;
368
491
}
369
370
static int
371
fold_binop(expr_ty node, PyArena *arena, _PyASTPreprocessState *state)
372
26.7k
{
373
26.7k
    if (state->syntax_check_only) {
374
21.1k
        return 1;
375
21.1k
    }
376
5.55k
    expr_ty lhs, rhs;
377
5.55k
    lhs = node->v.BinOp.left;
378
5.55k
    rhs = node->v.BinOp.right;
379
5.55k
    if (lhs->kind != Constant_kind) {
380
3.84k
        return 1;
381
3.84k
    }
382
1.70k
    PyObject *lv = lhs->v.Constant.value;
383
384
1.70k
    if (node->v.BinOp.op == Mod &&
385
1.17k
        rhs->kind == Tuple_kind &&
386
1.70k
        PyUnicode_Check(lv) &&
387
608
        !has_starred(rhs->v.Tuple.elts))
388
608
    {
389
608
        return optimize_format(node, lv, rhs->v.Tuple.elts, arena);
390
608
    }
391
392
1.09k
    return 1;
393
1.70k
}
394
395
static int astfold_mod(mod_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
396
static int astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
397
static int astfold_expr(expr_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
398
static int astfold_arguments(arguments_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
399
static int astfold_comprehension(comprehension_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
400
static int astfold_keyword(keyword_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
401
static int astfold_arg(arg_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
402
static int astfold_withitem(withitem_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
403
static int astfold_excepthandler(excepthandler_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
404
static int astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
405
static int astfold_pattern(pattern_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
406
static int astfold_type_param(type_param_ty node_, PyArena *ctx_, _PyASTPreprocessState *state);
407
408
#define CALL(FUNC, TYPE, ARG) \
409
350k
    if (!FUNC((ARG), ctx_, state)) \
410
350k
        return 0;
411
412
#define CALL_OPT(FUNC, TYPE, ARG) \
413
103k
    if ((ARG) != NULL && !FUNC((ARG), ctx_, state)) \
414
103k
        return 0;
415
416
254k
#define CALL_SEQ(FUNC, TYPE, ARG) { \
417
254k
    Py_ssize_t i; \
418
254k
    asdl_ ## TYPE ## _seq *seq = (ARG); /* avoid variable capture */ \
419
584k
    for (i = 0; i < asdl_seq_LEN(seq); i++) { \
420
330k
        TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
421
330k
        if (elt != NULL && !FUNC(elt, ctx_, state)) \
422
330k
            return 0; \
423
330k
    } \
424
254k
}
425
426
427
static int
428
stmt_seq_remove_item(asdl_stmt_seq *stmts, Py_ssize_t idx)
429
0
{
430
0
    if (idx >= asdl_seq_LEN(stmts)) {
431
0
        return 0;
432
0
    }
433
0
    for (Py_ssize_t i = idx; i < asdl_seq_LEN(stmts) - 1; i++) {
434
0
        stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, i+1);
435
0
        asdl_seq_SET(stmts, i, st);
436
0
    }
437
0
    stmts->size--;
438
0
    return 1;
439
0
}
440
441
static int
442
remove_docstring(asdl_stmt_seq *stmts, Py_ssize_t idx, PyArena *ctx_)
443
0
{
444
0
    assert(_PyAST_GetDocString(stmts) != NULL);
445
    // In case there's just the docstring in the body, replace it with `pass`
446
    // keyword, so body won't be empty.
447
0
    if (asdl_seq_LEN(stmts) == 1) {
448
0
        stmt_ty docstring = (stmt_ty)asdl_seq_GET(stmts, 0);
449
0
        stmt_ty pass = _PyAST_Pass(
450
0
            docstring->lineno, docstring->col_offset,
451
            // we know that `pass` always takes 4 chars and a single line,
452
            // while docstring can span on multiple lines
453
0
            docstring->lineno, docstring->col_offset + 4,
454
0
            ctx_
455
0
        );
456
0
        if (pass == NULL) {
457
0
            return 0;
458
0
        }
459
0
        asdl_seq_SET(stmts, 0, pass);
460
0
        return 1;
461
0
    }
462
    // In case there are more than 1 body items, just remove the docstring.
463
0
    return stmt_seq_remove_item(stmts, idx);
464
0
}
465
466
static int
467
astfold_body(asdl_stmt_seq *stmts, PyArena *ctx_, _PyASTPreprocessState *state)
468
15.9k
{
469
15.9k
    int docstring = _PyAST_GetDocString(stmts) != NULL;
470
15.9k
    if (docstring && (state->optimize >= 2)) {
471
        /* remove the docstring */
472
0
        if (!remove_docstring(stmts, 0, ctx_)) {
473
0
            return 0;
474
0
        }
475
0
        docstring = 0;
476
0
    }
477
15.9k
    CALL_SEQ(astfold_stmt, stmt, stmts);
478
15.9k
    if (!docstring && _PyAST_GetDocString(stmts) != NULL) {
479
0
        stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
480
0
        asdl_expr_seq *values = _Py_asdl_expr_seq_new(1, ctx_);
481
0
        if (!values) {
482
0
            return 0;
483
0
        }
484
0
        asdl_seq_SET(values, 0, st->v.Expr.value);
485
0
        expr_ty expr = _PyAST_JoinedStr(values, st->lineno, st->col_offset,
486
0
                                        st->end_lineno, st->end_col_offset,
487
0
                                        ctx_);
488
0
        if (!expr) {
489
0
            return 0;
490
0
        }
491
0
        st->v.Expr.value = expr;
492
0
    }
493
15.9k
    return 1;
494
15.9k
}
495
496
static int
497
astfold_mod(mod_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
498
6.38k
{
499
6.38k
    switch (node_->kind) {
500
6.30k
    case Module_kind:
501
6.30k
        CALL(astfold_body, asdl_seq, node_->v.Module.body);
502
6.30k
        break;
503
0
    case Interactive_kind:
504
0
        CALL_SEQ(astfold_stmt, stmt, node_->v.Interactive.body);
505
0
        break;
506
86
    case Expression_kind:
507
86
        CALL(astfold_expr, expr_ty, node_->v.Expression.body);
508
86
        break;
509
    // The following top level nodes don't participate in constant folding
510
0
    case FunctionType_kind:
511
0
        break;
512
    // No default case, so the compiler will emit a warning if new top level
513
    // compilation nodes are added without being handled here
514
6.38k
    }
515
6.38k
    return 1;
516
6.38k
}
517
518
static int
519
astfold_expr(expr_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
520
490k
{
521
490k
    ENTER_RECURSIVE();
522
490k
    switch (node_->kind) {
523
2.76k
    case BoolOp_kind:
524
2.76k
        CALL_SEQ(astfold_expr, expr, node_->v.BoolOp.values);
525
2.76k
        break;
526
26.7k
    case BinOp_kind:
527
26.7k
        CALL(astfold_expr, expr_ty, node_->v.BinOp.left);
528
26.7k
        CALL(astfold_expr, expr_ty, node_->v.BinOp.right);
529
26.7k
        CALL(fold_binop, expr_ty, node_);
530
26.7k
        break;
531
48.9k
    case UnaryOp_kind:
532
48.9k
        CALL(astfold_expr, expr_ty, node_->v.UnaryOp.operand);
533
48.9k
        break;
534
1.26k
    case Lambda_kind:
535
1.26k
        CALL(astfold_arguments, arguments_ty, node_->v.Lambda.args);
536
1.26k
        CALL(astfold_expr, expr_ty, node_->v.Lambda.body);
537
1.26k
        break;
538
501
    case IfExp_kind:
539
501
        CALL(astfold_expr, expr_ty, node_->v.IfExp.test);
540
501
        CALL(astfold_expr, expr_ty, node_->v.IfExp.body);
541
501
        CALL(astfold_expr, expr_ty, node_->v.IfExp.orelse);
542
501
        break;
543
2.04k
    case Dict_kind:
544
2.04k
        CALL_SEQ(astfold_expr, expr, node_->v.Dict.keys);
545
2.04k
        CALL_SEQ(astfold_expr, expr, node_->v.Dict.values);
546
2.04k
        break;
547
696
    case Set_kind:
548
696
        CALL_SEQ(astfold_expr, expr, node_->v.Set.elts);
549
696
        break;
550
604
    case ListComp_kind:
551
604
        CALL(astfold_expr, expr_ty, node_->v.ListComp.elt);
552
604
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.ListComp.generators);
553
604
        break;
554
172
    case SetComp_kind:
555
172
        CALL(astfold_expr, expr_ty, node_->v.SetComp.elt);
556
172
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.SetComp.generators);
557
172
        break;
558
422
    case DictComp_kind:
559
422
        CALL(astfold_expr, expr_ty, node_->v.DictComp.key);
560
422
        CALL(astfold_expr, expr_ty, node_->v.DictComp.value);
561
422
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.DictComp.generators);
562
422
        break;
563
627
    case GeneratorExp_kind:
564
627
        CALL(astfold_expr, expr_ty, node_->v.GeneratorExp.elt);
565
627
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.GeneratorExp.generators);
566
627
        break;
567
102
    case Await_kind:
568
102
        CALL(astfold_expr, expr_ty, node_->v.Await.value);
569
102
        break;
570
839
    case Yield_kind:
571
839
        CALL_OPT(astfold_expr, expr_ty, node_->v.Yield.value);
572
839
        break;
573
128
    case YieldFrom_kind:
574
128
        CALL(astfold_expr, expr_ty, node_->v.YieldFrom.value);
575
128
        break;
576
10.0k
    case Compare_kind:
577
10.0k
        CALL(astfold_expr, expr_ty, node_->v.Compare.left);
578
10.0k
        CALL_SEQ(astfold_expr, expr, node_->v.Compare.comparators);
579
10.0k
        break;
580
31.0k
    case Call_kind:
581
31.0k
        CALL(astfold_expr, expr_ty, node_->v.Call.func);
582
31.0k
        CALL_SEQ(astfold_expr, expr, node_->v.Call.args);
583
31.0k
        CALL_SEQ(astfold_keyword, keyword, node_->v.Call.keywords);
584
31.0k
        break;
585
12.5k
    case FormattedValue_kind:
586
12.5k
        CALL(astfold_expr, expr_ty, node_->v.FormattedValue.value);
587
12.5k
        CALL_OPT(astfold_expr, expr_ty, node_->v.FormattedValue.format_spec);
588
12.5k
        break;
589
1.82k
    case Interpolation_kind:
590
1.82k
        CALL(astfold_expr, expr_ty, node_->v.Interpolation.value);
591
1.82k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Interpolation.format_spec);
592
1.82k
        break;
593
6.94k
    case JoinedStr_kind:
594
6.94k
        CALL_SEQ(astfold_expr, expr, node_->v.JoinedStr.values);
595
6.94k
        break;
596
323
    case TemplateStr_kind:
597
323
        CALL_SEQ(astfold_expr, expr, node_->v.TemplateStr.values);
598
323
        break;
599
31.6k
    case Attribute_kind:
600
31.6k
        CALL(astfold_expr, expr_ty, node_->v.Attribute.value);
601
31.6k
        break;
602
5.70k
    case Subscript_kind:
603
5.70k
        CALL(astfold_expr, expr_ty, node_->v.Subscript.value);
604
5.70k
        CALL(astfold_expr, expr_ty, node_->v.Subscript.slice);
605
5.70k
        break;
606
817
    case Starred_kind:
607
817
        CALL(astfold_expr, expr_ty, node_->v.Starred.value);
608
817
        break;
609
3.24k
    case Slice_kind:
610
3.24k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.lower);
611
3.24k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.upper);
612
3.24k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.step);
613
3.24k
        break;
614
2.61k
    case List_kind:
615
2.61k
        CALL_SEQ(astfold_expr, expr, node_->v.List.elts);
616
2.61k
        break;
617
11.2k
    case Tuple_kind:
618
11.2k
        CALL_SEQ(astfold_expr, expr, node_->v.Tuple.elts);
619
11.2k
        break;
620
172k
    case Name_kind:
621
172k
        if (state->syntax_check_only) {
622
58.7k
            break;
623
58.7k
        }
624
113k
        if (node_->v.Name.ctx == Load &&
625
93.8k
                _PyUnicode_EqualToASCIIString(node_->v.Name.id, "__debug__")) {
626
0
            LEAVE_RECURSIVE();
627
0
            return make_const(node_, PyBool_FromLong(!state->optimize), ctx_);
628
0
        }
629
113k
        break;
630
113k
    case NamedExpr_kind:
631
74
        CALL(astfold_expr, expr_ty, node_->v.NamedExpr.value);
632
74
        break;
633
114k
    case Constant_kind:
634
        // Already a constant, nothing further to do
635
114k
        break;
636
    // No default case, so the compiler will emit a warning if new expression
637
    // kinds are added without being handled here
638
490k
    }
639
490k
    LEAVE_RECURSIVE();
640
490k
    return 1;
641
490k
}
642
643
static int
644
astfold_keyword(keyword_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
645
5.84k
{
646
5.84k
    CALL(astfold_expr, expr_ty, node_->value);
647
5.84k
    return 1;
648
5.84k
}
649
650
static int
651
astfold_comprehension(comprehension_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
652
1.92k
{
653
1.92k
    CALL(astfold_expr, expr_ty, node_->target);
654
1.92k
    CALL(astfold_expr, expr_ty, node_->iter);
655
1.92k
    CALL_SEQ(astfold_expr, expr, node_->ifs);
656
1.92k
    return 1;
657
1.92k
}
658
659
static int
660
astfold_arguments(arguments_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
661
9.15k
{
662
9.15k
    CALL_SEQ(astfold_arg, arg, node_->posonlyargs);
663
9.15k
    CALL_SEQ(astfold_arg, arg, node_->args);
664
9.15k
    CALL_OPT(astfold_arg, arg_ty, node_->vararg);
665
9.15k
    CALL_SEQ(astfold_arg, arg, node_->kwonlyargs);
666
9.15k
    CALL_SEQ(astfold_expr, expr, node_->kw_defaults);
667
9.15k
    CALL_OPT(astfold_arg, arg_ty, node_->kwarg);
668
9.15k
    CALL_SEQ(astfold_expr, expr, node_->defaults);
669
9.15k
    return 1;
670
9.15k
}
671
672
static int
673
astfold_arg(arg_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
674
22.4k
{
675
22.4k
    if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
676
21.3k
        CALL_OPT(astfold_expr, expr_ty, node_->annotation);
677
21.3k
    }
678
22.4k
    return 1;
679
22.4k
}
680
681
static int
682
astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
683
101k
{
684
101k
    ENTER_RECURSIVE();
685
101k
    switch (node_->kind) {
686
7.73k
    case FunctionDef_kind: {
687
7.73k
        CALL_SEQ(astfold_type_param, type_param, node_->v.FunctionDef.type_params);
688
7.73k
        CALL(astfold_arguments, arguments_ty, node_->v.FunctionDef.args);
689
7.73k
        BEFORE_FUNC_BODY(state, node_);
690
7.73k
        CALL(astfold_body, asdl_seq, node_->v.FunctionDef.body);
691
7.73k
        AFTER_FUNC_BODY(state);
692
7.73k
        CALL_SEQ(astfold_expr, expr, node_->v.FunctionDef.decorator_list);
693
7.73k
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
694
7.27k
            CALL_OPT(astfold_expr, expr_ty, node_->v.FunctionDef.returns);
695
7.27k
        }
696
7.73k
        break;
697
7.73k
    }
698
7.73k
    case AsyncFunctionDef_kind: {
699
153
        CALL_SEQ(astfold_type_param, type_param, node_->v.AsyncFunctionDef.type_params);
700
153
        CALL(astfold_arguments, arguments_ty, node_->v.AsyncFunctionDef.args);
701
153
        BEFORE_FUNC_BODY(state, node_);
702
153
        CALL(astfold_body, asdl_seq, node_->v.AsyncFunctionDef.body);
703
153
        AFTER_FUNC_BODY(state);
704
153
        CALL_SEQ(astfold_expr, expr, node_->v.AsyncFunctionDef.decorator_list);
705
153
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
706
138
            CALL_OPT(astfold_expr, expr_ty, node_->v.AsyncFunctionDef.returns);
707
138
        }
708
153
        break;
709
153
    }
710
1.78k
    case ClassDef_kind:
711
1.78k
        CALL_SEQ(astfold_type_param, type_param, node_->v.ClassDef.type_params);
712
1.78k
        CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.bases);
713
1.78k
        CALL_SEQ(astfold_keyword, keyword, node_->v.ClassDef.keywords);
714
1.78k
        CALL(astfold_body, asdl_seq, node_->v.ClassDef.body);
715
1.78k
        CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.decorator_list);
716
1.78k
        break;
717
7.18k
    case Return_kind:
718
7.18k
        BEFORE_RETURN(state, node_);
719
7.18k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Return.value);
720
7.18k
        break;
721
636
    case Delete_kind:
722
636
        CALL_SEQ(astfold_expr, expr, node_->v.Delete.targets);
723
636
        break;
724
18.9k
    case Assign_kind:
725
18.9k
        CALL_SEQ(astfold_expr, expr, node_->v.Assign.targets);
726
18.9k
        CALL(astfold_expr, expr_ty, node_->v.Assign.value);
727
18.9k
        break;
728
1.32k
    case AugAssign_kind:
729
1.32k
        CALL(astfold_expr, expr_ty, node_->v.AugAssign.target);
730
1.32k
        CALL(astfold_expr, expr_ty, node_->v.AugAssign.value);
731
1.32k
        break;
732
1.21k
    case AnnAssign_kind:
733
1.21k
        CALL(astfold_expr, expr_ty, node_->v.AnnAssign.target);
734
1.21k
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
735
885
            CALL(astfold_expr, expr_ty, node_->v.AnnAssign.annotation);
736
885
        }
737
1.21k
        CALL_OPT(astfold_expr, expr_ty, node_->v.AnnAssign.value);
738
1.21k
        break;
739
79
    case TypeAlias_kind:
740
79
        CALL(astfold_expr, expr_ty, node_->v.TypeAlias.name);
741
79
        CALL_SEQ(astfold_type_param, type_param, node_->v.TypeAlias.type_params);
742
79
        CALL(astfold_expr, expr_ty, node_->v.TypeAlias.value);
743
79
        break;
744
1.59k
    case For_kind: {
745
1.59k
        CALL(astfold_expr, expr_ty, node_->v.For.target);
746
1.59k
        CALL(astfold_expr, expr_ty, node_->v.For.iter);
747
1.59k
        BEFORE_LOOP_BODY(state, node_);
748
1.59k
        CALL_SEQ(astfold_stmt, stmt, node_->v.For.body);
749
1.59k
        AFTER_LOOP_BODY(state);
750
1.59k
        CALL_SEQ(astfold_stmt, stmt, node_->v.For.orelse);
751
1.59k
        break;
752
1.59k
    }
753
71
    case AsyncFor_kind: {
754
71
        CALL(astfold_expr, expr_ty, node_->v.AsyncFor.target);
755
71
        CALL(astfold_expr, expr_ty, node_->v.AsyncFor.iter);
756
71
        BEFORE_LOOP_BODY(state, node_);
757
71
        CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncFor.body);
758
71
        AFTER_LOOP_BODY(state);
759
71
        CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncFor.orelse);
760
71
        break;
761
71
    }
762
681
    case While_kind: {
763
681
        CALL(astfold_expr, expr_ty, node_->v.While.test);
764
681
        BEFORE_LOOP_BODY(state, node_);
765
681
        CALL_SEQ(astfold_stmt, stmt, node_->v.While.body);
766
681
        AFTER_LOOP_BODY(state);
767
681
        CALL_SEQ(astfold_stmt, stmt, node_->v.While.orelse);
768
681
        break;
769
681
    }
770
11.1k
    case If_kind:
771
11.1k
        CALL(astfold_expr, expr_ty, node_->v.If.test);
772
11.1k
        CALL_SEQ(astfold_stmt, stmt, node_->v.If.body);
773
11.1k
        CALL_SEQ(astfold_stmt, stmt, node_->v.If.orelse);
774
11.1k
        break;
775
365
    case With_kind:
776
365
        CALL_SEQ(astfold_withitem, withitem, node_->v.With.items);
777
365
        CALL_SEQ(astfold_stmt, stmt, node_->v.With.body);
778
365
        break;
779
230
    case AsyncWith_kind:
780
230
        CALL_SEQ(astfold_withitem, withitem, node_->v.AsyncWith.items);
781
230
        CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncWith.body);
782
230
        break;
783
3.07k
    case Raise_kind:
784
3.07k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Raise.exc);
785
3.07k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Raise.cause);
786
3.07k
        break;
787
1.53k
    case Try_kind: {
788
1.53k
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.body);
789
1.53k
        CALL_SEQ(astfold_excepthandler, excepthandler, node_->v.Try.handlers);
790
1.53k
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.orelse);
791
1.53k
        BEFORE_FINALLY(state, node_);
792
1.53k
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.finalbody);
793
1.53k
        AFTER_FINALLY(state);
794
1.53k
        break;
795
1.53k
    }
796
325
    case TryStar_kind: {
797
325
        CALL_SEQ(astfold_stmt, stmt, node_->v.TryStar.body);
798
325
        CALL_SEQ(astfold_excepthandler, excepthandler, node_->v.TryStar.handlers);
799
325
        CALL_SEQ(astfold_stmt, stmt, node_->v.TryStar.orelse);
800
325
        BEFORE_FINALLY(state, node_);
801
325
        CALL_SEQ(astfold_stmt, stmt, node_->v.TryStar.finalbody);
802
325
        AFTER_FINALLY(state);
803
325
        break;
804
325
    }
805
487
    case Assert_kind:
806
487
        CALL(astfold_expr, expr_ty, node_->v.Assert.test);
807
487
        CALL_OPT(astfold_expr, expr_ty, node_->v.Assert.msg);
808
487
        break;
809
37.6k
    case Expr_kind:
810
37.6k
        CALL(astfold_expr, expr_ty, node_->v.Expr.value);
811
37.6k
        break;
812
263
    case Match_kind:
813
263
        CALL(astfold_expr, expr_ty, node_->v.Match.subject);
814
263
        CALL_SEQ(astfold_match_case, match_case, node_->v.Match.cases);
815
263
        break;
816
739
    case Break_kind:
817
739
        BEFORE_LOOP_EXIT(state, node_, "break");
818
739
        break;
819
840
    case Continue_kind:
820
840
        BEFORE_LOOP_EXIT(state, node_, "continue");
821
840
        break;
822
    // The following statements don't contain any subexpressions to be folded
823
1.43k
    case Import_kind:
824
2.64k
    case ImportFrom_kind:
825
2.86k
    case Global_kind:
826
2.97k
    case Nonlocal_kind:
827
3.59k
    case Pass_kind:
828
3.59k
        break;
829
    // No default case, so the compiler will emit a warning if new statement
830
    // kinds are added without being handled here
831
101k
    }
832
101k
    LEAVE_RECURSIVE();
833
101k
    return 1;
834
101k
}
835
836
static int
837
astfold_excepthandler(excepthandler_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
838
2.14k
{
839
2.14k
    switch (node_->kind) {
840
2.14k
    case ExceptHandler_kind:
841
2.14k
        CALL_OPT(astfold_expr, expr_ty, node_->v.ExceptHandler.type);
842
2.14k
        CALL_SEQ(astfold_stmt, stmt, node_->v.ExceptHandler.body);
843
2.14k
        break;
844
    // No default case, so the compiler will emit a warning if new handler
845
    // kinds are added without being handled here
846
2.14k
    }
847
2.14k
    return 1;
848
2.14k
}
849
850
static int
851
astfold_withitem(withitem_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
852
1.65k
{
853
1.65k
    CALL(astfold_expr, expr_ty, node_->context_expr);
854
1.65k
    CALL_OPT(astfold_expr, expr_ty, node_->optional_vars);
855
1.65k
    return 1;
856
1.65k
}
857
858
static int
859
fold_const_match_patterns(expr_ty node, PyArena *ctx_, _PyASTPreprocessState *state)
860
375
{
861
375
    if (state->syntax_check_only) {
862
359
        return 1;
863
359
    }
864
16
    switch (node->kind)
865
16
    {
866
0
        case UnaryOp_kind:
867
0
        {
868
0
            if (node->v.UnaryOp.op == USub &&
869
0
                node->v.UnaryOp.operand->kind == Constant_kind)
870
0
            {
871
0
                PyObject *operand = node->v.UnaryOp.operand->v.Constant.value;
872
0
                PyObject *folded = PyNumber_Negative(operand);
873
0
                return make_const(node, folded, ctx_);
874
0
            }
875
0
            break;
876
0
        }
877
0
        case BinOp_kind:
878
0
        {
879
0
            operator_ty op = node->v.BinOp.op;
880
0
            if ((op == Add || op == Sub) &&
881
0
                node->v.BinOp.right->kind == Constant_kind)
882
0
            {
883
0
                CALL(fold_const_match_patterns, expr_ty, node->v.BinOp.left);
884
0
                if (node->v.BinOp.left->kind == Constant_kind) {
885
0
                    PyObject *left = node->v.BinOp.left->v.Constant.value;
886
0
                    PyObject *right = node->v.BinOp.right->v.Constant.value;
887
0
                    PyObject *folded = op == Add ? PyNumber_Add(left, right) : PyNumber_Subtract(left, right);
888
0
                    return make_const(node, folded, ctx_);
889
0
                }
890
0
            }
891
0
            break;
892
0
        }
893
16
        default:
894
16
            break;
895
16
    }
896
16
    return 1;
897
16
}
898
899
static int
900
astfold_pattern(pattern_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
901
14.3k
{
902
    // Currently, this is really only used to form complex/negative numeric
903
    // constants in MatchValue and MatchMapping nodes
904
    // We still recurse into all subexpressions and subpatterns anyway
905
14.3k
    ENTER_RECURSIVE();
906
14.3k
    switch (node_->kind) {
907
306
        case MatchValue_kind:
908
306
            CALL(fold_const_match_patterns, expr_ty, node_->v.MatchValue.value);
909
306
            break;
910
73
        case MatchSingleton_kind:
911
73
            break;
912
574
        case MatchSequence_kind:
913
574
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchSequence.patterns);
914
574
            break;
915
184
        case MatchMapping_kind:
916
184
            CALL_SEQ(fold_const_match_patterns, expr, node_->v.MatchMapping.keys);
917
184
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchMapping.patterns);
918
184
            break;
919
1.44k
        case MatchClass_kind:
920
1.44k
            CALL(astfold_expr, expr_ty, node_->v.MatchClass.cls);
921
1.44k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchClass.patterns);
922
1.44k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchClass.kwd_patterns);
923
1.44k
            break;
924
334
        case MatchStar_kind:
925
334
            break;
926
8.73k
        case MatchAs_kind:
927
8.73k
            if (node_->v.MatchAs.pattern) {
928
87
                CALL(astfold_pattern, pattern_ty, node_->v.MatchAs.pattern);
929
87
            }
930
8.73k
            break;
931
8.73k
        case MatchOr_kind:
932
2.66k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchOr.patterns);
933
2.66k
            break;
934
    // No default case, so the compiler will emit a warning if new pattern
935
    // kinds are added without being handled here
936
14.3k
    }
937
14.3k
    LEAVE_RECURSIVE();
938
14.3k
    return 1;
939
14.3k
}
940
941
static int
942
astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
943
778
{
944
778
    CALL(astfold_pattern, expr_ty, node_->pattern);
945
778
    CALL_OPT(astfold_expr, expr_ty, node_->guard);
946
778
    CALL_SEQ(astfold_stmt, stmt, node_->body);
947
778
    return 1;
948
778
}
949
950
static int
951
astfold_type_param(type_param_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
952
6.66k
{
953
6.66k
    switch (node_->kind) {
954
5.41k
        case TypeVar_kind:
955
5.41k
            CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVar.bound);
956
5.41k
            CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVar.default_value);
957
5.41k
            break;
958
524
        case ParamSpec_kind:
959
524
            CALL_OPT(astfold_expr, expr_ty, node_->v.ParamSpec.default_value);
960
524
            break;
961
730
        case TypeVarTuple_kind:
962
730
            CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVarTuple.default_value);
963
730
            break;
964
6.66k
    }
965
6.66k
    return 1;
966
6.66k
}
967
968
#undef CALL
969
#undef CALL_OPT
970
#undef CALL_SEQ
971
972
int
973
_PyAST_Preprocess(mod_ty mod, PyArena *arena, PyObject *filename, int optimize,
974
                  int ff_features, int syntax_check_only, int enable_warnings,
975
                  PyObject *module)
976
6.38k
{
977
6.38k
    _PyASTPreprocessState state;
978
6.38k
    memset(&state, 0, sizeof(_PyASTPreprocessState));
979
6.38k
    state.filename = filename;
980
6.38k
    state.module = module;
981
6.38k
    state.optimize = optimize;
982
6.38k
    state.ff_features = ff_features;
983
6.38k
    state.syntax_check_only = syntax_check_only;
984
6.38k
    state.enable_warnings = enable_warnings;
985
6.38k
    if (_Py_CArray_Init(&state.cf_finally, sizeof(ControlFlowInFinallyContext), 20) < 0) {
986
0
        return -1;
987
0
    }
988
989
6.38k
    int ret = astfold_mod(mod, arena, &state);
990
6.38k
    assert(ret || PyErr_Occurred());
991
992
6.38k
    _Py_CArray_Fini(&state.cf_finally);
993
6.38k
    return ret;
994
6.38k
}