Coverage Report

Created: 2025-07-04 06:49

/src/cpython/Python/ast.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * This file exposes PyAST_Validate interface to check the integrity
3
 * of the given abstract syntax tree (potentially constructed manually).
4
 */
5
#include "Python.h"
6
#include "pycore_ast.h"           // asdl_stmt_seq
7
#include "pycore_pystate.h"       // _PyThreadState_GET()
8
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString()
9
10
#include <stdbool.h>              // bool
11
12
13
0
#define ENTER_RECURSIVE() \
14
0
if (Py_EnterRecursiveCall(" during compilation")) { \
15
0
    return 0; \
16
0
}
17
18
0
#define LEAVE_RECURSIVE() Py_LeaveRecursiveCall();
19
20
static int validate_stmts(asdl_stmt_seq *);
21
static int validate_exprs(asdl_expr_seq *, expr_context_ty, int);
22
static int validate_patterns(asdl_pattern_seq *, int);
23
static int validate_type_params(asdl_type_param_seq *);
24
static int _validate_nonempty_seq(asdl_seq *, const char *, const char *);
25
static int validate_stmt(stmt_ty);
26
static int validate_expr(expr_ty, expr_context_ty);
27
static int validate_pattern(pattern_ty, int);
28
static int validate_typeparam(type_param_ty);
29
30
#define VALIDATE_POSITIONS(node) \
31
0
    if (node->lineno > node->end_lineno) { \
32
0
        PyErr_Format(PyExc_ValueError, \
33
0
                     "AST node line range (%d, %d) is not valid", \
34
0
                     node->lineno, node->end_lineno); \
35
0
        return 0; \
36
0
    } \
37
0
    if ((node->lineno < 0 && node->end_lineno != node->lineno) || \
38
0
        (node->col_offset < 0 && node->col_offset != node->end_col_offset)) { \
39
0
        PyErr_Format(PyExc_ValueError, \
40
0
                     "AST node column range (%d, %d) for line range (%d, %d) is not valid", \
41
0
                     node->col_offset, node->end_col_offset, node->lineno, node->end_lineno); \
42
0
        return 0; \
43
0
    } \
44
0
    if (node->lineno == node->end_lineno && node->col_offset > node->end_col_offset) { \
45
0
        PyErr_Format(PyExc_ValueError, \
46
0
                     "line %d, column %d-%d is not a valid range", \
47
0
                     node->lineno, node->col_offset, node->end_col_offset); \
48
0
        return 0; \
49
0
    }
50
51
static int
52
validate_name(PyObject *name)
53
0
{
54
0
    assert(!PyErr_Occurred());
55
0
    assert(PyUnicode_Check(name));
56
0
    static const char * const forbidden[] = {
57
0
        "None",
58
0
        "True",
59
0
        "False",
60
0
        NULL
61
0
    };
62
0
    for (int i = 0; forbidden[i] != NULL; i++) {
63
0
        if (_PyUnicode_EqualToASCIIString(name, forbidden[i])) {
64
0
            PyErr_Format(PyExc_ValueError, "identifier field can't represent '%s' constant", forbidden[i]);
65
0
            return 0;
66
0
        }
67
0
    }
68
0
    return 1;
69
0
}
70
71
static int
72
validate_comprehension(asdl_comprehension_seq *gens)
73
0
{
74
0
    assert(!PyErr_Occurred());
75
0
    if (!asdl_seq_LEN(gens)) {
76
0
        PyErr_SetString(PyExc_ValueError, "comprehension with no generators");
77
0
        return 0;
78
0
    }
79
0
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(gens); i++) {
80
0
        comprehension_ty comp = asdl_seq_GET(gens, i);
81
0
        if (!validate_expr(comp->target, Store) ||
82
0
            !validate_expr(comp->iter, Load) ||
83
0
            !validate_exprs(comp->ifs, Load, 0))
84
0
            return 0;
85
0
    }
86
0
    return 1;
87
0
}
88
89
static int
90
validate_keywords(asdl_keyword_seq *keywords)
91
0
{
92
0
    assert(!PyErr_Occurred());
93
0
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(keywords); i++)
94
0
        if (!validate_expr((asdl_seq_GET(keywords, i))->value, Load))
95
0
            return 0;
96
0
    return 1;
97
0
}
98
99
static int
100
validate_args(asdl_arg_seq *args)
101
0
{
102
0
    assert(!PyErr_Occurred());
103
0
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(args); i++) {
104
0
        arg_ty arg = asdl_seq_GET(args, i);
105
0
        VALIDATE_POSITIONS(arg);
106
0
        if (arg->annotation && !validate_expr(arg->annotation, Load))
107
0
            return 0;
108
0
    }
109
0
    return 1;
110
0
}
111
112
static const char *
113
expr_context_name(expr_context_ty ctx)
114
0
{
115
0
    switch (ctx) {
116
0
    case Load:
117
0
        return "Load";
118
0
    case Store:
119
0
        return "Store";
120
0
    case Del:
121
0
        return "Del";
122
    // No default case so compiler emits warning for unhandled cases
123
0
    }
124
0
    Py_UNREACHABLE();
125
0
}
126
127
static int
128
validate_arguments(arguments_ty args)
129
0
{
130
0
    assert(!PyErr_Occurred());
131
0
    if (!validate_args(args->posonlyargs) || !validate_args(args->args)) {
132
0
        return 0;
133
0
    }
134
0
    if (args->vararg && args->vararg->annotation
135
0
        && !validate_expr(args->vararg->annotation, Load)) {
136
0
            return 0;
137
0
    }
138
0
    if (!validate_args(args->kwonlyargs))
139
0
        return 0;
140
0
    if (args->kwarg && args->kwarg->annotation
141
0
        && !validate_expr(args->kwarg->annotation, Load)) {
142
0
            return 0;
143
0
    }
144
0
    if (asdl_seq_LEN(args->defaults) > asdl_seq_LEN(args->posonlyargs) + asdl_seq_LEN(args->args)) {
145
0
        PyErr_SetString(PyExc_ValueError, "more positional defaults than args on arguments");
146
0
        return 0;
147
0
    }
148
0
    if (asdl_seq_LEN(args->kw_defaults) != asdl_seq_LEN(args->kwonlyargs)) {
149
0
        PyErr_SetString(PyExc_ValueError, "length of kwonlyargs is not the same as "
150
0
                        "kw_defaults on arguments");
151
0
        return 0;
152
0
    }
153
0
    return validate_exprs(args->defaults, Load, 0) && validate_exprs(args->kw_defaults, Load, 1);
154
0
}
155
156
static int
157
validate_constant(PyObject *value)
158
0
{
159
0
    assert(!PyErr_Occurred());
160
0
    if (value == Py_None || value == Py_Ellipsis)
161
0
        return 1;
162
163
0
    if (PyLong_CheckExact(value)
164
0
            || PyFloat_CheckExact(value)
165
0
            || PyComplex_CheckExact(value)
166
0
            || PyBool_Check(value)
167
0
            || PyUnicode_CheckExact(value)
168
0
            || PyBytes_CheckExact(value))
169
0
        return 1;
170
171
0
    if (PyTuple_CheckExact(value) || PyFrozenSet_CheckExact(value)) {
172
0
        ENTER_RECURSIVE();
173
174
0
        PyObject *it = PyObject_GetIter(value);
175
0
        if (it == NULL)
176
0
            return 0;
177
178
0
        while (1) {
179
0
            PyObject *item = PyIter_Next(it);
180
0
            if (item == NULL) {
181
0
                if (PyErr_Occurred()) {
182
0
                    Py_DECREF(it);
183
0
                    return 0;
184
0
                }
185
0
                break;
186
0
            }
187
188
0
            if (!validate_constant(item)) {
189
0
                Py_DECREF(it);
190
0
                Py_DECREF(item);
191
0
                return 0;
192
0
            }
193
0
            Py_DECREF(item);
194
0
        }
195
196
0
        Py_DECREF(it);
197
0
        LEAVE_RECURSIVE();
198
0
        return 1;
199
0
    }
200
201
0
    if (!PyErr_Occurred()) {
202
0
        PyErr_Format(PyExc_TypeError,
203
0
                     "got an invalid type in Constant: %s",
204
0
                     _PyType_Name(Py_TYPE(value)));
205
0
    }
206
0
    return 0;
207
0
}
208
209
static int
210
validate_expr(expr_ty exp, expr_context_ty ctx)
211
0
{
212
0
    assert(!PyErr_Occurred());
213
0
    VALIDATE_POSITIONS(exp);
214
0
    int ret = -1;
215
0
    ENTER_RECURSIVE();
216
0
    int check_ctx = 1;
217
0
    expr_context_ty actual_ctx;
218
219
    /* First check expression context. */
220
0
    switch (exp->kind) {
221
0
    case Attribute_kind:
222
0
        actual_ctx = exp->v.Attribute.ctx;
223
0
        break;
224
0
    case Subscript_kind:
225
0
        actual_ctx = exp->v.Subscript.ctx;
226
0
        break;
227
0
    case Starred_kind:
228
0
        actual_ctx = exp->v.Starred.ctx;
229
0
        break;
230
0
    case Name_kind:
231
0
        if (!validate_name(exp->v.Name.id)) {
232
0
            return 0;
233
0
        }
234
0
        actual_ctx = exp->v.Name.ctx;
235
0
        break;
236
0
    case List_kind:
237
0
        actual_ctx = exp->v.List.ctx;
238
0
        break;
239
0
    case Tuple_kind:
240
0
        actual_ctx = exp->v.Tuple.ctx;
241
0
        break;
242
0
    default:
243
0
        if (ctx != Load) {
244
0
            PyErr_Format(PyExc_ValueError, "expression which can't be "
245
0
                         "assigned to in %s context", expr_context_name(ctx));
246
0
            return 0;
247
0
        }
248
0
        check_ctx = 0;
249
        /* set actual_ctx to prevent gcc warning */
250
0
        actual_ctx = 0;
251
0
    }
252
0
    if (check_ctx && actual_ctx != ctx) {
253
0
        PyErr_Format(PyExc_ValueError, "expression must have %s context but has %s instead",
254
0
                     expr_context_name(ctx), expr_context_name(actual_ctx));
255
0
        return 0;
256
0
    }
257
258
    /* Now validate expression. */
259
0
    switch (exp->kind) {
260
0
    case BoolOp_kind:
261
0
        if (asdl_seq_LEN(exp->v.BoolOp.values) < 2) {
262
0
            PyErr_SetString(PyExc_ValueError, "BoolOp with less than 2 values");
263
0
            return 0;
264
0
        }
265
0
        ret = validate_exprs(exp->v.BoolOp.values, Load, 0);
266
0
        break;
267
0
    case BinOp_kind:
268
0
        ret = validate_expr(exp->v.BinOp.left, Load) &&
269
0
            validate_expr(exp->v.BinOp.right, Load);
270
0
        break;
271
0
    case UnaryOp_kind:
272
0
        ret = validate_expr(exp->v.UnaryOp.operand, Load);
273
0
        break;
274
0
    case Lambda_kind:
275
0
        ret = validate_arguments(exp->v.Lambda.args) &&
276
0
            validate_expr(exp->v.Lambda.body, Load);
277
0
        break;
278
0
    case IfExp_kind:
279
0
        ret = validate_expr(exp->v.IfExp.test, Load) &&
280
0
            validate_expr(exp->v.IfExp.body, Load) &&
281
0
            validate_expr(exp->v.IfExp.orelse, Load);
282
0
        break;
283
0
    case Dict_kind:
284
0
        if (asdl_seq_LEN(exp->v.Dict.keys) != asdl_seq_LEN(exp->v.Dict.values)) {
285
0
            PyErr_SetString(PyExc_ValueError,
286
0
                            "Dict doesn't have the same number of keys as values");
287
0
            return 0;
288
0
        }
289
        /* null_ok=1 for keys expressions to allow dict unpacking to work in
290
           dict literals, i.e. ``{**{a:b}}`` */
291
0
        ret = validate_exprs(exp->v.Dict.keys, Load, /*null_ok=*/ 1) &&
292
0
            validate_exprs(exp->v.Dict.values, Load, /*null_ok=*/ 0);
293
0
        break;
294
0
    case Set_kind:
295
0
        ret = validate_exprs(exp->v.Set.elts, Load, 0);
296
0
        break;
297
0
#define COMP(NAME) \
298
0
        case NAME ## _kind: \
299
0
            ret = validate_comprehension(exp->v.NAME.generators) && \
300
0
                validate_expr(exp->v.NAME.elt, Load); \
301
0
            break;
302
0
    COMP(ListComp)
303
0
    COMP(SetComp)
304
0
    COMP(GeneratorExp)
305
0
#undef COMP
306
0
    case DictComp_kind:
307
0
        ret = validate_comprehension(exp->v.DictComp.generators) &&
308
0
            validate_expr(exp->v.DictComp.key, Load) &&
309
0
            validate_expr(exp->v.DictComp.value, Load);
310
0
        break;
311
0
    case Yield_kind:
312
0
        ret = !exp->v.Yield.value || validate_expr(exp->v.Yield.value, Load);
313
0
        break;
314
0
    case YieldFrom_kind:
315
0
        ret = validate_expr(exp->v.YieldFrom.value, Load);
316
0
        break;
317
0
    case Await_kind:
318
0
        ret = validate_expr(exp->v.Await.value, Load);
319
0
        break;
320
0
    case Compare_kind:
321
0
        if (!asdl_seq_LEN(exp->v.Compare.comparators)) {
322
0
            PyErr_SetString(PyExc_ValueError, "Compare with no comparators");
323
0
            return 0;
324
0
        }
325
0
        if (asdl_seq_LEN(exp->v.Compare.comparators) !=
326
0
            asdl_seq_LEN(exp->v.Compare.ops)) {
327
0
            PyErr_SetString(PyExc_ValueError, "Compare has a different number "
328
0
                            "of comparators and operands");
329
0
            return 0;
330
0
        }
331
0
        ret = validate_exprs(exp->v.Compare.comparators, Load, 0) &&
332
0
            validate_expr(exp->v.Compare.left, Load);
333
0
        break;
334
0
    case Call_kind:
335
0
        ret = validate_expr(exp->v.Call.func, Load) &&
336
0
            validate_exprs(exp->v.Call.args, Load, 0) &&
337
0
            validate_keywords(exp->v.Call.keywords);
338
0
        break;
339
0
    case Constant_kind:
340
0
        if (!validate_constant(exp->v.Constant.value)) {
341
0
            return 0;
342
0
        }
343
0
        ret = 1;
344
0
        break;
345
0
    case JoinedStr_kind:
346
0
        ret = validate_exprs(exp->v.JoinedStr.values, Load, 0);
347
0
        break;
348
0
    case TemplateStr_kind:
349
0
        ret = validate_exprs(exp->v.TemplateStr.values, Load, 0);
350
0
        break;
351
0
    case FormattedValue_kind:
352
0
        if (validate_expr(exp->v.FormattedValue.value, Load) == 0)
353
0
            return 0;
354
0
        if (exp->v.FormattedValue.format_spec) {
355
0
            ret = validate_expr(exp->v.FormattedValue.format_spec, Load);
356
0
            break;
357
0
        }
358
0
        ret = 1;
359
0
        break;
360
0
    case Interpolation_kind:
361
0
        if (validate_expr(exp->v.Interpolation.value, Load) == 0)
362
0
            return 0;
363
0
        if (exp->v.Interpolation.format_spec) {
364
0
            ret = validate_expr(exp->v.Interpolation.format_spec, Load);
365
0
            break;
366
0
        }
367
0
        ret = 1;
368
0
        break;
369
0
    case Attribute_kind:
370
0
        ret = validate_expr(exp->v.Attribute.value, Load);
371
0
        break;
372
0
    case Subscript_kind:
373
0
        ret = validate_expr(exp->v.Subscript.slice, Load) &&
374
0
            validate_expr(exp->v.Subscript.value, Load);
375
0
        break;
376
0
    case Starred_kind:
377
0
        ret = validate_expr(exp->v.Starred.value, ctx);
378
0
        break;
379
0
    case Slice_kind:
380
0
        ret = (!exp->v.Slice.lower || validate_expr(exp->v.Slice.lower, Load)) &&
381
0
            (!exp->v.Slice.upper || validate_expr(exp->v.Slice.upper, Load)) &&
382
0
            (!exp->v.Slice.step || validate_expr(exp->v.Slice.step, Load));
383
0
        break;
384
0
    case List_kind:
385
0
        ret = validate_exprs(exp->v.List.elts, ctx, 0);
386
0
        break;
387
0
    case Tuple_kind:
388
0
        ret = validate_exprs(exp->v.Tuple.elts, ctx, 0);
389
0
        break;
390
0
    case NamedExpr_kind:
391
0
        if (exp->v.NamedExpr.target->kind != Name_kind) {
392
0
            PyErr_SetString(PyExc_TypeError,
393
0
                            "NamedExpr target must be a Name");
394
0
            return 0;
395
0
        }
396
0
        ret = validate_expr(exp->v.NamedExpr.value, Load);
397
0
        break;
398
    /* This last case doesn't have any checking. */
399
0
    case Name_kind:
400
0
        ret = 1;
401
0
        break;
402
    // No default case so compiler emits warning for unhandled cases
403
0
    }
404
0
    if (ret < 0) {
405
0
        PyErr_SetString(PyExc_SystemError, "unexpected expression");
406
0
        ret = 0;
407
0
    }
408
0
    LEAVE_RECURSIVE();
409
0
    return ret;
410
0
}
411
412
413
// Note: the ensure_literal_* functions are only used to validate a restricted
414
//       set of non-recursive literals that have already been checked with
415
//       validate_expr, so they don't accept the validator state
416
static int
417
ensure_literal_number(expr_ty exp, bool allow_real, bool allow_imaginary)
418
0
{
419
0
    assert(exp->kind == Constant_kind);
420
0
    PyObject *value = exp->v.Constant.value;
421
0
    return (allow_real && PyFloat_CheckExact(value)) ||
422
0
           (allow_real && PyLong_CheckExact(value)) ||
423
0
           (allow_imaginary && PyComplex_CheckExact(value));
424
0
}
425
426
static int
427
ensure_literal_negative(expr_ty exp, bool allow_real, bool allow_imaginary)
428
0
{
429
0
    assert(exp->kind == UnaryOp_kind);
430
    // Must be negation ...
431
0
    if (exp->v.UnaryOp.op != USub) {
432
0
        return 0;
433
0
    }
434
    // ... of a constant ...
435
0
    expr_ty operand = exp->v.UnaryOp.operand;
436
0
    if (operand->kind != Constant_kind) {
437
0
        return 0;
438
0
    }
439
    // ... number
440
0
    return ensure_literal_number(operand, allow_real, allow_imaginary);
441
0
}
442
443
static int
444
ensure_literal_complex(expr_ty exp)
445
0
{
446
0
    assert(exp->kind == BinOp_kind);
447
0
    expr_ty left = exp->v.BinOp.left;
448
0
    expr_ty right = exp->v.BinOp.right;
449
    // Ensure op is addition or subtraction
450
0
    if (exp->v.BinOp.op != Add && exp->v.BinOp.op != Sub) {
451
0
        return 0;
452
0
    }
453
    // Check LHS is a real number (potentially signed)
454
0
    switch (left->kind)
455
0
    {
456
0
        case Constant_kind:
457
0
            if (!ensure_literal_number(left, /*real=*/true, /*imaginary=*/false)) {
458
0
                return 0;
459
0
            }
460
0
            break;
461
0
        case UnaryOp_kind:
462
0
            if (!ensure_literal_negative(left, /*real=*/true, /*imaginary=*/false)) {
463
0
                return 0;
464
0
            }
465
0
            break;
466
0
        default:
467
0
            return 0;
468
0
    }
469
    // Check RHS is an imaginary number (no separate sign allowed)
470
0
    switch (right->kind)
471
0
    {
472
0
        case Constant_kind:
473
0
            if (!ensure_literal_number(right, /*real=*/false, /*imaginary=*/true)) {
474
0
                return 0;
475
0
            }
476
0
            break;
477
0
        default:
478
0
            return 0;
479
0
    }
480
0
    return 1;
481
0
}
482
483
static int
484
validate_pattern_match_value(expr_ty exp)
485
0
{
486
0
    assert(!PyErr_Occurred());
487
0
    if (!validate_expr(exp, Load)) {
488
0
        return 0;
489
0
    }
490
491
0
    switch (exp->kind)
492
0
    {
493
0
        case Constant_kind:
494
            /* Ellipsis and immutable sequences are not allowed.
495
               For True, False and None, MatchSingleton() should
496
               be used */
497
0
            if (!validate_expr(exp, Load)) {
498
0
                return 0;
499
0
            }
500
0
            PyObject *literal = exp->v.Constant.value;
501
0
            if (PyLong_CheckExact(literal) || PyFloat_CheckExact(literal) ||
502
0
                PyBytes_CheckExact(literal) || PyComplex_CheckExact(literal) ||
503
0
                PyUnicode_CheckExact(literal)) {
504
0
                return 1;
505
0
            }
506
0
            PyErr_SetString(PyExc_ValueError,
507
0
                            "unexpected constant inside of a literal pattern");
508
0
            return 0;
509
0
        case Attribute_kind:
510
            // Constants and attribute lookups are always permitted
511
0
            return 1;
512
0
        case UnaryOp_kind:
513
            // Negated numbers are permitted (whether real or imaginary)
514
            // Compiler will complain if AST folding doesn't create a constant
515
0
            if (ensure_literal_negative(exp, /*real=*/true, /*imaginary=*/true)) {
516
0
                return 1;
517
0
            }
518
0
            break;
519
0
        case BinOp_kind:
520
            // Complex literals are permitted
521
            // Compiler will complain if AST folding doesn't create a constant
522
0
            if (ensure_literal_complex(exp)) {
523
0
                return 1;
524
0
            }
525
0
            break;
526
0
        case JoinedStr_kind:
527
0
        case TemplateStr_kind:
528
            // Handled in the later stages
529
0
            return 1;
530
0
        default:
531
0
            break;
532
0
    }
533
0
    PyErr_SetString(PyExc_ValueError,
534
0
                    "patterns may only match literals and attribute lookups");
535
0
    return 0;
536
0
}
537
538
static int
539
validate_capture(PyObject *name)
540
0
{
541
0
    assert(!PyErr_Occurred());
542
0
    if (_PyUnicode_EqualToASCIIString(name, "_")) {
543
0
        PyErr_Format(PyExc_ValueError, "can't capture name '_' in patterns");
544
0
        return 0;
545
0
    }
546
0
    return validate_name(name);
547
0
}
548
549
static int
550
validate_pattern(pattern_ty p, int star_ok)
551
0
{
552
0
    assert(!PyErr_Occurred());
553
0
    VALIDATE_POSITIONS(p);
554
0
    int ret = -1;
555
0
    ENTER_RECURSIVE();
556
0
    switch (p->kind) {
557
0
        case MatchValue_kind:
558
0
            ret = validate_pattern_match_value(p->v.MatchValue.value);
559
0
            break;
560
0
        case MatchSingleton_kind:
561
0
            ret = p->v.MatchSingleton.value == Py_None || PyBool_Check(p->v.MatchSingleton.value);
562
0
            if (!ret) {
563
0
                PyErr_SetString(PyExc_ValueError,
564
0
                                "MatchSingleton can only contain True, False and None");
565
0
            }
566
0
            break;
567
0
        case MatchSequence_kind:
568
0
            ret = validate_patterns(p->v.MatchSequence.patterns, /*star_ok=*/1);
569
0
            break;
570
0
        case MatchMapping_kind:
571
0
            if (asdl_seq_LEN(p->v.MatchMapping.keys) != asdl_seq_LEN(p->v.MatchMapping.patterns)) {
572
0
                PyErr_SetString(PyExc_ValueError,
573
0
                                "MatchMapping doesn't have the same number of keys as patterns");
574
0
                ret = 0;
575
0
                break;
576
0
            }
577
578
0
            if (p->v.MatchMapping.rest && !validate_capture(p->v.MatchMapping.rest)) {
579
0
                ret = 0;
580
0
                break;
581
0
            }
582
583
0
            asdl_expr_seq *keys = p->v.MatchMapping.keys;
584
0
            for (Py_ssize_t i = 0; i < asdl_seq_LEN(keys); i++) {
585
0
                expr_ty key = asdl_seq_GET(keys, i);
586
0
                if (key->kind == Constant_kind) {
587
0
                    PyObject *literal = key->v.Constant.value;
588
0
                    if (literal == Py_None || PyBool_Check(literal)) {
589
                        /* validate_pattern_match_value will ensure the key
590
                           doesn't contain True, False and None but it is
591
                           syntactically valid, so we will pass those on in
592
                           a special case. */
593
0
                        continue;
594
0
                    }
595
0
                }
596
0
                if (!validate_pattern_match_value(key)) {
597
0
                    ret = 0;
598
0
                    break;
599
0
                }
600
0
            }
601
0
            if (ret == 0) {
602
0
                break;
603
0
            }
604
0
            ret = validate_patterns(p->v.MatchMapping.patterns, /*star_ok=*/0);
605
0
            break;
606
0
        case MatchClass_kind:
607
0
            if (asdl_seq_LEN(p->v.MatchClass.kwd_attrs) != asdl_seq_LEN(p->v.MatchClass.kwd_patterns)) {
608
0
                PyErr_SetString(PyExc_ValueError,
609
0
                                "MatchClass doesn't have the same number of keyword attributes as patterns");
610
0
                ret = 0;
611
0
                break;
612
0
            }
613
0
            if (!validate_expr(p->v.MatchClass.cls, Load)) {
614
0
                ret = 0;
615
0
                break;
616
0
            }
617
618
0
            expr_ty cls = p->v.MatchClass.cls;
619
0
            while (1) {
620
0
                if (cls->kind == Name_kind) {
621
0
                    break;
622
0
                }
623
0
                else if (cls->kind == Attribute_kind) {
624
0
                    cls = cls->v.Attribute.value;
625
0
                    continue;
626
0
                }
627
0
                else {
628
0
                    PyErr_SetString(PyExc_ValueError,
629
0
                                    "MatchClass cls field can only contain Name or Attribute nodes.");
630
0
                    ret = 0;
631
0
                    break;
632
0
                }
633
0
            }
634
0
            if (ret == 0) {
635
0
                break;
636
0
            }
637
638
0
            for (Py_ssize_t i = 0; i < asdl_seq_LEN(p->v.MatchClass.kwd_attrs); i++) {
639
0
                PyObject *identifier = asdl_seq_GET(p->v.MatchClass.kwd_attrs, i);
640
0
                if (!validate_name(identifier)) {
641
0
                    ret = 0;
642
0
                    break;
643
0
                }
644
0
            }
645
0
            if (ret == 0) {
646
0
                break;
647
0
            }
648
649
0
            if (!validate_patterns(p->v.MatchClass.patterns, /*star_ok=*/0)) {
650
0
                ret = 0;
651
0
                break;
652
0
            }
653
654
0
            ret = validate_patterns(p->v.MatchClass.kwd_patterns, /*star_ok=*/0);
655
0
            break;
656
0
        case MatchStar_kind:
657
0
            if (!star_ok) {
658
0
                PyErr_SetString(PyExc_ValueError, "can't use MatchStar here");
659
0
                ret = 0;
660
0
                break;
661
0
            }
662
0
            ret = p->v.MatchStar.name == NULL || validate_capture(p->v.MatchStar.name);
663
0
            break;
664
0
        case MatchAs_kind:
665
0
            if (p->v.MatchAs.name && !validate_capture(p->v.MatchAs.name)) {
666
0
                ret = 0;
667
0
                break;
668
0
            }
669
0
            if (p->v.MatchAs.pattern == NULL) {
670
0
                ret = 1;
671
0
            }
672
0
            else if (p->v.MatchAs.name == NULL) {
673
0
                PyErr_SetString(PyExc_ValueError,
674
0
                                "MatchAs must specify a target name if a pattern is given");
675
0
                ret = 0;
676
0
            }
677
0
            else {
678
0
                ret = validate_pattern(p->v.MatchAs.pattern, /*star_ok=*/0);
679
0
            }
680
0
            break;
681
0
        case MatchOr_kind:
682
0
            if (asdl_seq_LEN(p->v.MatchOr.patterns) < 2) {
683
0
                PyErr_SetString(PyExc_ValueError,
684
0
                                "MatchOr requires at least 2 patterns");
685
0
                ret = 0;
686
0
                break;
687
0
            }
688
0
            ret = validate_patterns(p->v.MatchOr.patterns, /*star_ok=*/0);
689
0
            break;
690
    // No default case, so the compiler will emit a warning if new pattern
691
    // kinds are added without being handled here
692
0
    }
693
0
    if (ret < 0) {
694
0
        PyErr_SetString(PyExc_SystemError, "unexpected pattern");
695
0
        ret = 0;
696
0
    }
697
0
    LEAVE_RECURSIVE();
698
0
    return ret;
699
0
}
700
701
static int
702
_validate_nonempty_seq(asdl_seq *seq, const char *what, const char *owner)
703
0
{
704
0
    if (asdl_seq_LEN(seq))
705
0
        return 1;
706
0
    PyErr_Format(PyExc_ValueError, "empty %s on %s", what, owner);
707
0
    return 0;
708
0
}
709
0
#define validate_nonempty_seq(seq, what, owner) _validate_nonempty_seq((asdl_seq*)seq, what, owner)
710
711
static int
712
validate_assignlist(asdl_expr_seq *targets, expr_context_ty ctx)
713
0
{
714
0
    assert(!PyErr_Occurred());
715
0
    return validate_nonempty_seq(targets, "targets", ctx == Del ? "Delete" : "Assign") &&
716
0
        validate_exprs(targets, ctx, 0);
717
0
}
718
719
static int
720
validate_body(asdl_stmt_seq *body, const char *owner)
721
0
{
722
0
    assert(!PyErr_Occurred());
723
0
    return validate_nonempty_seq(body, "body", owner) && validate_stmts(body);
724
0
}
725
726
static int
727
validate_stmt(stmt_ty stmt)
728
0
{
729
0
    assert(!PyErr_Occurred());
730
0
    VALIDATE_POSITIONS(stmt);
731
0
    int ret = -1;
732
0
    ENTER_RECURSIVE();
733
0
    switch (stmt->kind) {
734
0
    case FunctionDef_kind:
735
0
        ret = validate_body(stmt->v.FunctionDef.body, "FunctionDef") &&
736
0
            validate_type_params(stmt->v.FunctionDef.type_params) &&
737
0
            validate_arguments(stmt->v.FunctionDef.args) &&
738
0
            validate_exprs(stmt->v.FunctionDef.decorator_list, Load, 0) &&
739
0
            (!stmt->v.FunctionDef.returns ||
740
0
             validate_expr(stmt->v.FunctionDef.returns, Load));
741
0
        break;
742
0
    case ClassDef_kind:
743
0
        ret = validate_body(stmt->v.ClassDef.body, "ClassDef") &&
744
0
            validate_type_params(stmt->v.ClassDef.type_params) &&
745
0
            validate_exprs(stmt->v.ClassDef.bases, Load, 0) &&
746
0
            validate_keywords(stmt->v.ClassDef.keywords) &&
747
0
            validate_exprs(stmt->v.ClassDef.decorator_list, Load, 0);
748
0
        break;
749
0
    case Return_kind:
750
0
        ret = !stmt->v.Return.value || validate_expr(stmt->v.Return.value, Load);
751
0
        break;
752
0
    case Delete_kind:
753
0
        ret = validate_assignlist(stmt->v.Delete.targets, Del);
754
0
        break;
755
0
    case Assign_kind:
756
0
        ret = validate_assignlist(stmt->v.Assign.targets, Store) &&
757
0
            validate_expr(stmt->v.Assign.value, Load);
758
0
        break;
759
0
    case AugAssign_kind:
760
0
        ret = validate_expr(stmt->v.AugAssign.target, Store) &&
761
0
            validate_expr(stmt->v.AugAssign.value, Load);
762
0
        break;
763
0
    case AnnAssign_kind:
764
0
        if (stmt->v.AnnAssign.target->kind != Name_kind &&
765
0
            stmt->v.AnnAssign.simple) {
766
0
            PyErr_SetString(PyExc_TypeError,
767
0
                            "AnnAssign with simple non-Name target");
768
0
            return 0;
769
0
        }
770
0
        ret = validate_expr(stmt->v.AnnAssign.target, Store) &&
771
0
               (!stmt->v.AnnAssign.value ||
772
0
                validate_expr(stmt->v.AnnAssign.value, Load)) &&
773
0
               validate_expr(stmt->v.AnnAssign.annotation, Load);
774
0
        break;
775
0
    case TypeAlias_kind:
776
0
        if (stmt->v.TypeAlias.name->kind != Name_kind) {
777
0
            PyErr_SetString(PyExc_TypeError,
778
0
                            "TypeAlias with non-Name name");
779
0
            return 0;
780
0
        }
781
0
        ret = validate_expr(stmt->v.TypeAlias.name, Store) &&
782
0
            validate_type_params(stmt->v.TypeAlias.type_params) &&
783
0
            validate_expr(stmt->v.TypeAlias.value, Load);
784
0
        break;
785
0
    case For_kind:
786
0
        ret = validate_expr(stmt->v.For.target, Store) &&
787
0
            validate_expr(stmt->v.For.iter, Load) &&
788
0
            validate_body(stmt->v.For.body, "For") &&
789
0
            validate_stmts(stmt->v.For.orelse);
790
0
        break;
791
0
    case AsyncFor_kind:
792
0
        ret = validate_expr(stmt->v.AsyncFor.target, Store) &&
793
0
            validate_expr(stmt->v.AsyncFor.iter, Load) &&
794
0
            validate_body(stmt->v.AsyncFor.body, "AsyncFor") &&
795
0
            validate_stmts(stmt->v.AsyncFor.orelse);
796
0
        break;
797
0
    case While_kind:
798
0
        ret = validate_expr(stmt->v.While.test, Load) &&
799
0
            validate_body(stmt->v.While.body, "While") &&
800
0
            validate_stmts(stmt->v.While.orelse);
801
0
        break;
802
0
    case If_kind:
803
0
        ret = validate_expr(stmt->v.If.test, Load) &&
804
0
            validate_body(stmt->v.If.body, "If") &&
805
0
            validate_stmts(stmt->v.If.orelse);
806
0
        break;
807
0
    case With_kind:
808
0
        if (!validate_nonempty_seq(stmt->v.With.items, "items", "With"))
809
0
            return 0;
810
0
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(stmt->v.With.items); i++) {
811
0
            withitem_ty item = asdl_seq_GET(stmt->v.With.items, i);
812
0
            if (!validate_expr(item->context_expr, Load) ||
813
0
                (item->optional_vars && !validate_expr(item->optional_vars, Store)))
814
0
                return 0;
815
0
        }
816
0
        ret = validate_body(stmt->v.With.body, "With");
817
0
        break;
818
0
    case AsyncWith_kind:
819
0
        if (!validate_nonempty_seq(stmt->v.AsyncWith.items, "items", "AsyncWith"))
820
0
            return 0;
821
0
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(stmt->v.AsyncWith.items); i++) {
822
0
            withitem_ty item = asdl_seq_GET(stmt->v.AsyncWith.items, i);
823
0
            if (!validate_expr(item->context_expr, Load) ||
824
0
                (item->optional_vars && !validate_expr(item->optional_vars, Store)))
825
0
                return 0;
826
0
        }
827
0
        ret = validate_body(stmt->v.AsyncWith.body, "AsyncWith");
828
0
        break;
829
0
    case Match_kind:
830
0
        if (!validate_expr(stmt->v.Match.subject, Load)
831
0
            || !validate_nonempty_seq(stmt->v.Match.cases, "cases", "Match")) {
832
0
            return 0;
833
0
        }
834
0
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(stmt->v.Match.cases); i++) {
835
0
            match_case_ty m = asdl_seq_GET(stmt->v.Match.cases, i);
836
0
            if (!validate_pattern(m->pattern, /*star_ok=*/0)
837
0
                || (m->guard && !validate_expr(m->guard, Load))
838
0
                || !validate_body(m->body, "match_case")) {
839
0
                return 0;
840
0
            }
841
0
        }
842
0
        ret = 1;
843
0
        break;
844
0
    case Raise_kind:
845
0
        if (stmt->v.Raise.exc) {
846
0
            ret = validate_expr(stmt->v.Raise.exc, Load) &&
847
0
                (!stmt->v.Raise.cause || validate_expr(stmt->v.Raise.cause, Load));
848
0
            break;
849
0
        }
850
0
        if (stmt->v.Raise.cause) {
851
0
            PyErr_SetString(PyExc_ValueError, "Raise with cause but no exception");
852
0
            return 0;
853
0
        }
854
0
        ret = 1;
855
0
        break;
856
0
    case Try_kind:
857
0
        if (!validate_body(stmt->v.Try.body, "Try"))
858
0
            return 0;
859
0
        if (!asdl_seq_LEN(stmt->v.Try.handlers) &&
860
0
            !asdl_seq_LEN(stmt->v.Try.finalbody)) {
861
0
            PyErr_SetString(PyExc_ValueError, "Try has neither except handlers nor finalbody");
862
0
            return 0;
863
0
        }
864
0
        if (!asdl_seq_LEN(stmt->v.Try.handlers) &&
865
0
            asdl_seq_LEN(stmt->v.Try.orelse)) {
866
0
            PyErr_SetString(PyExc_ValueError, "Try has orelse but no except handlers");
867
0
            return 0;
868
0
        }
869
0
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(stmt->v.Try.handlers); i++) {
870
0
            excepthandler_ty handler = asdl_seq_GET(stmt->v.Try.handlers, i);
871
0
            VALIDATE_POSITIONS(handler);
872
0
            if ((handler->v.ExceptHandler.type &&
873
0
                 !validate_expr(handler->v.ExceptHandler.type, Load)) ||
874
0
                !validate_body(handler->v.ExceptHandler.body, "ExceptHandler"))
875
0
                return 0;
876
0
        }
877
0
        ret = (!asdl_seq_LEN(stmt->v.Try.finalbody) ||
878
0
                validate_stmts(stmt->v.Try.finalbody)) &&
879
0
            (!asdl_seq_LEN(stmt->v.Try.orelse) ||
880
0
             validate_stmts(stmt->v.Try.orelse));
881
0
        break;
882
0
    case TryStar_kind:
883
0
        if (!validate_body(stmt->v.TryStar.body, "TryStar"))
884
0
            return 0;
885
0
        if (!asdl_seq_LEN(stmt->v.TryStar.handlers) &&
886
0
            !asdl_seq_LEN(stmt->v.TryStar.finalbody)) {
887
0
            PyErr_SetString(PyExc_ValueError, "TryStar has neither except handlers nor finalbody");
888
0
            return 0;
889
0
        }
890
0
        if (!asdl_seq_LEN(stmt->v.TryStar.handlers) &&
891
0
            asdl_seq_LEN(stmt->v.TryStar.orelse)) {
892
0
            PyErr_SetString(PyExc_ValueError, "TryStar has orelse but no except handlers");
893
0
            return 0;
894
0
        }
895
0
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(stmt->v.TryStar.handlers); i++) {
896
0
            excepthandler_ty handler = asdl_seq_GET(stmt->v.TryStar.handlers, i);
897
0
            if ((handler->v.ExceptHandler.type &&
898
0
                 !validate_expr(handler->v.ExceptHandler.type, Load)) ||
899
0
                !validate_body(handler->v.ExceptHandler.body, "ExceptHandler"))
900
0
                return 0;
901
0
        }
902
0
        ret = (!asdl_seq_LEN(stmt->v.TryStar.finalbody) ||
903
0
                validate_stmts(stmt->v.TryStar.finalbody)) &&
904
0
            (!asdl_seq_LEN(stmt->v.TryStar.orelse) ||
905
0
             validate_stmts(stmt->v.TryStar.orelse));
906
0
        break;
907
0
    case Assert_kind:
908
0
        ret = validate_expr(stmt->v.Assert.test, Load) &&
909
0
            (!stmt->v.Assert.msg || validate_expr(stmt->v.Assert.msg, Load));
910
0
        break;
911
0
    case Import_kind:
912
0
        ret = validate_nonempty_seq(stmt->v.Import.names, "names", "Import");
913
0
        break;
914
0
    case ImportFrom_kind:
915
0
        if (stmt->v.ImportFrom.level < 0) {
916
0
            PyErr_SetString(PyExc_ValueError, "Negative ImportFrom level");
917
0
            return 0;
918
0
        }
919
0
        ret = validate_nonempty_seq(stmt->v.ImportFrom.names, "names", "ImportFrom");
920
0
        break;
921
0
    case Global_kind:
922
0
        ret = validate_nonempty_seq(stmt->v.Global.names, "names", "Global");
923
0
        break;
924
0
    case Nonlocal_kind:
925
0
        ret = validate_nonempty_seq(stmt->v.Nonlocal.names, "names", "Nonlocal");
926
0
        break;
927
0
    case Expr_kind:
928
0
        ret = validate_expr(stmt->v.Expr.value, Load);
929
0
        break;
930
0
    case AsyncFunctionDef_kind:
931
0
        ret = validate_body(stmt->v.AsyncFunctionDef.body, "AsyncFunctionDef") &&
932
0
            validate_type_params(stmt->v.AsyncFunctionDef.type_params) &&
933
0
            validate_arguments(stmt->v.AsyncFunctionDef.args) &&
934
0
            validate_exprs(stmt->v.AsyncFunctionDef.decorator_list, Load, 0) &&
935
0
            (!stmt->v.AsyncFunctionDef.returns ||
936
0
             validate_expr(stmt->v.AsyncFunctionDef.returns, Load));
937
0
        break;
938
0
    case Pass_kind:
939
0
    case Break_kind:
940
0
    case Continue_kind:
941
0
        ret = 1;
942
0
        break;
943
    // No default case so compiler emits warning for unhandled cases
944
0
    }
945
0
    if (ret < 0) {
946
0
        PyErr_SetString(PyExc_SystemError, "unexpected statement");
947
0
        ret = 0;
948
0
    }
949
0
    LEAVE_RECURSIVE();
950
0
    return ret;
951
0
}
952
953
static int
954
validate_stmts(asdl_stmt_seq *seq)
955
0
{
956
0
    assert(!PyErr_Occurred());
957
0
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(seq); i++) {
958
0
        stmt_ty stmt = asdl_seq_GET(seq, i);
959
0
        if (stmt) {
960
0
            if (!validate_stmt(stmt))
961
0
                return 0;
962
0
        }
963
0
        else {
964
0
            PyErr_SetString(PyExc_ValueError,
965
0
                            "None disallowed in statement list");
966
0
            return 0;
967
0
        }
968
0
    }
969
0
    return 1;
970
0
}
971
972
static int
973
validate_exprs(asdl_expr_seq *exprs, expr_context_ty ctx, int null_ok)
974
0
{
975
0
    assert(!PyErr_Occurred());
976
0
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(exprs); i++) {
977
0
        expr_ty expr = asdl_seq_GET(exprs, i);
978
0
        if (expr) {
979
0
            if (!validate_expr(expr, ctx))
980
0
                return 0;
981
0
        }
982
0
        else if (!null_ok) {
983
0
            PyErr_SetString(PyExc_ValueError,
984
0
                            "None disallowed in expression list");
985
0
            return 0;
986
0
        }
987
988
0
    }
989
0
    return 1;
990
0
}
991
992
static int
993
validate_patterns(asdl_pattern_seq *patterns, int star_ok)
994
0
{
995
0
    assert(!PyErr_Occurred());
996
0
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(patterns); i++) {
997
0
        pattern_ty pattern = asdl_seq_GET(patterns, i);
998
0
        if (!validate_pattern(pattern, star_ok)) {
999
0
            return 0;
1000
0
        }
1001
0
    }
1002
0
    return 1;
1003
0
}
1004
1005
static int
1006
validate_typeparam(type_param_ty tp)
1007
0
{
1008
0
    VALIDATE_POSITIONS(tp);
1009
0
    int ret = -1;
1010
0
    switch (tp->kind) {
1011
0
        case TypeVar_kind:
1012
0
            ret = validate_name(tp->v.TypeVar.name) &&
1013
0
                (!tp->v.TypeVar.bound ||
1014
0
                 validate_expr(tp->v.TypeVar.bound, Load)) &&
1015
0
                (!tp->v.TypeVar.default_value ||
1016
0
                 validate_expr(tp->v.TypeVar.default_value, Load));
1017
0
            break;
1018
0
        case ParamSpec_kind:
1019
0
            ret = validate_name(tp->v.ParamSpec.name) &&
1020
0
                (!tp->v.ParamSpec.default_value ||
1021
0
                 validate_expr(tp->v.ParamSpec.default_value, Load));
1022
0
            break;
1023
0
        case TypeVarTuple_kind:
1024
0
            ret = validate_name(tp->v.TypeVarTuple.name) &&
1025
0
                (!tp->v.TypeVarTuple.default_value ||
1026
0
                 validate_expr(tp->v.TypeVarTuple.default_value, Load));
1027
0
            break;
1028
0
    }
1029
0
    return ret;
1030
0
}
1031
1032
static int
1033
validate_type_params(asdl_type_param_seq *tps)
1034
0
{
1035
0
    Py_ssize_t i;
1036
0
    for (i = 0; i < asdl_seq_LEN(tps); i++) {
1037
0
        type_param_ty tp = asdl_seq_GET(tps, i);
1038
0
        if (tp) {
1039
0
            if (!validate_typeparam(tp))
1040
0
                return 0;
1041
0
        }
1042
0
    }
1043
0
    return 1;
1044
0
}
1045
1046
int
1047
_PyAST_Validate(mod_ty mod)
1048
0
{
1049
0
    assert(!PyErr_Occurred());
1050
0
    int res = -1;
1051
1052
0
    switch (mod->kind) {
1053
0
    case Module_kind:
1054
0
        res = validate_stmts(mod->v.Module.body);
1055
0
        break;
1056
0
    case Interactive_kind:
1057
0
        res = validate_stmts(mod->v.Interactive.body);
1058
0
        break;
1059
0
    case Expression_kind:
1060
0
        res = validate_expr(mod->v.Expression.body, Load);
1061
0
        break;
1062
0
    case FunctionType_kind:
1063
0
        res = validate_exprs(mod->v.FunctionType.argtypes, Load, /*null_ok=*/0) &&
1064
0
              validate_expr(mod->v.FunctionType.returns, Load);
1065
0
        break;
1066
    // No default case so compiler emits warning for unhandled cases
1067
0
    }
1068
1069
0
    if (res < 0) {
1070
0
        PyErr_SetString(PyExc_SystemError, "impossible module node");
1071
0
        return 0;
1072
0
    }
1073
0
    return res;
1074
0
}
1075
1076
PyObject *
1077
_PyAST_GetDocString(asdl_stmt_seq *body)
1078
44.0k
{
1079
44.0k
    if (!asdl_seq_LEN(body)) {
1080
1.75k
        return NULL;
1081
1.75k
    }
1082
42.3k
    stmt_ty st = asdl_seq_GET(body, 0);
1083
42.3k
    if (st->kind != Expr_kind) {
1084
13.9k
        return NULL;
1085
13.9k
    }
1086
28.3k
    expr_ty e = st->v.Expr.value;
1087
28.3k
    if (e->kind == Constant_kind && PyUnicode_CheckExact(e->v.Constant.value)) {
1088
6.89k
        return e->v.Constant.value;
1089
6.89k
    }
1090
21.4k
    return NULL;
1091
28.3k
}