Coverage Report

Created: 2025-11-02 06:30

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