Coverage Report

Created: 2025-10-10 06:33

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
706k
#define ENTER_RECURSIVE() \
28
706k
if (Py_EnterRecursiveCall(" during compilation")) { \
29
0
    return 0; \
30
0
}
31
32
706k
#define LEAVE_RECURSIVE() Py_LeaveRecursiveCall();
33
34
static ControlFlowInFinallyContext*
35
get_cf_finally_top(_PyASTPreprocessState *state)
36
19.8k
{
37
19.8k
    int idx = state->cf_finally_used;
38
19.8k
    return ((ControlFlowInFinallyContext*)state->cf_finally.array) + idx;
39
19.8k
}
40
41
static int
42
push_cf_context(_PyASTPreprocessState *state, stmt_ty node, bool finally, bool funcdef, bool loop)
43
11.2k
{
44
11.2k
    if (_Py_CArray_EnsureCapacity(&state->cf_finally, state->cf_finally_used+1) < 0) {
45
0
        return 0;
46
0
    }
47
48
11.2k
    state->cf_finally_used++;
49
11.2k
    ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
50
51
11.2k
    ctx->in_finally = finally;
52
11.2k
    ctx->in_funcdef = funcdef;
53
11.2k
    ctx->in_loop = loop;
54
11.2k
    return 1;
55
11.2k
}
56
57
static void
58
pop_cf_context(_PyASTPreprocessState *state)
59
11.2k
{
60
11.2k
    assert(state->cf_finally_used > 0);
61
11.2k
    state->cf_finally_used--;
62
11.2k
}
63
64
static int
65
control_flow_in_finally_warning(const char *kw, stmt_ty n, _PyASTPreprocessState *state)
66
2.19k
{
67
2.19k
    PyObject *msg = PyUnicode_FromFormat("'%s' in a 'finally' block", kw);
68
2.19k
    if (msg == NULL) {
69
0
        return 0;
70
0
    }
71
2.19k
    int ret = _PyErr_EmitSyntaxWarning(msg, state->filename, n->lineno,
72
2.19k
                                       n->col_offset + 1, n->end_lineno,
73
2.19k
                                       n->end_col_offset + 1);
74
2.19k
    Py_DECREF(msg);
75
2.19k
    return ret < 0 ? 0 : 1;
76
2.19k
}
77
78
static int
79
before_return(_PyASTPreprocessState *state, stmt_ty node_)
80
8.17k
{
81
8.17k
    if (state->cf_finally_used > 0) {
82
7.75k
        ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
83
7.75k
        if (ctx->in_finally && ! ctx->in_funcdef) {
84
2.04k
            if (!control_flow_in_finally_warning("return", node_, state)) {
85
0
                return 0;
86
0
            }
87
2.04k
        }
88
7.75k
    }
89
8.17k
    return 1;
90
8.17k
}
91
92
static int
93
before_loop_exit(_PyASTPreprocessState *state, stmt_ty node_, const char *kw)
94
1.16k
{
95
1.16k
    if (state->cf_finally_used > 0) {
96
777
        ControlFlowInFinallyContext *ctx = get_cf_finally_top(state);
97
777
        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
777
    }
103
1.16k
    return 1;
104
1.16k
}
105
106
#define PUSH_CONTEXT(S, N, FINALLY, FUNCDEF, LOOP) \
107
11.2k
    if (!push_cf_context((S), (N), (FINALLY), (FUNCDEF), (LOOP))) { \
108
0
        return 0; \
109
0
    }
110
111
11.2k
#define POP_CONTEXT(S) pop_cf_context(S)
112
113
2.05k
#define BEFORE_FINALLY(S, N)    PUSH_CONTEXT((S), (N), true, false, false)
114
2.05k
#define AFTER_FINALLY(S)        POP_CONTEXT(S)
115
7.18k
#define BEFORE_FUNC_BODY(S, N)  PUSH_CONTEXT((S), (N), false, true, false)
116
7.18k
#define AFTER_FUNC_BODY(S)      POP_CONTEXT(S)
117
2.04k
#define BEFORE_LOOP_BODY(S, N)  PUSH_CONTEXT((S), (N), false, false, true)
118
2.04k
#define AFTER_LOOP_BODY(S)      POP_CONTEXT(S)
119
120
#define BEFORE_RETURN(S, N) \
121
8.17k
    if (!before_return((S), (N))) { \
122
0
        return 0; \
123
0
    }
124
125
#define BEFORE_LOOP_EXIT(S, N, KW) \
126
1.16k
    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
413
#define COPY_NODE(TO, FROM) (memcpy((TO), (FROM), sizeof(struct _expr)))
153
154
static int
155
has_starred(asdl_expr_seq *elts)
156
510
{
157
510
    Py_ssize_t n = asdl_seq_LEN(elts);
158
1.56k
    for (Py_ssize_t i = 0; i < n; i++) {
159
1.05k
        expr_ty e = (expr_ty)asdl_seq_GET(elts, i);
160
1.05k
        if (e->kind == Starred_kind) {
161
0
            return 1;
162
0
        }
163
1.05k
    }
164
510
    return 0;
165
510
}
166
167
static expr_ty
168
parse_literal(PyObject *fmt, Py_ssize_t *ppos, PyArena *arena)
169
1.37k
{
170
1.37k
    const void *data = PyUnicode_DATA(fmt);
171
1.37k
    int kind = PyUnicode_KIND(fmt);
172
1.37k
    Py_ssize_t size = PyUnicode_GET_LENGTH(fmt);
173
1.37k
    Py_ssize_t start, pos;
174
1.37k
    int has_percents = 0;
175
1.37k
    start = pos = *ppos;
176
9.83k
    while (pos < size) {
177
9.42k
        if (PyUnicode_READ(kind, data, pos) != '%') {
178
8.46k
            pos++;
179
8.46k
        }
180
966
        else if (pos+1 < size && PyUnicode_READ(kind, data, pos+1) == '%') {
181
2
            has_percents = 1;
182
2
            pos += 2;
183
2
        }
184
964
        else {
185
964
            break;
186
964
        }
187
9.42k
    }
188
1.37k
    *ppos = pos;
189
1.37k
    if (pos == start) {
190
579
        return NULL;
191
579
    }
192
798
    PyObject *str = PyUnicode_Substring(fmt, start, pos);
193
    /* str = str.replace('%%', '%') */
194
798
    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
798
    if (!str) {
200
0
        return NULL;
201
0
    }
202
203
798
    if (_PyArena_AddPyObject(arena, str) < 0) {
204
0
        Py_DECREF(str);
205
0
        return NULL;
206
0
    }
207
798
    return _PyAST_Constant(str, NULL, -1, -1, -1, -1, arena);
208
798
}
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
964
{
216
964
    Py_ssize_t pos = *ppos, len = PyUnicode_GET_LENGTH(fmt);
217
964
    Py_UCS4 ch;
218
219
1.03k
#define NEXTC do {                      \
220
1.03k
    if (pos >= len) {                   \
221
0
        return 0;                       \
222
0
    }                                   \
223
1.03k
    ch = PyUnicode_READ_CHAR(fmt, pos); \
224
1.03k
    pos++;                              \
225
1.03k
} while (0)
226
227
964
    *flags = 0;
228
1.00k
    while (1) {
229
1.00k
        NEXTC;
230
1.00k
        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
1.00k
        }
237
964
        break;
238
1.00k
    }
239
964
    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
961
    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
961
    *spec = ch;
266
961
    *ppos = pos;
267
961
    return 1;
268
269
961
#undef NEXTC
270
961
}
271
272
static expr_ty
273
parse_format(PyObject *fmt, Py_ssize_t *ppos, expr_ty arg, PyArena *arena)
274
964
{
275
964
    int spec, flags, width = -1, prec = -1;
276
964
    if (!simple_format_arg_parse(fmt, ppos, &spec, &flags, &width, &prec)) {
277
        // Unsupported format.
278
3
        return NULL;
279
3
    }
280
961
    if (spec == 's' || spec == 'r' || spec == 'a') {
281
867
        char buf[1 + MAXDIGITS + 1 + MAXDIGITS + 1], *p = buf;
282
867
        if (!(flags & F_LJUST) && width > 0) {
283
0
            *p++ = '>';
284
0
        }
285
867
        if (width >= 0) {
286
6
            p += snprintf(p, MAXDIGITS + 1, "%d", width);
287
6
        }
288
867
        if (prec >= 0) {
289
1
            p += snprintf(p, MAXDIGITS + 2, ".%d", prec);
290
1
        }
291
867
        expr_ty format_spec = NULL;
292
867
        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
867
        return _PyAST_FormattedValue(arg, spec, format_spec,
307
867
                                     arg->lineno, arg->col_offset,
308
867
                                     arg->end_lineno, arg->end_col_offset,
309
867
                                     arena);
310
867
    }
311
    // Unsupported format.
312
94
    return NULL;
313
961
}
314
315
static int
316
optimize_format(expr_ty node, PyObject *fmt, asdl_expr_seq *elts, PyArena *arena)
317
510
{
318
510
    Py_ssize_t pos = 0;
319
510
    Py_ssize_t cnt = 0;
320
510
    asdl_expr_seq *seq = _Py_asdl_expr_seq_new(asdl_seq_LEN(elts) * 2 + 1, arena);
321
510
    if (!seq) {
322
0
        return 0;
323
0
    }
324
510
    seq->size = 0;
325
326
1.37k
    while (1) {
327
1.37k
        expr_ty lit = parse_literal(fmt, &pos, arena);
328
1.37k
        if (lit) {
329
798
            asdl_seq_SET(seq, seq->size++, lit);
330
798
        }
331
579
        else if (PyErr_Occurred()) {
332
0
            return 0;
333
0
        }
334
335
1.37k
        if (pos >= PyUnicode_GET_LENGTH(fmt)) {
336
413
            break;
337
413
        }
338
964
        if (cnt >= asdl_seq_LEN(elts)) {
339
            // More format units than items.
340
0
            return 1;
341
0
        }
342
964
        assert(PyUnicode_READ_CHAR(fmt, pos) == '%');
343
964
        pos++;
344
964
        expr_ty expr = parse_format(fmt, &pos, asdl_seq_GET(elts, cnt), arena);
345
964
        cnt++;
346
964
        if (!expr) {
347
97
            return !PyErr_Occurred();
348
97
        }
349
867
        asdl_seq_SET(seq, seq->size++, expr);
350
867
    }
351
413
    if (cnt < asdl_seq_LEN(elts)) {
352
        // More items than format units.
353
0
        return 1;
354
0
    }
355
413
    expr_ty res = _PyAST_JoinedStr(seq,
356
413
                                   node->lineno, node->col_offset,
357
413
                                   node->end_lineno, node->end_col_offset,
358
413
                                   arena);
359
413
    if (!res) {
360
0
        return 0;
361
0
    }
362
413
    COPY_NODE(node, res);
363
//     PySys_FormatStderr("format = %R\n", fmt);
364
413
    return 1;
365
413
}
366
367
static int
368
fold_binop(expr_ty node, PyArena *arena, _PyASTPreprocessState *state)
369
27.6k
{
370
27.6k
    if (state->syntax_check_only) {
371
23.2k
        return 1;
372
23.2k
    }
373
4.38k
    expr_ty lhs, rhs;
374
4.38k
    lhs = node->v.BinOp.left;
375
4.38k
    rhs = node->v.BinOp.right;
376
4.38k
    if (lhs->kind != Constant_kind) {
377
3.05k
        return 1;
378
3.05k
    }
379
1.33k
    PyObject *lv = lhs->v.Constant.value;
380
381
1.33k
    if (node->v.BinOp.op == Mod &&
382
944
        rhs->kind == Tuple_kind &&
383
1.33k
        PyUnicode_Check(lv) &&
384
510
        !has_starred(rhs->v.Tuple.elts))
385
510
    {
386
510
        return optimize_format(node, lv, rhs->v.Tuple.elts, arena);
387
510
    }
388
389
820
    return 1;
390
1.33k
}
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
456k
    if (!FUNC((ARG), ctx_, state)) \
407
456k
        return 0;
408
409
#define CALL_OPT(FUNC, TYPE, ARG) \
410
106k
    if ((ARG) != NULL && !FUNC((ARG), ctx_, state)) \
411
106k
        return 0;
412
413
244k
#define CALL_SEQ(FUNC, TYPE, ARG) { \
414
244k
    Py_ssize_t i; \
415
244k
    asdl_ ## TYPE ## _seq *seq = (ARG); /* avoid variable capture */ \
416
572k
    for (i = 0; i < asdl_seq_LEN(seq); i++) { \
417
328k
        TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
418
328k
        if (elt != NULL && !FUNC(elt, ctx_, state)) \
419
328k
            return 0; \
420
328k
    } \
421
244k
}
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
16.2k
{
466
16.2k
    int docstring = _PyAST_GetDocString(stmts) != NULL;
467
16.2k
    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
16.2k
    CALL_SEQ(astfold_stmt, stmt, stmts);
475
16.2k
    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
16.2k
    return 1;
491
16.2k
}
492
493
static int
494
astfold_mod(mod_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
495
7.10k
{
496
7.10k
    switch (node_->kind) {
497
7.04k
    case Module_kind:
498
7.04k
        CALL(astfold_body, asdl_seq, node_->v.Module.body);
499
7.04k
        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
7.10k
    }
512
7.10k
    return 1;
513
7.10k
}
514
515
static int
516
astfold_expr(expr_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
517
589k
{
518
589k
    ENTER_RECURSIVE();
519
589k
    switch (node_->kind) {
520
2.43k
    case BoolOp_kind:
521
2.43k
        CALL_SEQ(astfold_expr, expr, node_->v.BoolOp.values);
522
2.43k
        break;
523
27.6k
    case BinOp_kind:
524
27.6k
        CALL(astfold_expr, expr_ty, node_->v.BinOp.left);
525
27.6k
        CALL(astfold_expr, expr_ty, node_->v.BinOp.right);
526
27.6k
        CALL(fold_binop, expr_ty, node_);
527
27.6k
        break;
528
163k
    case UnaryOp_kind:
529
163k
        CALL(astfold_expr, expr_ty, node_->v.UnaryOp.operand);
530
163k
        break;
531
1.48k
    case Lambda_kind:
532
1.48k
        CALL(astfold_arguments, arguments_ty, node_->v.Lambda.args);
533
1.48k
        CALL(astfold_expr, expr_ty, node_->v.Lambda.body);
534
1.48k
        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.84k
    case Dict_kind:
541
1.84k
        CALL_SEQ(astfold_expr, expr, node_->v.Dict.keys);
542
1.84k
        CALL_SEQ(astfold_expr, expr, node_->v.Dict.values);
543
1.84k
        break;
544
497
    case Set_kind:
545
497
        CALL_SEQ(astfold_expr, expr, node_->v.Set.elts);
546
497
        break;
547
568
    case ListComp_kind:
548
568
        CALL(astfold_expr, expr_ty, node_->v.ListComp.elt);
549
568
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.ListComp.generators);
550
568
        break;
551
142
    case SetComp_kind:
552
142
        CALL(astfold_expr, expr_ty, node_->v.SetComp.elt);
553
142
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.SetComp.generators);
554
142
        break;
555
622
    case DictComp_kind:
556
622
        CALL(astfold_expr, expr_ty, node_->v.DictComp.key);
557
622
        CALL(astfold_expr, expr_ty, node_->v.DictComp.value);
558
622
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.DictComp.generators);
559
622
        break;
560
654
    case GeneratorExp_kind:
561
654
        CALL(astfold_expr, expr_ty, node_->v.GeneratorExp.elt);
562
654
        CALL_SEQ(astfold_comprehension, comprehension, node_->v.GeneratorExp.generators);
563
654
        break;
564
205
    case Await_kind:
565
205
        CALL(astfold_expr, expr_ty, node_->v.Await.value);
566
205
        break;
567
1.10k
    case Yield_kind:
568
1.10k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Yield.value);
569
1.10k
        break;
570
99
    case YieldFrom_kind:
571
99
        CALL(astfold_expr, expr_ty, node_->v.YieldFrom.value);
572
99
        break;
573
9.87k
    case Compare_kind:
574
9.87k
        CALL(astfold_expr, expr_ty, node_->v.Compare.left);
575
9.87k
        CALL_SEQ(astfold_expr, expr, node_->v.Compare.comparators);
576
9.87k
        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.5k
    case FormattedValue_kind:
583
14.5k
        CALL(astfold_expr, expr_ty, node_->v.FormattedValue.value);
584
14.5k
        CALL_OPT(astfold_expr, expr_ty, node_->v.FormattedValue.format_spec);
585
14.5k
        break;
586
1.26k
    case Interpolation_kind:
587
1.26k
        CALL(astfold_expr, expr_ty, node_->v.Interpolation.value);
588
1.26k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Interpolation.format_spec);
589
1.26k
        break;
590
7.26k
    case JoinedStr_kind:
591
7.26k
        CALL_SEQ(astfold_expr, expr, node_->v.JoinedStr.values);
592
7.26k
        break;
593
285
    case TemplateStr_kind:
594
285
        CALL_SEQ(astfold_expr, expr, node_->v.TemplateStr.values);
595
285
        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.78k
    case Subscript_kind:
600
4.78k
        CALL(astfold_expr, expr_ty, node_->v.Subscript.value);
601
4.78k
        CALL(astfold_expr, expr_ty, node_->v.Subscript.slice);
602
4.78k
        break;
603
956
    case Starred_kind:
604
956
        CALL(astfold_expr, expr_ty, node_->v.Starred.value);
605
956
        break;
606
3.45k
    case Slice_kind:
607
3.45k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.lower);
608
3.45k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.upper);
609
3.45k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Slice.step);
610
3.45k
        break;
611
3.19k
    case List_kind:
612
3.19k
        CALL_SEQ(astfold_expr, expr, node_->v.List.elts);
613
3.19k
        break;
614
12.7k
    case Tuple_kind:
615
12.7k
        CALL_SEQ(astfold_expr, expr, node_->v.Tuple.elts);
616
12.7k
        break;
617
160k
    case Name_kind:
618
160k
        if (state->syntax_check_only) {
619
69.4k
            break;
620
69.4k
        }
621
91.2k
        if (node_->v.Name.ctx == Load &&
622
75.0k
                _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
91.2k
        break;
627
91.2k
    case NamedExpr_kind:
628
99
        CALL(astfold_expr, expr_ty, node_->v.NamedExpr.value);
629
99
        break;
630
116k
    case Constant_kind:
631
        // Already a constant, nothing further to do
632
116k
        break;
633
    // No default case, so the compiler will emit a warning if new expression
634
    // kinds are added without being handled here
635
589k
    }
636
589k
    LEAVE_RECURSIVE();
637
589k
    return 1;
638
589k
}
639
640
static int
641
astfold_keyword(keyword_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
642
5.13k
{
643
5.13k
    CALL(astfold_expr, expr_ty, node_->value);
644
5.13k
    return 1;
645
5.13k
}
646
647
static int
648
astfold_comprehension(comprehension_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
649
2.11k
{
650
2.11k
    CALL(astfold_expr, expr_ty, node_->target);
651
2.11k
    CALL(astfold_expr, expr_ty, node_->iter);
652
2.11k
    CALL_SEQ(astfold_expr, expr, node_->ifs);
653
2.11k
    return 1;
654
2.11k
}
655
656
static int
657
astfold_arguments(arguments_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
658
8.67k
{
659
8.67k
    CALL_SEQ(astfold_arg, arg, node_->posonlyargs);
660
8.67k
    CALL_SEQ(astfold_arg, arg, node_->args);
661
8.67k
    CALL_OPT(astfold_arg, arg_ty, node_->vararg);
662
8.67k
    CALL_SEQ(astfold_arg, arg, node_->kwonlyargs);
663
8.67k
    CALL_SEQ(astfold_expr, expr, node_->kw_defaults);
664
8.67k
    CALL_OPT(astfold_arg, arg_ty, node_->kwarg);
665
8.67k
    CALL_SEQ(astfold_expr, expr, node_->defaults);
666
8.67k
    return 1;
667
8.67k
}
668
669
static int
670
astfold_arg(arg_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
671
24.5k
{
672
24.5k
    if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
673
23.8k
        CALL_OPT(astfold_expr, expr_ty, node_->annotation);
674
23.8k
    }
675
24.5k
    return 1;
676
24.5k
}
677
678
static int
679
astfold_stmt(stmt_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
680
99.5k
{
681
99.5k
    ENTER_RECURSIVE();
682
99.5k
    switch (node_->kind) {
683
6.80k
    case FunctionDef_kind: {
684
6.80k
        CALL_SEQ(astfold_type_param, type_param, node_->v.FunctionDef.type_params);
685
6.80k
        CALL(astfold_arguments, arguments_ty, node_->v.FunctionDef.args);
686
6.80k
        BEFORE_FUNC_BODY(state, node_);
687
6.80k
        CALL(astfold_body, asdl_seq, node_->v.FunctionDef.body);
688
6.80k
        AFTER_FUNC_BODY(state);
689
6.80k
        CALL_SEQ(astfold_expr, expr, node_->v.FunctionDef.decorator_list);
690
6.80k
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
691
6.61k
            CALL_OPT(astfold_expr, expr_ty, node_->v.FunctionDef.returns);
692
6.61k
        }
693
6.80k
        break;
694
6.80k
    }
695
6.80k
    case AsyncFunctionDef_kind: {
696
383
        CALL_SEQ(astfold_type_param, type_param, node_->v.AsyncFunctionDef.type_params);
697
383
        CALL(astfold_arguments, arguments_ty, node_->v.AsyncFunctionDef.args);
698
383
        BEFORE_FUNC_BODY(state, node_);
699
383
        CALL(astfold_body, asdl_seq, node_->v.AsyncFunctionDef.body);
700
383
        AFTER_FUNC_BODY(state);
701
383
        CALL_SEQ(astfold_expr, expr, node_->v.AsyncFunctionDef.decorator_list);
702
383
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
703
317
            CALL_OPT(astfold_expr, expr_ty, node_->v.AsyncFunctionDef.returns);
704
317
        }
705
383
        break;
706
383
    }
707
2.01k
    case ClassDef_kind:
708
2.01k
        CALL_SEQ(astfold_type_param, type_param, node_->v.ClassDef.type_params);
709
2.01k
        CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.bases);
710
2.01k
        CALL_SEQ(astfold_keyword, keyword, node_->v.ClassDef.keywords);
711
2.01k
        CALL(astfold_body, asdl_seq, node_->v.ClassDef.body);
712
2.01k
        CALL_SEQ(astfold_expr, expr, node_->v.ClassDef.decorator_list);
713
2.01k
        break;
714
8.17k
    case Return_kind:
715
8.17k
        BEFORE_RETURN(state, node_);
716
8.17k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Return.value);
717
8.17k
        break;
718
657
    case Delete_kind:
719
657
        CALL_SEQ(astfold_expr, expr, node_->v.Delete.targets);
720
657
        break;
721
15.2k
    case Assign_kind:
722
15.2k
        CALL_SEQ(astfold_expr, expr, node_->v.Assign.targets);
723
15.2k
        CALL(astfold_expr, expr_ty, node_->v.Assign.value);
724
15.2k
        break;
725
986
    case AugAssign_kind:
726
986
        CALL(astfold_expr, expr_ty, node_->v.AugAssign.target);
727
986
        CALL(astfold_expr, expr_ty, node_->v.AugAssign.value);
728
986
        break;
729
1.15k
    case AnnAssign_kind:
730
1.15k
        CALL(astfold_expr, expr_ty, node_->v.AnnAssign.target);
731
1.15k
        if (!(state->ff_features & CO_FUTURE_ANNOTATIONS)) {
732
1.08k
            CALL(astfold_expr, expr_ty, node_->v.AnnAssign.annotation);
733
1.08k
        }
734
1.15k
        CALL_OPT(astfold_expr, expr_ty, node_->v.AnnAssign.value);
735
1.15k
        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.37k
    case For_kind: {
742
1.37k
        CALL(astfold_expr, expr_ty, node_->v.For.target);
743
1.37k
        CALL(astfold_expr, expr_ty, node_->v.For.iter);
744
1.37k
        BEFORE_LOOP_BODY(state, node_);
745
1.37k
        CALL_SEQ(astfold_stmt, stmt, node_->v.For.body);
746
1.37k
        AFTER_LOOP_BODY(state);
747
1.37k
        CALL_SEQ(astfold_stmt, stmt, node_->v.For.orelse);
748
1.37k
        break;
749
1.37k
    }
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
605
    case While_kind: {
760
605
        CALL(astfold_expr, expr_ty, node_->v.While.test);
761
605
        BEFORE_LOOP_BODY(state, node_);
762
605
        CALL_SEQ(astfold_stmt, stmt, node_->v.While.body);
763
605
        AFTER_LOOP_BODY(state);
764
605
        CALL_SEQ(astfold_stmt, stmt, node_->v.While.orelse);
765
605
        break;
766
605
    }
767
8.72k
    case If_kind:
768
8.72k
        CALL(astfold_expr, expr_ty, node_->v.If.test);
769
8.72k
        CALL_SEQ(astfold_stmt, stmt, node_->v.If.body);
770
8.72k
        CALL_SEQ(astfold_stmt, stmt, node_->v.If.orelse);
771
8.72k
        break;
772
425
    case With_kind:
773
425
        CALL_SEQ(astfold_withitem, withitem, node_->v.With.items);
774
425
        CALL_SEQ(astfold_stmt, stmt, node_->v.With.body);
775
425
        break;
776
160
    case AsyncWith_kind:
777
160
        CALL_SEQ(astfold_withitem, withitem, node_->v.AsyncWith.items);
778
160
        CALL_SEQ(astfold_stmt, stmt, node_->v.AsyncWith.body);
779
160
        break;
780
2.55k
    case Raise_kind:
781
2.55k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Raise.exc);
782
2.55k
        CALL_OPT(astfold_expr, expr_ty, node_->v.Raise.cause);
783
2.55k
        break;
784
1.62k
    case Try_kind: {
785
1.62k
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.body);
786
1.62k
        CALL_SEQ(astfold_excepthandler, excepthandler, node_->v.Try.handlers);
787
1.62k
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.orelse);
788
1.62k
        BEFORE_FINALLY(state, node_);
789
1.62k
        CALL_SEQ(astfold_stmt, stmt, node_->v.Try.finalbody);
790
1.62k
        AFTER_FINALLY(state);
791
1.62k
        break;
792
1.62k
    }
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
409
    case Assert_kind:
803
409
        CALL(astfold_expr, expr_ty, node_->v.Assert.test);
804
409
        CALL_OPT(astfold_expr, expr_ty, node_->v.Assert.msg);
805
409
        break;
806
42.3k
    case Expr_kind:
807
42.3k
        CALL(astfold_expr, expr_ty, node_->v.Expr.value);
808
42.3k
        break;
809
276
    case Match_kind:
810
276
        CALL(astfold_expr, expr_ty, node_->v.Match.subject);
811
276
        CALL_SEQ(astfold_match_case, match_case, node_->v.Match.cases);
812
276
        break;
813
707
    case Break_kind:
814
707
        BEFORE_LOOP_EXIT(state, node_, "break");
815
707
        break;
816
460
    case Continue_kind:
817
460
        BEFORE_LOOP_EXIT(state, node_, "continue");
818
460
        break;
819
    // The following statements don't contain any subexpressions to be folded
820
1.39k
    case Import_kind:
821
2.63k
    case ImportFrom_kind:
822
2.88k
    case Global_kind:
823
3.17k
    case Nonlocal_kind:
824
3.86k
    case Pass_kind:
825
3.86k
        break;
826
    // No default case, so the compiler will emit a warning if new statement
827
    // kinds are added without being handled here
828
99.5k
    }
829
99.5k
    LEAVE_RECURSIVE();
830
99.5k
    return 1;
831
99.5k
}
832
833
static int
834
astfold_excepthandler(excepthandler_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
835
2.14k
{
836
2.14k
    switch (node_->kind) {
837
2.14k
    case ExceptHandler_kind:
838
2.14k
        CALL_OPT(astfold_expr, expr_ty, node_->v.ExceptHandler.type);
839
2.14k
        CALL_SEQ(astfold_stmt, stmt, node_->v.ExceptHandler.body);
840
2.14k
        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.14k
    }
844
2.14k
    return 1;
845
2.14k
}
846
847
static int
848
astfold_withitem(withitem_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
849
1.93k
{
850
1.93k
    CALL(astfold_expr, expr_ty, node_->context_expr);
851
1.93k
    CALL_OPT(astfold_expr, expr_ty, node_->optional_vars);
852
1.93k
    return 1;
853
1.93k
}
854
855
static int
856
fold_const_match_patterns(expr_ty node, PyArena *ctx_, _PyASTPreprocessState *state)
857
1.29k
{
858
1.29k
    if (state->syntax_check_only) {
859
1.28k
        return 1;
860
1.28k
    }
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
16.8k
{
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
16.8k
    ENTER_RECURSIVE();
903
16.8k
    switch (node_->kind) {
904
861
        case MatchValue_kind:
905
861
            CALL(fold_const_match_patterns, expr_ty, node_->v.MatchValue.value);
906
861
            break;
907
88
        case MatchSingleton_kind:
908
88
            break;
909
799
        case MatchSequence_kind:
910
799
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchSequence.patterns);
911
799
            break;
912
1.36k
        case MatchMapping_kind:
913
1.36k
            CALL_SEQ(fold_const_match_patterns, expr, node_->v.MatchMapping.keys);
914
1.36k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchMapping.patterns);
915
1.36k
            break;
916
1.90k
        case MatchClass_kind:
917
1.90k
            CALL(astfold_expr, expr_ty, node_->v.MatchClass.cls);
918
1.90k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchClass.patterns);
919
1.90k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchClass.kwd_patterns);
920
1.90k
            break;
921
474
        case MatchStar_kind:
922
474
            break;
923
8.72k
        case MatchAs_kind:
924
8.72k
            if (node_->v.MatchAs.pattern) {
925
82
                CALL(astfold_pattern, pattern_ty, node_->v.MatchAs.pattern);
926
82
            }
927
8.72k
            break;
928
8.72k
        case MatchOr_kind:
929
2.58k
            CALL_SEQ(astfold_pattern, pattern, node_->v.MatchOr.patterns);
930
2.58k
            break;
931
    // No default case, so the compiler will emit a warning if new pattern
932
    // kinds are added without being handled here
933
16.8k
    }
934
16.8k
    LEAVE_RECURSIVE();
935
16.8k
    return 1;
936
16.8k
}
937
938
static int
939
astfold_match_case(match_case_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
940
1.25k
{
941
1.25k
    CALL(astfold_pattern, expr_ty, node_->pattern);
942
1.25k
    CALL_OPT(astfold_expr, expr_ty, node_->guard);
943
1.25k
    CALL_SEQ(astfold_stmt, stmt, node_->body);
944
1.25k
    return 1;
945
1.25k
}
946
947
static int
948
astfold_type_param(type_param_ty node_, PyArena *ctx_, _PyASTPreprocessState *state)
949
6.16k
{
950
6.16k
    switch (node_->kind) {
951
5.00k
        case TypeVar_kind:
952
5.00k
            CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVar.bound);
953
5.00k
            CALL_OPT(astfold_expr, expr_ty, node_->v.TypeVar.default_value);
954
5.00k
            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.16k
    }
962
6.16k
    return 1;
963
6.16k
}
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
7.10k
{
973
7.10k
    _PyASTPreprocessState state;
974
7.10k
    memset(&state, 0, sizeof(_PyASTPreprocessState));
975
7.10k
    state.filename = filename;
976
7.10k
    state.optimize = optimize;
977
7.10k
    state.ff_features = ff_features;
978
7.10k
    state.syntax_check_only = syntax_check_only;
979
7.10k
    if (_Py_CArray_Init(&state.cf_finally, sizeof(ControlFlowInFinallyContext), 20) < 0) {
980
0
        return -1;
981
0
    }
982
983
7.10k
    int ret = astfold_mod(mod, arena, &state);
984
7.10k
    assert(ret || PyErr_Occurred());
985
986
7.10k
    _Py_CArray_Fini(&state.cf_finally);
987
7.10k
    return ret;
988
7.10k
}