Coverage Report

Created: 2025-10-12 06:48

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