Coverage Report

Created: 2026-12-01 06:09

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
491k
#define ENTER_RECURSIVE() \
30
491k
if (Py_EnterRecursiveCall(" during compilation")) { \
31
0
    return 0; \
32
0
}
33
34
491k
#define LEAVE_RECURSIVE() Py_LeaveRecursiveCall();
35
36
static ControlFlowInFinallyContext*
37
get_cf_finally_top(_PyASTPreprocessState *state)
38
9.16k
{
39
9.16k
    int idx = state->cf_finally_used;
40
9.16k
    return ((ControlFlowInFinallyContext*)state->cf_finally.array) + idx;
41
9.16k
}
42
43
static int
44
push_cf_context(_PyASTPreprocessState *state, stmt_ty node, bool finally, bool funcdef, bool loop)
45
7.09k
{
46
7.09k
    if (_Py_CArray_EnsureCapacity(&state->cf_finally, state->cf_finally_used+1) < 0) {
47
0
        return 0;
48
0
    }
49
50
7.09k
    state->cf_finally_used++;
51
7.09k
    ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
52
53
7.09k
    ctx->in_finally = finally;
54
7.09k
    ctx->in_funcdef = funcdef;
55
7.09k
    ctx->in_loop = loop;
56
7.09k
    return 1;
57
7.09k
}
58
59
static void
60
pop_cf_context(_PyASTPreprocessState *state)
61
7.09k
{
62
7.09k
    assert(state->cf_finally_used > 0);
63
7.09k
    state->cf_finally_used--;
64
7.09k
}
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
2.49k
{
84
2.49k
    if (state->enable_warnings && state->cf_finally_used > 0) {
85
2.02k
        ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
86
2.02k
        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
2.02k
    }
92
2.49k
    return 1;
93
2.49k
}
94
95
static int
96
before_loop_exit(_PyASTPreprocessState *state, stmt_ty node_, const char *kw)
97
558
{
98
558
    if (state->enable_warnings && state->cf_finally_used > 0) {
99
41
        ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
100
41
        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
41
    }
106
558
    return 1;
107
558
}
108
109
#define PUSH_CONTEXT(S, N, FINALLY, FUNCDEF, LOOP) \
110
7.09k
    if (!push_cf_context((S), (N), (FINALLY), (FUNCDEF), (LOOP))) { \
111
0
        return 0; \
112
0
    }
113
114
7.09k
#define POP_CONTEXT(S) pop_cf_context(S)
115
116
1.15k
#define BEFORE_FINALLY(S, N)    PUSH_CONTEXT((S), (N), true, false, false)
117
1.15k
#define AFTER_FINALLY(S)        POP_CONTEXT(S)
118
5.14k
#define BEFORE_FUNC_BODY(S, N)  PUSH_CONTEXT((S), (N), false, true, false)
119
5.14k
#define AFTER_FUNC_BODY(S)      POP_CONTEXT(S)
120
804
#define BEFORE_LOOP_BODY(S, N)  PUSH_CONTEXT((S), (N), false, false, true)
121
804
#define AFTER_LOOP_BODY(S)      POP_CONTEXT(S)
122
123
#define BEFORE_RETURN(S, N) \
124
2.49k
    if (!before_return((S), (N))) { \
125
0
        return 0; \
126
0
    }
127
128
#define BEFORE_LOOP_EXIT(S, N, KW) \
129
558
    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
61
#define COPY_NODE(TO, FROM) (memcpy((TO), (FROM), sizeof(struct _expr)))
156
157
static int
158
has_starred(asdl_expr_seq *elts)
159
77
{
160
77
    Py_ssize_t n = asdl_seq_LEN(elts);
161
242
    for (Py_ssize_t i = 0; i < n; i++) {
162
165
        expr_ty e = (expr_ty)asdl_seq_GET(elts, i);
163
165
        if (e->kind == Starred_kind) {
164
0
            return 1;
165
0
        }
166
165
    }
167
77
    return 0;
168
77
}
169
170
static expr_ty
171
parse_literal(PyObject *fmt, Py_ssize_t *ppos, PyArena *arena)
172
208
{
173
208
    const void *data = PyUnicode_DATA(fmt);
174
208
    int kind = PyUnicode_KIND(fmt);
175
208
    Py_ssize_t size = PyUnicode_GET_LENGTH(fmt);
176
208
    Py_ssize_t start, pos;
177
208
    int has_percents = 0;
178
208
    start = pos = *ppos;
179
1.41k
    while (pos < size) {
180
1.35k
        if (PyUnicode_READ(kind, data, pos) != '%') {
181
1.20k
            pos++;
182
1.20k
        }
183
147
        else if (pos+1 < size && PyUnicode_READ(kind, data, pos+1) == '%') {
184
0
            has_percents = 1;
185
0
            pos += 2;
186
0
        }
187
147
        else {
188
147
            break;
189
147
        }
190
1.35k
    }
191
208
    *ppos = pos;
192
208
    if (pos == start) {
193
63
        return NULL;
194
63
    }
195
145
    PyObject *str = PyUnicode_Substring(fmt, start, pos);
196
    /* str = str.replace('%%', '%') */
197
145
    if (str && has_percents) {
198
0
        _Py_DECLARE_STR(dbl_percent, "%%");
199
0
        Py_SETREF(str, PyUnicode_Replace(str, &_Py_STR(dbl_percent),
200
0
                                         _Py_LATIN1_CHR('%'), -1));
201
0
    }
202
145
    if (!str) {
203
0
        return NULL;
204
0
    }
205
206
145
    if (_PyArena_AddPyObject(arena, str) < 0) {
207
0
        Py_DECREF(str);
208
0
        return NULL;
209
0
    }
210
145
    return _PyAST_Constant(str, NULL, -1, -1, -1, -1, arena);
211
145
}
212
213
4
#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
147
{
219
147
    Py_ssize_t pos = *ppos, len = PyUnicode_GET_LENGTH(fmt);
220
147
    Py_UCS4 ch;
221
222
153
#define NEXTC do {                      \
223
153
    if (pos >= len) {                   \
224
0
        return 0;                       \
225
0
    }                                   \
226
153
    ch = PyUnicode_READ_CHAR(fmt, pos); \
227
153
    pos++;                              \
228
153
} while (0)
229
230
147
    *flags = 0;
231
150
    while (1) {
232
150
        NEXTC;
233
150
        switch (ch) {
234
1
            case '-': *flags |= F_LJUST; continue;
235
0
            case '+': *flags |= F_SIGN; continue;
236
0
            case ' ': *flags |= F_BLANK; continue;
237
1
            case '#': *flags |= F_ALT; continue;
238
1
            case '0': *flags |= F_ZERO; continue;
239
150
        }
240
147
        break;
241
150
    }
242
147
    if ('0' <= ch && ch <= '9') {
243
2
        *width = 0;
244
2
        int digits = 0;
245
5
        while ('0' <= ch && ch <= '9') {
246
3
            *width = *width * 10 + (ch - '0');
247
3
            NEXTC;
248
3
            if (++digits >= MAXDIGITS) {
249
0
                return 0;
250
0
            }
251
3
        }
252
2
    }
253
254
147
    if (ch == '.') {
255
0
        NEXTC;
256
0
        *prec = 0;
257
0
        if ('0' <= ch && ch <= '9') {
258
0
            int digits = 0;
259
0
            while ('0' <= ch && ch <= '9') {
260
0
                *prec = *prec * 10 + (ch - '0');
261
0
                NEXTC;
262
0
                if (++digits >= MAXDIGITS) {
263
0
                    return 0;
264
0
                }
265
0
            }
266
0
        }
267
0
    }
268
147
    *spec = ch;
269
147
    *ppos = pos;
270
147
    return 1;
271
272
147
#undef NEXTC
273
147
}
274
275
static expr_ty
276
parse_format(PyObject *fmt, Py_ssize_t *ppos, expr_ty arg, PyArena *arena)
277
147
{
278
147
    int spec, flags, width = -1, prec = -1;
279
147
    if (!simple_format_arg_parse(fmt, ppos, &spec, &flags, &width, &prec)) {
280
        // Unsupported format.
281
0
        return NULL;
282
0
    }
283
147
    if (spec == 's' || spec == 'r' || spec == 'a') {
284
131
        char buf[1 + MAXDIGITS + 1 + MAXDIGITS + 1], *p = buf;
285
131
        if (!(flags & F_LJUST) && width > 0) {
286
0
            *p++ = '>';
287
0
        }
288
131
        if (width >= 0) {
289
1
            p += snprintf(p, MAXDIGITS + 1, "%d", width);
290
1
        }
291
131
        if (prec >= 0) {
292
0
            p += snprintf(p, MAXDIGITS + 2, ".%d", prec);
293
0
        }
294
131
        expr_ty format_spec = NULL;
295
131
        if (p != buf) {
296
1
            PyObject *str = PyUnicode_FromString(buf);
297
1
            if (str == NULL) {
298
0
                return NULL;
299
0
            }
300
1
            if (_PyArena_AddPyObject(arena, str) < 0) {
301
0
                Py_DECREF(str);
302
0
                return NULL;
303
0
            }
304
1
            format_spec = _PyAST_Constant(str, NULL, -1, -1, -1, -1, arena);
305
1
            if (format_spec == NULL) {
306
0
                return NULL;
307
0
            }
308
1
        }
309
131
        return _PyAST_FormattedValue(arg, spec, format_spec,
310
131
                                     arg->lineno, arg->col_offset,
311
131
                                     arg->end_lineno, arg->end_col_offset,
312
131
                                     arena);
313
131
    }
314
    // Unsupported format.
315
16
    return NULL;
316
147
}
317
318
static int
319
optimize_format(expr_ty node, PyObject *fmt, asdl_expr_seq *elts, PyArena *arena)
320
77
{
321
77
    Py_ssize_t pos = 0;
322
77
    Py_ssize_t cnt = 0;
323
77
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(asdl_seq_LEN(elts) * 2 + 1, arena);
324
77
    if (!seq) {
325
0
        return 0;
326
0
    }
327
77
    seq->size = 0;
328
329
208
    while (1) {
330
208
        expr_ty lit = parse_literal(fmt, &pos, arena);
331
208
        if (lit) {
332
145
            asdl_seq_SET(seq, seq->size++, lit);
333
145
        }
334
63
        else if (PyErr_Occurred()) {
335
0
            return 0;
336
0
        }
337
338
208
        if (pos >= PyUnicode_GET_LENGTH(fmt)) {
339
61
            break;
340
61
        }
341
147
        if (cnt >= asdl_seq_LEN(elts)) {
342
            // More format units than items.
343
0
            return 1;
344
0
        }
345
147
        assert(PyUnicode_READ_CHAR(fmt, pos) == '%');
346
147
        pos++;
347
147
        expr_ty expr = parse_format(fmt, &pos, asdl_seq_GET(elts, cnt), arena);
348
147
        cnt++;
349
147
        if (!expr) {
350
16
            return !PyErr_Occurred();
351
16
        }
352
131
        asdl_seq_SET(seq, seq->size++, expr);
353
131
    }
354
61
    if (cnt < asdl_seq_LEN(elts)) {
355
        // More items than format units.
356
0
        return 1;
357
0
    }
358
61
    expr_ty res = _PyAST_JoinedStr(seq,
359
61
                                   node->lineno, node->col_offset,
360
61
                                   node->end_lineno, node->end_col_offset,
361
61
                                   arena);
362
61
    if (!res) {
363
0
        return 0;
364
0
    }
365
61
    COPY_NODE(node, res);
366
//     PySys_FormatStderr("format = %R\n", fmt);
367
61
    return 1;
368
61
}
369
370
static int
371
fold_binop(expr_ty node, PyArena *arena, _PyASTPreprocessState *state)
372
24.9k
{
373
24.9k
    if (state->syntax_check_only) {
374
24.4k
        return 1;
375
24.4k
    }
376
538
    expr_ty lhs, rhs;
377
538
    lhs = node->v.BinOp.left;
378
538
    rhs = node->v.BinOp.right;
379
538
    if (lhs->kind != Constant_kind) {
380
313
        return 1;
381
313
    }
382
225
    PyObject *lv = lhs->v.Constant.value;
383
384
225
    if (node->v.BinOp.op == Mod &&
385
128
        rhs->kind == Tuple_kind &&
386
225
        PyUnicode_Check(lv) &&
387
77
        !has_starred(rhs->v.Tuple.elts))
388
77
    {
389
77
        return optimize_format(node, lv, rhs->v.Tuple.elts, arena);
390
77
    }
391
392
148
    return 1;
393
225
}
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
330k
    if (!FUNC((ARG), ctx_, state)) \
410
330k
        return 0;
411
412
#define CALL_OPT(FUNC, TYPE, ARG) \
413
86.3k
    if ((ARG) != NULL && !FUNC((ARG), ctx_, state)) \
414
86.3k
        return 0;
415
416
152k
#define CALL_SEQ(FUNC, TYPE, ARG) { \
417
152k
    Py_ssize_t i; \
418
152k
    asdl_ ## TYPE ## _seq *seq = (ARG); /* avoid variable capture */ \
419
380k
    for (i = 0; i < asdl_seq_LEN(seq); i++) { \
420
228k
        TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
421
228k
        if (elt != NULL && !FUNC(elt, ctx_, state)) \
422
228k
            return 0; \
423
228k
    } \
424
152k
}
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
14.8k
{
469
14.8k
    int docstring = _PyAST_GetDocString(stmts) != NULL;
470
14.8k
    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
14.8k
    CALL_SEQ(astfold_stmt, stmt, stmts);
478
14.8k
    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
14.8k
    return 1;
494
14.8k
}
495
496
static int
497
astfold_mod(mod_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
498
8.92k
{
499
8.92k
    switch (node_->kind) {
500
8.74k
    case Module_kind:
501
8.74k
        CALL(astfold_body, asdl_seq, node_->v.Module.body);
502
8.74k
        break;
503
0
    case Interactive_kind:
504
0
        CALL_SEQ(astfold_stmt, stmt, node_->v.Interactive.body);
505
0
        break;
506
172
    case Expression_kind:
507
172
        CALL(astfold_expr, expr_ty, node_->v.Expression.body);
508
172
        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
8.92k
    }
515
8.92k
    return 1;
516
8.92k
}
517
518
static int
519
astfold_expr(expr_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
520
406k
{
521
406k
    ENTER_RECURSIVE();
522
406k
    switch (node_->kind) {
523
1.31k
    case BoolOp_kind:
524
1.31k
        CALL_SEQ(astfold_expr, expr, node_->v.BoolOp.values);
525
1.31k
        break;
526
24.9k
    case BinOp_kind:
527
24.9k
        CALL(astfold_expr, expr_ty, node_->v.BinOp.left);
528
24.9k
        CALL(astfold_expr, expr_ty, node_->v.BinOp.right);
529
24.9k
        CALL(fold_binop, expr_ty, node_);
530
24.9k
        break;
531
99.9k
    case UnaryOp_kind:
532
99.9k
        CALL(astfold_expr, expr_ty, node_->v.UnaryOp.operand);
533
99.9k
        break;
534
1.87k
    case Lambda_kind:
535
1.87k
        CALL(astfold_arguments, arguments_ty, node_->v.Lambda.args);
536
1.87k
        CALL(astfold_expr, expr_ty, node_->v.Lambda.body);
537
1.87k
        break;
538
267
    case IfExp_kind:
539
267
        CALL(astfold_expr, expr_ty, node_->v.IfExp.test);
540
267
        CALL(astfold_expr, expr_ty, node_->v.IfExp.body);
541
267
        CALL(astfold_expr, expr_ty, node_->v.IfExp.orelse);
542
267
        break;
543
1.25k
    case Dict_kind:
544
1.25k
        CALL_SEQ(astfold_expr, expr, node_->v.Dict.keys);
545
1.25k
        CALL_SEQ(astfold_expr, expr, node_->v.Dict.values);
546
1.25k
        break;
547
606
    case Set_kind:
548
606
        CALL_SEQ(astfold_expr, expr, node_->v.Set.elts);
549
606
        break;
550
266
    case ListComp_kind:
551
266
        CALL(astfold_expr, expr_ty, node_->v.ListComp.elt);
552
266
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.ListComp.generators);
553
266
        break;
554
281
    case SetComp_kind:
555
281
        CALL(astfold_expr, expr_ty, node_->v.SetComp.elt);
556
281
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.SetComp.generators);
557
281
        break;
558
419
    case DictComp_kind:
559
419
        CALL(astfold_expr, expr_ty, node_->v.DictComp.key);
560
419
        if (node_->v.DictComp.value != NULL){
561
351
            CALL(astfold_expr, expr_ty, node_->v.DictComp.value);
562
351
        }
563
419
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.DictComp.generators);
564
419
        break;
565
576
    case GeneratorExp_kind:
566
576
        CALL(astfold_expr, expr_ty, node_->v.GeneratorExp.elt);
567
576
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.GeneratorExp.generators);
568
576
        break;
569
207
    case Await_kind:
570
207
        CALL(astfold_expr, expr_ty, node_->v.Await.value);
571
207
        break;
572
337
    case Yield_kind:
573
337
        CALL_OPT(astfold_expr, expr_ty, node_->v.Yield.value);
574
337
        break;
575
207
    case YieldFrom_kind:
576
207
        CALL(astfold_expr, expr_ty, node_->v.YieldFrom.value);
577
207
        break;
578
6.33k
    case Compare_kind:
579
6.33k
        CALL(astfold_expr, expr_ty, node_->v.Compare.left);
580
6.33k
        CALL_SEQ(astfold_expr, expr, node_->v.Compare.comparators);
581
6.33k
        break;
582
15.2k
    case Call_kind:
583
15.2k
        CALL(astfold_expr, expr_ty, node_->v.Call.func);
584
15.2k
        CALL_SEQ(astfold_expr, expr, node_->v.Call.args);
585
15.2k
        CALL_SEQ(astfold_keyword, keyword, node_->v.Call.keywords);
586
15.2k
        break;
587
15.2k
    case FormattedValue_kind:
588
15.2k
        CALL(astfold_expr, expr_ty, node_->v.FormattedValue.value);
589
15.2k
        CALL_OPT(astfold_expr, expr_ty, node_->v.FormattedValue.format_spec);
590
15.2k
        break;
591
2.48k
    case Interpolation_kind:
592
2.48k
        CALL(astfold_expr, expr_ty, node_->v.Interpolation.value);
593
2.48k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Interpolation.format_spec);
594
2.48k
        break;
595
8.94k
    case JoinedStr_kind:
596
8.94k
        CALL_SEQ(astfold_expr, expr, node_->v.JoinedStr.values);
597
8.94k
        break;
598
439
    case TemplateStr_kind:
599
439
        CALL_SEQ(astfold_expr, expr, node_->v.TemplateStr.values);
600
439
        break;
601
18.8k
    case Attribute_kind:
602
18.8k
        CALL(astfold_expr, expr_ty, node_->v.Attribute.value);
603
18.8k
        break;
604
1.65k
    case Subscript_kind:
605
1.65k
        CALL(astfold_expr, expr_ty, node_->v.Subscript.value);
606
1.65k
        CALL(astfold_expr, expr_ty, node_->v.Subscript.slice);
607
1.65k
        break;
608
1.33k
    case Starred_kind:
609
1.33k
        CALL(astfold_expr, expr_ty, node_->v.Starred.value);
610
1.33k
        break;
611
3.27k
    case Slice_kind:
612
3.27k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.lower);
613
3.27k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.upper);
614
3.27k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.step);
615
3.27k
        break;
616
1.57k
    case List_kind:
617
1.57k
        CALL_SEQ(astfold_expr, expr, node_->v.List.elts);
618
1.57k
        break;
619
7.74k
    case Tuple_kind:
620
7.74k
        CALL_SEQ(astfold_expr, expr, node_->v.Tuple.elts);
621
7.74k
        break;
622
109k
    case Name_kind:
623
109k
        if (state->syntax_check_only) {
624
83.0k
            break;
625
83.0k
        }
626
26.1k
        if (node_->v.Name.ctx == Load &&
627
23.7k
                _PyUnicode_EqualToASCIIString(node_->v.Name.id, "__debug__")) {
628
0
            LEAVE_RECURSIVE();
629
0
            return make_const(node_, PyBool_FromLong(!state->optimize), ctx_);
630
0
        }
631
26.1k
        break;
632
26.1k
    case NamedExpr_kind:
633
72
        CALL(astfold_expr, expr_ty, node_->v.NamedExpr.value);
634
72
        break;
635
81.6k
    case Constant_kind:
636
        // Already a constant, nothing further to do
637
81.6k
        break;
638
    // No default case, so the compiler will emit a warning if new expression
639
    // kinds are added without being handled here
640
406k
    }
641
406k
    LEAVE_RECURSIVE();
642
406k
    return 1;
643
406k
}
644
645
static int
646
astfold_keyword(keyword_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
647
3.29k
{
648
3.29k
    CALL(astfold_expr, expr_ty, node_->value);
649
3.29k
    return 1;
650
3.29k
}
651
652
static int
653
astfold_comprehension(comprehension_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
654
1.65k
{
655
1.65k
    CALL(astfold_expr, expr_ty, node_->target);
656
1.65k
    CALL(astfold_expr, expr_ty, node_->iter);
657
1.65k
    CALL_SEQ(astfold_expr, expr, node_->ifs);
658
1.65k
    return 1;
659
1.65k
}
660
661
static int
662
astfold_arguments(arguments_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
663
7.01k
{
664
7.01k
    CALL_SEQ(astfold_arg, arg, node_->posonlyargs);
665
7.01k
    CALL_SEQ(astfold_arg, arg, node_->args);
666
7.01k
    CALL_OPT(astfold_arg, arg_ty, node_->vararg);
667
7.01k
    CALL_SEQ(astfold_arg, arg, node_->kwonlyargs);
668
7.01k
    CALL_SEQ(astfold_expr, expr, node_->kw_defaults);
669
7.01k
    CALL_OPT(astfold_arg, arg_ty, node_->kwarg);
670
7.01k
    CALL_SEQ(astfold_expr, expr, node_->defaults);
671
7.01k
    return 1;
672
7.01k
}
673
674
static int
675
astfold_arg(arg_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
676
17.7k
{
677
17.7k
    if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
678
16.7k
        CALL_OPT(astfold_expr, expr_ty, node_->annotation);
679
16.7k
    }
680
17.7k
    return 1;
681
17.7k
}
682
683
static int
684
astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
685
68.0k
{
686
68.0k
    ENTER_RECURSIVE();
687
68.0k
    switch (node_->kind) {
688
4.44k
    case FunctionDef_kind: {
689
4.44k
        CALL_SEQ(astfold_type_param, type_param, node_->v.FunctionDef.type_params);
690
4.44k
        CALL(astfold_arguments, arguments_ty, node_->v.FunctionDef.args);
691
4.44k
        BEFORE_FUNC_BODY(state, node_);
692
4.44k
        CALL(astfold_body, asdl_seq, node_->v.FunctionDef.body);
693
4.44k
        AFTER_FUNC_BODY(state);
694
4.44k
        CALL_SEQ(astfold_expr, expr, node_->v.FunctionDef.decorator_list);
695
4.44k
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
696
4.08k
            CALL_OPT(astfold_expr, expr_ty, node_->v.FunctionDef.returns);
697
4.08k
        }
698
4.44k
        break;
699
4.44k
    }
700
4.44k
    case AsyncFunctionDef_kind: {
701
698
        CALL_SEQ(astfold_type_param, type_param, node_->v.AsyncFunctionDef.type_params);
702
698
        CALL(astfold_arguments, arguments_ty, node_->v.AsyncFunctionDef.args);
703
698
        BEFORE_FUNC_BODY(state, node_);
704
698
        CALL(astfold_body, asdl_seq, node_->v.AsyncFunctionDef.body);
705
698
        AFTER_FUNC_BODY(state);
706
698
        CALL_SEQ(astfold_expr, expr, node_->v.AsyncFunctionDef.decorator_list);
707
698
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
708
632
            CALL_OPT(astfold_expr, expr_ty, node_->v.AsyncFunctionDef.returns);
709
632
        }
710
698
        break;
711
698
    }
712
965
    case ClassDef_kind:
713
965
        CALL_SEQ(astfold_type_param, type_param, node_->v.ClassDef.type_params);
714
965
        CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.bases);
715
965
        CALL_SEQ(astfold_keyword, keyword, node_->v.ClassDef.keywords);
716
965
        CALL(astfold_body, asdl_seq, node_->v.ClassDef.body);
717
965
        CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.decorator_list);
718
965
        break;
719
2.49k
    case Return_kind:
720
2.49k
        BEFORE_RETURN(state, node_);
721
2.49k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Return.value);
722
2.49k
        break;
723
385
    case Delete_kind:
724
385
        CALL_SEQ(astfold_expr, expr, node_->v.Delete.targets);
725
385
        break;
726
3.27k
    case Assign_kind:
727
3.27k
        CALL_SEQ(astfold_expr, expr, node_->v.Assign.targets);
728
3.27k
        CALL(astfold_expr, expr_ty, node_->v.Assign.value);
729
3.27k
        break;
730
617
    case AugAssign_kind:
731
617
        CALL(astfold_expr, expr_ty, node_->v.AugAssign.target);
732
617
        CALL(astfold_expr, expr_ty, node_->v.AugAssign.value);
733
617
        break;
734
1.25k
    case AnnAssign_kind:
735
1.25k
        CALL(astfold_expr, expr_ty, node_->v.AnnAssign.target);
736
1.25k
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
737
1.18k
            CALL(astfold_expr, expr_ty, node_->v.AnnAssign.annotation);
738
1.18k
        }
739
1.25k
        CALL_OPT(astfold_expr, expr_ty, node_->v.AnnAssign.value);
740
1.25k
        break;
741
215
    case TypeAlias_kind:
742
215
        CALL(astfold_expr, expr_ty, node_->v.TypeAlias.name);
743
215
        CALL_SEQ(astfold_type_param, type_param, node_->v.TypeAlias.type_params);
744
215
        CALL(astfold_expr, expr_ty, node_->v.TypeAlias.value);
745
215
        break;
746
412
    case For_kind: {
747
412
        CALL(astfold_expr, expr_ty, node_->v.For.target);
748
412
        CALL(astfold_expr, expr_ty, node_->v.For.iter);
749
412
        BEFORE_LOOP_BODY(state, node_);
750
412
        CALL_SEQ(astfold_stmt, stmt, node_->v.For.body);
751
412
        AFTER_LOOP_BODY(state);
752
412
        CALL_SEQ(astfold_stmt, stmt, node_->v.For.orelse);
753
412
        break;
754
412
    }
755
84
    case AsyncFor_kind: {
756
84
        CALL(astfold_expr, expr_ty, node_->v.AsyncFor.target);
757
84
        CALL(astfold_expr, expr_ty, node_->v.AsyncFor.iter);
758
84
        BEFORE_LOOP_BODY(state, node_);
759
84
        CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncFor.body);
760
84
        AFTER_LOOP_BODY(state);
761
84
        CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncFor.orelse);
762
84
        break;
763
84
    }
764
308
    case While_kind: {
765
308
        CALL(astfold_expr, expr_ty, node_->v.While.test);
766
308
        BEFORE_LOOP_BODY(state, node_);
767
308
        CALL_SEQ(astfold_stmt, stmt, node_->v.While.body);
768
308
        AFTER_LOOP_BODY(state);
769
308
        CALL_SEQ(astfold_stmt, stmt, node_->v.While.orelse);
770
308
        break;
771
308
    }
772
1.98k
    case If_kind:
773
1.98k
        CALL(astfold_expr, expr_ty, node_->v.If.test);
774
1.98k
        CALL_SEQ(astfold_stmt, stmt, node_->v.If.body);
775
1.98k
        CALL_SEQ(astfold_stmt, stmt, node_->v.If.orelse);
776
1.98k
        break;
777
659
    case With_kind:
778
659
        CALL_SEQ(astfold_withitem, withitem, node_->v.With.items);
779
659
        CALL_SEQ(astfold_stmt, stmt, node_->v.With.body);
780
659
        break;
781
236
    case AsyncWith_kind:
782
236
        CALL_SEQ(astfold_withitem, withitem, node_->v.AsyncWith.items);
783
236
        CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncWith.body);
784
236
        break;
785
945
    case Raise_kind:
786
945
        CALL_OPT(astfold_expr, expr_ty, node_->v.Raise.exc);
787
945
        CALL_OPT(astfold_expr, expr_ty, node_->v.Raise.cause);
788
945
        break;
789
778
    case Try_kind: {
790
778
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.body);
791
778
        CALL_SEQ(astfold_excepthandler, excepthandler, node_->v.Try.handlers);
792
778
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.orelse);
793
778
        BEFORE_FINALLY(state, node_);
794
778
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.finalbody);
795
778
        AFTER_FINALLY(state);
796
778
        break;
797
778
    }
798
373
    case TryStar_kind: {
799
373
        CALL_SEQ(astfold_stmt, stmt, node_->v.TryStar.body);
800
373
        CALL_SEQ(astfold_excepthandler, excepthandler, node_->v.TryStar.handlers);
801
373
        CALL_SEQ(astfold_stmt, stmt, node_->v.TryStar.orelse);
802
373
        BEFORE_FINALLY(state, node_);
803
373
        CALL_SEQ(astfold_stmt, stmt, node_->v.TryStar.finalbody);
804
373
        AFTER_FINALLY(state);
805
373
        break;
806
373
    }
807
337
    case Assert_kind:
808
337
        CALL(astfold_expr, expr_ty, node_->v.Assert.test);
809
337
        CALL_OPT(astfold_expr, expr_ty, node_->v.Assert.msg);
810
337
        break;
811
43.2k
    case Expr_kind:
812
43.2k
        CALL(astfold_expr, expr_ty, node_->v.Expr.value);
813
43.2k
        break;
814
295
    case Match_kind:
815
295
        CALL(astfold_expr, expr_ty, node_->v.Match.subject);
816
295
        CALL_SEQ(astfold_match_case, match_case, node_->v.Match.cases);
817
295
        break;
818
325
    case Break_kind:
819
325
        BEFORE_LOOP_EXIT(state, node_, "break");
820
325
        break;
821
233
    case Continue_kind:
822
233
        BEFORE_LOOP_EXIT(state, node_, "continue");
823
233
        break;
824
    // The following statements don't contain any subexpressions to be folded
825
1.00k
    case Import_kind:
826
2.54k
    case ImportFrom_kind:
827
2.88k
    case Global_kind:
828
3.08k
    case Nonlocal_kind:
829
3.50k
    case Pass_kind:
830
3.50k
        break;
831
    // No default case, so the compiler will emit a warning if new statement
832
    // kinds are added without being handled here
833
68.0k
    }
834
68.0k
    LEAVE_RECURSIVE();
835
68.0k
    return 1;
836
68.0k
}
837
838
static int
839
astfold_excepthandler(excepthandler_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
840
1.49k
{
841
1.49k
    switch (node_->kind) {
842
1.49k
    case ExceptHandler_kind:
843
1.49k
        CALL_OPT(astfold_expr, expr_ty, node_->v.ExceptHandler.type);
844
1.49k
        CALL_SEQ(astfold_stmt, stmt, node_->v.ExceptHandler.body);
845
1.49k
        break;
846
    // No default case, so the compiler will emit a warning if new handler
847
    // kinds are added without being handled here
848
1.49k
    }
849
1.49k
    return 1;
850
1.49k
}
851
852
static int
853
astfold_withitem(withitem_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
854
2.04k
{
855
2.04k
    CALL(astfold_expr, expr_ty, node_->context_expr);
856
2.04k
    CALL_OPT(astfold_expr, expr_ty, node_->optional_vars);
857
2.04k
    return 1;
858
2.04k
}
859
860
static int
861
fold_const_match_patterns(expr_ty node, PyArena *ctx_, _PyASTPreprocessState *state)
862
1.20k
{
863
1.20k
    if (state->syntax_check_only) {
864
1.20k
        return 1;
865
1.20k
    }
866
0
    switch (node->kind)
867
0
    {
868
0
        case UnaryOp_kind:
869
0
        {
870
0
            if ((node->v.UnaryOp.op == USub || node->v.UnaryOp.op == UAdd) &&
871
0
                node->v.UnaryOp.operand->kind == Constant_kind)
872
0
            {
873
0
                PyObject *operand = node->v.UnaryOp.operand->v.Constant.value;
874
0
                PyObject *folded = node->v.UnaryOp.op == USub ? PyNumber_Negative(operand) : PyNumber_Positive(operand);
875
0
                return make_const(node, folded, ctx_);
876
0
            }
877
0
            break;
878
0
        }
879
0
        case BinOp_kind:
880
0
        {
881
0
            operator_ty op = node->v.BinOp.op;
882
0
            if ((op == Add || op == Sub) &&
883
0
                node->v.BinOp.right->kind == Constant_kind)
884
0
            {
885
0
                CALL(fold_const_match_patterns, expr_ty, node->v.BinOp.left);
886
0
                if (node->v.BinOp.left->kind == Constant_kind) {
887
0
                    PyObject *left = node->v.BinOp.left->v.Constant.value;
888
0
                    PyObject *right = node->v.BinOp.right->v.Constant.value;
889
0
                    PyObject *folded = op == Add ? PyNumber_Add(left, right) : PyNumber_Subtract(left, right);
890
0
                    return make_const(node, folded, ctx_);
891
0
                }
892
0
            }
893
0
            break;
894
0
        }
895
0
        default:
896
0
            break;
897
0
    }
898
0
    return 1;
899
0
}
900
901
static int
902
astfold_pattern(pattern_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
903
16.8k
{
904
    // Currently, this is really only used to form complex/negative numeric
905
    // constants in MatchValue and MatchMapping nodes
906
    // We still recurse into all subexpressions and subpatterns anyway
907
16.8k
    ENTER_RECURSIVE();
908
16.8k
    switch (node_->kind) {
909
803
        case MatchValue_kind:
910
803
            CALL(fold_const_match_patterns, expr_ty, node_->v.MatchValue.value);
911
803
            break;
912
410
        case MatchSingleton_kind:
913
410
            break;
914
516
        case MatchSequence_kind:
915
516
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchSequence.patterns);
916
516
            break;
917
364
        case MatchMapping_kind:
918
364
            CALL_SEQ(fold_const_match_patterns, expr, node_->v.MatchMapping.keys);
919
364
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchMapping.patterns);
920
364
            break;
921
1.13k
        case MatchClass_kind:
922
1.13k
            CALL(astfold_expr, expr_ty, node_->v.MatchClass.cls);
923
1.13k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchClass.patterns);
924
1.13k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchClass.kwd_patterns);
925
1.13k
            break;
926
510
        case MatchStar_kind:
927
510
            break;
928
9.78k
        case MatchAs_kind:
929
9.78k
            if (node_->v.MatchAs.pattern) {
930
66
                CALL(astfold_pattern, pattern_ty, node_->v.MatchAs.pattern);
931
66
            }
932
9.78k
            break;
933
9.78k
        case MatchOr_kind:
934
3.30k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchOr.patterns);
935
3.30k
            break;
936
    // No default case, so the compiler will emit a warning if new pattern
937
    // kinds are added without being handled here
938
16.8k
    }
939
16.8k
    LEAVE_RECURSIVE();
940
16.8k
    return 1;
941
16.8k
}
942
943
static int
944
astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
945
838
{
946
838
    CALL(astfold_pattern, expr_ty, node_->pattern);
947
838
    CALL_OPT(astfold_expr, expr_ty, node_->guard);
948
838
    CALL_SEQ(astfold_stmt, stmt, node_->body);
949
838
    return 1;
950
838
}
951
952
static int
953
astfold_type_param(type_param_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
954
7.22k
{
955
7.22k
    switch (node_->kind) {
956
5.41k
        case TypeVar_kind:
957
5.41k
            CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVar.bound);
958
5.41k
            CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVar.default_value);
959
5.41k
            break;
960
1.02k
        case ParamSpec_kind:
961
1.02k
            CALL_OPT(astfold_expr, expr_ty, node_->v.ParamSpec.default_value);
962
1.02k
            break;
963
782
        case TypeVarTuple_kind:
964
782
            CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVarTuple.default_value);
965
782
            break;
966
7.22k
    }
967
7.22k
    return 1;
968
7.22k
}
969
970
#undef CALL
971
#undef CALL_OPT
972
#undef CALL_SEQ
973
974
int
975
_PyAST_Preprocess(mod_ty mod, PyArena *arena, PyObject *filename, int optimize,
976
                  int ff_features, int syntax_check_only, int enable_warnings,
977
                  PyObject *module)
978
8.92k
{
979
8.92k
    _PyASTPreprocessState state;
980
8.92k
    memset(&state, 0, sizeof(_PyASTPreprocessState));
981
8.92k
    state.filename = filename;
982
8.92k
    state.module = module;
983
8.92k
    state.optimize = optimize;
984
8.92k
    state.ff_features = ff_features;
985
8.92k
    state.syntax_check_only = syntax_check_only;
986
8.92k
    state.enable_warnings = enable_warnings;
987
8.92k
    if (_Py_CArray_Init(&state.cf_finally, sizeof(ControlFlowInFinallyContext), 20) < 0) {
988
0
        return -1;
989
0
    }
990
991
8.92k
    int ret = astfold_mod(mod, arena, &state);
992
8.92k
    assert(ret || PyErr_Occurred());
993
994
8.92k
    _Py_CArray_Fini(&state.cf_finally);
995
8.92k
    return ret;
996
8.92k
}