Coverage Report

Created: 2026-04-20 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Python/symtable.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_ast.h"           // stmt_ty
3
#include "pycore_parser.h"        // _PyParser_ASTFromString()
4
#include "pycore_pystate.h"       // _PyThreadState_GET()
5
#include "pycore_runtime.h"       // _Py_ID()
6
#include "pycore_symtable.h"      // PySTEntryObject
7
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString
8
9
#include <stddef.h>               // offsetof()
10
11
12
// Set this to 1 to dump all symtables to stdout for debugging
13
#define _PY_DUMP_SYMTABLE 0
14
15
/* error strings used for warnings */
16
0
#define GLOBAL_PARAM \
17
0
"name '%U' is parameter and global"
18
19
0
#define NONLOCAL_PARAM \
20
0
"name '%U' is parameter and nonlocal"
21
22
1
#define GLOBAL_AFTER_ASSIGN \
23
1
"name '%U' is assigned to before global declaration"
24
25
0
#define NONLOCAL_AFTER_ASSIGN \
26
0
"name '%U' is assigned to before nonlocal declaration"
27
28
4
#define GLOBAL_AFTER_USE \
29
4
"name '%U' is used prior to global declaration"
30
31
1
#define NONLOCAL_AFTER_USE \
32
1
"name '%U' is used prior to nonlocal declaration"
33
34
0
#define GLOBAL_ANNOT \
35
0
"annotated name '%U' can't be global"
36
37
0
#define NONLOCAL_ANNOT \
38
0
"annotated name '%U' can't be nonlocal"
39
40
1
#define IMPORT_STAR_WARNING "import * only allowed at module level"
41
42
0
#define NAMED_EXPR_COMP_IN_CLASS \
43
0
"assignment expression within a comprehension cannot be used in a class body"
44
45
0
#define NAMED_EXPR_COMP_IN_TYPEVAR_BOUND \
46
0
"assignment expression within a comprehension cannot be used in a TypeVar bound"
47
48
0
#define NAMED_EXPR_COMP_IN_TYPEALIAS \
49
0
"assignment expression within a comprehension cannot be used in a type alias"
50
51
0
#define NAMED_EXPR_COMP_IN_TYPEPARAM \
52
0
"assignment expression within a comprehension cannot be used within the definition of a generic"
53
54
0
#define NAMED_EXPR_COMP_CONFLICT \
55
0
"assignment expression cannot rebind comprehension iteration variable '%U'"
56
57
0
#define NAMED_EXPR_COMP_INNER_LOOP_CONFLICT \
58
0
"comprehension inner loop cannot rebind assignment expression target '%U'"
59
60
0
#define NAMED_EXPR_COMP_ITER_EXPR \
61
0
"assignment expression cannot be used in a comprehension iterable expression"
62
63
6
#define ANNOTATION_NOT_ALLOWED \
64
6
"%s cannot be used within an annotation"
65
66
0
#define EXPR_NOT_ALLOWED_IN_TYPE_VARIABLE \
67
0
"%s cannot be used within %s"
68
69
0
#define EXPR_NOT_ALLOWED_IN_TYPE_ALIAS \
70
0
"%s cannot be used within a type alias"
71
72
0
#define EXPR_NOT_ALLOWED_IN_TYPE_PARAMETERS \
73
0
"%s cannot be used within the definition of a generic"
74
75
0
#define DUPLICATE_TYPE_PARAM \
76
0
"duplicate type parameter '%U'"
77
78
820
#define ASYNC_WITH_OUTSIDE_ASYNC_FUNC \
79
820
"'async with' outside async function"
80
81
6
#define ASYNC_FOR_OUTSIDE_ASYNC_FUNC \
82
6
"'async for' outside async function"
83
84
174k
#define LOCATION(x) SRC_LOCATION_FROM_AST(x)
85
86
#define SET_ERROR_LOCATION(FNAME, L) \
87
62
    PyErr_RangedSyntaxLocationObject((FNAME), \
88
62
        (L).lineno, (L).col_offset + 1, (L).end_lineno, (L).end_col_offset + 1)
89
90
1.54k
#define IS_ASYNC_DEF(st) ((st)->st_cur->ste_type == FunctionBlock && (st)->st_cur->ste_coroutine)
91
92
static PySTEntryObject *
93
ste_new(struct symtable *st, identifier name, _Py_block_ty block,
94
        void *key, _Py_SourceLocation loc)
95
28.8k
{
96
28.8k
    PySTEntryObject *ste = NULL;
97
28.8k
    PyObject *k = NULL;
98
99
28.8k
    k = PyLong_FromVoidPtr(key);
100
28.8k
    if (k == NULL)
101
0
        goto fail;
102
28.8k
    ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
103
28.8k
    if (ste == NULL) {
104
0
        Py_DECREF(k);
105
0
        goto fail;
106
0
    }
107
28.8k
    ste->ste_table = st;
108
28.8k
    ste->ste_id = k; /* ste owns reference to k */
109
110
28.8k
    ste->ste_name = Py_NewRef(name);
111
28.8k
    ste->ste_function_name = NULL;
112
113
28.8k
    ste->ste_symbols = NULL;
114
28.8k
    ste->ste_varnames = NULL;
115
28.8k
    ste->ste_children = NULL;
116
117
28.8k
    ste->ste_directives = NULL;
118
28.8k
    ste->ste_mangled_names = NULL;
119
120
28.8k
    ste->ste_type = block;
121
28.8k
    ste->ste_scope_info = NULL;
122
123
28.8k
    ste->ste_nested = 0;
124
28.8k
    ste->ste_varargs = 0;
125
28.8k
    ste->ste_varkeywords = 0;
126
28.8k
    ste->ste_annotations_used = 0;
127
28.8k
    ste->ste_loc = loc;
128
129
28.8k
    if (st->st_cur != NULL &&
130
24.1k
        (st->st_cur->ste_nested ||
131
20.8k
         _PyST_IsFunctionLike(st->st_cur)))
132
9.05k
        ste->ste_nested = 1;
133
28.8k
    ste->ste_generator = 0;
134
28.8k
    ste->ste_coroutine = 0;
135
28.8k
    ste->ste_comprehension = NoComprehension;
136
28.8k
    ste->ste_returns_value = 0;
137
28.8k
    ste->ste_needs_class_closure = 0;
138
28.8k
    ste->ste_comp_inlined = 0;
139
28.8k
    ste->ste_comp_iter_target = 0;
140
28.8k
    ste->ste_can_see_class_scope = 0;
141
28.8k
    ste->ste_comp_iter_expr = 0;
142
28.8k
    ste->ste_needs_classdict = 0;
143
28.8k
    ste->ste_has_conditional_annotations = 0;
144
28.8k
    ste->ste_in_conditional_block = 0;
145
28.8k
    ste->ste_in_try_block = 0;
146
28.8k
    ste->ste_in_unevaluated_annotation = 0;
147
28.8k
    ste->ste_annotation_block = NULL;
148
149
28.8k
    ste->ste_has_docstring = 0;
150
151
28.8k
    ste->ste_method = 0;
152
28.8k
    if (st->st_cur != NULL &&
153
24.1k
        st->st_cur->ste_type == ClassBlock &&
154
3.38k
        block == FunctionBlock) {
155
3
        ste->ste_method = 1;
156
3
    }
157
158
28.8k
    ste->ste_symbols = PyDict_New();
159
28.8k
    ste->ste_varnames = PyList_New(0);
160
28.8k
    ste->ste_children = PyList_New(0);
161
28.8k
    if (ste->ste_symbols == NULL
162
28.8k
        || ste->ste_varnames == NULL
163
28.8k
        || ste->ste_children == NULL)
164
0
        goto fail;
165
166
28.8k
    if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
167
0
        goto fail;
168
169
28.8k
    return ste;
170
0
 fail:
171
0
    Py_XDECREF(ste);
172
0
    return NULL;
173
28.8k
}
174
175
static PyObject *
176
ste_repr(PyObject *op)
177
0
{
178
0
    PySTEntryObject *ste = (PySTEntryObject *)op;
179
0
    return PyUnicode_FromFormat("<symtable entry %U(%R), line %d>",
180
0
                                ste->ste_name, ste->ste_id, ste->ste_loc.lineno);
181
0
}
182
183
static void
184
ste_dealloc(PyObject *op)
185
28.8k
{
186
28.8k
    PySTEntryObject *ste = (PySTEntryObject *)op;
187
28.8k
    ste->ste_table = NULL;
188
28.8k
    Py_XDECREF(ste->ste_id);
189
28.8k
    Py_XDECREF(ste->ste_name);
190
28.8k
    Py_XDECREF(ste->ste_function_name);
191
28.8k
    Py_XDECREF(ste->ste_symbols);
192
28.8k
    Py_XDECREF(ste->ste_varnames);
193
28.8k
    Py_XDECREF(ste->ste_children);
194
28.8k
    Py_XDECREF(ste->ste_directives);
195
28.8k
    Py_XDECREF(ste->ste_annotation_block);
196
28.8k
    Py_XDECREF(ste->ste_mangled_names);
197
28.8k
    PyObject_Free(ste);
198
28.8k
}
199
200
#define OFF(x) offsetof(PySTEntryObject, x)
201
202
static PyMemberDef ste_memberlist[] = {
203
    {"id",       _Py_T_OBJECT, OFF(ste_id), Py_READONLY},
204
    {"name",     _Py_T_OBJECT, OFF(ste_name), Py_READONLY},
205
    {"symbols",  _Py_T_OBJECT, OFF(ste_symbols), Py_READONLY},
206
    {"varnames", _Py_T_OBJECT, OFF(ste_varnames), Py_READONLY},
207
    {"children", _Py_T_OBJECT, OFF(ste_children), Py_READONLY},
208
    {"nested",   Py_T_INT,    OFF(ste_nested), Py_READONLY},
209
    {"type",     Py_T_INT,    OFF(ste_type), Py_READONLY},
210
    {"lineno",   Py_T_INT,    OFF(ste_loc.lineno), Py_READONLY},
211
    {NULL}
212
};
213
214
PyTypeObject PySTEntry_Type = {
215
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
216
    "symtable entry",
217
    sizeof(PySTEntryObject),
218
    0,
219
    ste_dealloc,                                /* tp_dealloc */
220
    0,                                          /* tp_vectorcall_offset */
221
    0,                                          /* tp_getattr */
222
    0,                                          /* tp_setattr */
223
    0,                                          /* tp_as_async */
224
    ste_repr,                                   /* tp_repr */
225
    0,                                          /* tp_as_number */
226
    0,                                          /* tp_as_sequence */
227
    0,                                          /* tp_as_mapping */
228
    0,                                          /* tp_hash */
229
    0,                                          /* tp_call */
230
    0,                                          /* tp_str */
231
    PyObject_GenericGetAttr,                    /* tp_getattro */
232
    0,                                          /* tp_setattro */
233
    0,                                          /* tp_as_buffer */
234
    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
235
    0,                                          /* tp_doc */
236
    0,                                          /* tp_traverse */
237
    0,                                          /* tp_clear */
238
    0,                                          /* tp_richcompare */
239
    0,                                          /* tp_weaklistoffset */
240
    0,                                          /* tp_iter */
241
    0,                                          /* tp_iternext */
242
    0,                                          /* tp_methods */
243
    ste_memberlist,                             /* tp_members */
244
    0,                                          /* tp_getset */
245
    0,                                          /* tp_base */
246
    0,                                          /* tp_dict */
247
    0,                                          /* tp_descr_get */
248
    0,                                          /* tp_descr_set */
249
    0,                                          /* tp_dictoffset */
250
    0,                                          /* tp_init */
251
    0,                                          /* tp_alloc */
252
    0,                                          /* tp_new */
253
};
254
255
static int symtable_analyze(struct symtable *st);
256
static int symtable_enter_block(struct symtable *st, identifier name,
257
                                _Py_block_ty block, void *ast, _Py_SourceLocation loc);
258
static int symtable_exit_block(struct symtable *st);
259
static int symtable_visit_stmt(struct symtable *st, stmt_ty s);
260
static int symtable_visit_expr(struct symtable *st, expr_ty s);
261
static int symtable_visit_type_param(struct symtable *st, type_param_ty s);
262
static int symtable_visit_genexp(struct symtable *st, expr_ty s);
263
static int symtable_visit_listcomp(struct symtable *st, expr_ty s);
264
static int symtable_visit_setcomp(struct symtable *st, expr_ty s);
265
static int symtable_visit_dictcomp(struct symtable *st, expr_ty s);
266
static int symtable_visit_arguments(struct symtable *st, arguments_ty);
267
static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty);
268
static int symtable_visit_alias(struct symtable *st, alias_ty);
269
static int symtable_visit_comprehension(struct symtable *st, comprehension_ty);
270
static int symtable_visit_keyword(struct symtable *st, keyword_ty);
271
static int symtable_visit_params(struct symtable *st, asdl_arg_seq *args);
272
static int symtable_visit_annotation(struct symtable *st, expr_ty annotation, void *key);
273
static int symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args);
274
static int symtable_implicit_arg(struct symtable *st, int pos);
275
static int symtable_visit_annotations(struct symtable *st, stmt_ty, arguments_ty, expr_ty,
276
                                      struct _symtable_entry *parent_ste);
277
static int symtable_visit_withitem(struct symtable *st, withitem_ty item);
278
static int symtable_visit_match_case(struct symtable *st, match_case_ty m);
279
static int symtable_visit_pattern(struct symtable *st, pattern_ty s);
280
static int symtable_raise_if_annotation_block(struct symtable *st, const char *, expr_ty);
281
static int symtable_raise_if_not_coroutine(struct symtable *st, const char *msg, _Py_SourceLocation loc);
282
static int symtable_raise_if_comprehension_block(struct symtable *st, expr_ty);
283
static int symtable_add_def(struct symtable *st, PyObject *name, int flag, _Py_SourceLocation loc);
284
285
/* For debugging purposes only */
286
#if _PY_DUMP_SYMTABLE
287
static void _dump_symtable(PySTEntryObject* ste, PyObject* prefix)
288
{
289
    const char *blocktype = "";
290
    switch (ste->ste_type) {
291
        case FunctionBlock: blocktype = "FunctionBlock"; break;
292
        case ClassBlock: blocktype = "ClassBlock"; break;
293
        case ModuleBlock: blocktype = "ModuleBlock"; break;
294
        case AnnotationBlock: blocktype = "AnnotationBlock"; break;
295
        case TypeVariableBlock: blocktype = "TypeVariableBlock"; break;
296
        case TypeAliasBlock: blocktype = "TypeAliasBlock"; break;
297
        case TypeParametersBlock: blocktype = "TypeParametersBlock"; break;
298
    }
299
    const char *comptype = "";
300
    switch (ste->ste_comprehension) {
301
        case ListComprehension: comptype = " ListComprehension"; break;
302
        case DictComprehension: comptype = " DictComprehension"; break;
303
        case SetComprehension: comptype = " SetComprehension"; break;
304
        case GeneratorExpression: comptype = " GeneratorExpression"; break;
305
        case NoComprehension: break;
306
    }
307
    PyObject* msg = PyUnicode_FromFormat(
308
        (
309
            "%U=== Symtable for %U ===\n"
310
            "%U%s%s\n"
311
            "%U%s%s%s%s%s%s%s%s%s%s%s\n"
312
            "%Ulineno: %d col_offset: %d\n"
313
            "%U--- Symbols ---\n"
314
        ),
315
        prefix,
316
        ste->ste_name,
317
        prefix,
318
        blocktype,
319
        comptype,
320
        prefix,
321
        ste->ste_nested ? " nested" : "",
322
        ste->ste_generator ? " generator" : "",
323
        ste->ste_coroutine ? " coroutine" : "",
324
        ste->ste_varargs ? " varargs" : "",
325
        ste->ste_varkeywords ? " varkeywords" : "",
326
        ste->ste_returns_value ? " returns_value" : "",
327
        ste->ste_needs_class_closure ? " needs_class_closure" : "",
328
        ste->ste_needs_classdict ? " needs_classdict" : "",
329
        ste->ste_comp_inlined ? " comp_inlined" : "",
330
        ste->ste_comp_iter_target ? " comp_iter_target" : "",
331
        ste->ste_can_see_class_scope ? " can_see_class_scope" : "",
332
        prefix,
333
        ste->ste_loc.lineno,
334
        ste->ste_loc.col_offset,
335
        prefix
336
    );
337
    assert(msg != NULL);
338
    printf("%s", PyUnicode_AsUTF8(msg));
339
    Py_DECREF(msg);
340
    PyObject *name, *value;
341
    Py_ssize_t pos = 0;
342
    while (PyDict_Next(ste->ste_symbols, &pos, &name, &value)) {
343
        int scope = _PyST_GetScope(ste, name);
344
        long flags = _PyST_GetSymbol(ste, name);
345
        printf("%s  %s: ", PyUnicode_AsUTF8(prefix), PyUnicode_AsUTF8(name));
346
        if (flags & DEF_GLOBAL) printf(" DEF_GLOBAL");
347
        if (flags & DEF_LOCAL) printf(" DEF_LOCAL");
348
        if (flags & DEF_PARAM) printf(" DEF_PARAM");
349
        if (flags & DEF_NONLOCAL) printf(" DEF_NONLOCAL");
350
        if (flags & USE) printf(" USE");
351
        if (flags & DEF_FREE_CLASS) printf(" DEF_FREE_CLASS");
352
        if (flags & DEF_IMPORT) printf(" DEF_IMPORT");
353
        if (flags & DEF_ANNOT) printf(" DEF_ANNOT");
354
        if (flags & DEF_COMP_ITER) printf(" DEF_COMP_ITER");
355
        if (flags & DEF_TYPE_PARAM) printf(" DEF_TYPE_PARAM");
356
        if (flags & DEF_COMP_CELL) printf(" DEF_COMP_CELL");
357
        switch (scope) {
358
            case LOCAL: printf(" LOCAL"); break;
359
            case GLOBAL_EXPLICIT: printf(" GLOBAL_EXPLICIT"); break;
360
            case GLOBAL_IMPLICIT: printf(" GLOBAL_IMPLICIT"); break;
361
            case FREE: printf(" FREE"); break;
362
            case CELL: printf(" CELL"); break;
363
        }
364
        printf("\n");
365
    }
366
    printf("%s--- Children ---\n", PyUnicode_AsUTF8(prefix));
367
    PyObject *new_prefix = PyUnicode_FromFormat("  %U", prefix);
368
    assert(new_prefix != NULL);
369
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(ste->ste_children); i++) {
370
        PyObject *child = PyList_GetItem(ste->ste_children, i);
371
        assert(child != NULL && PySTEntry_Check(child));
372
        _dump_symtable((PySTEntryObject *)child, new_prefix);
373
    }
374
    Py_DECREF(new_prefix);
375
}
376
377
static void dump_symtable(PySTEntryObject* ste)
378
{
379
    PyObject *empty = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
380
    assert(empty != NULL);
381
    _dump_symtable(ste, empty);
382
    Py_DECREF(empty);
383
}
384
#endif
385
386
9
#define DUPLICATE_PARAMETER \
387
9
"duplicate parameter '%U' in function definition"
388
389
static struct symtable *
390
symtable_new(void)
391
4.71k
{
392
4.71k
    struct symtable *st;
393
394
4.71k
    st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
395
4.71k
    if (st == NULL) {
396
0
        PyErr_NoMemory();
397
0
        return NULL;
398
0
    }
399
400
4.71k
    st->st_filename = NULL;
401
4.71k
    st->st_blocks = NULL;
402
403
4.71k
    if ((st->st_stack = PyList_New(0)) == NULL)
404
0
        goto fail;
405
4.71k
    if ((st->st_blocks = PyDict_New()) == NULL)
406
0
        goto fail;
407
4.71k
    st->st_cur = NULL;
408
4.71k
    st->st_private = NULL;
409
4.71k
    return st;
410
0
 fail:
411
0
    _PySymtable_Free(st);
412
0
    return NULL;
413
4.71k
}
414
415
struct symtable *
416
_PySymtable_Build(mod_ty mod, PyObject *filename, _PyFutureFeatures *future)
417
4.71k
{
418
4.71k
    struct symtable *st = symtable_new();
419
4.71k
    asdl_stmt_seq *seq;
420
4.71k
    Py_ssize_t i;
421
4.71k
    PyThreadState *tstate;
422
423
4.71k
    if (st == NULL)
424
0
        return NULL;
425
4.71k
    if (filename == NULL) {
426
0
        _PySymtable_Free(st);
427
0
        return NULL;
428
0
    }
429
4.71k
    st->st_filename = Py_NewRef(filename);
430
4.71k
    st->st_future = future;
431
432
    /* Setup recursion depth check counters */
433
4.71k
    tstate = _PyThreadState_GET();
434
4.71k
    if (!tstate) {
435
0
        _PySymtable_Free(st);
436
0
        return NULL;
437
0
    }
438
439
    /* Make the initial symbol information gathering pass */
440
441
4.71k
    _Py_SourceLocation loc0 = {0, 0, 0, 0};
442
4.71k
    if (!symtable_enter_block(st, &_Py_ID(top), ModuleBlock, (void *)mod, loc0)) {
443
0
        _PySymtable_Free(st);
444
0
        return NULL;
445
0
    }
446
447
4.71k
    st->st_top = st->st_cur;
448
4.71k
    switch (mod->kind) {
449
2.85k
    case Module_kind:
450
2.85k
        seq = mod->v.Module.body;
451
2.85k
        if (_PyAST_GetDocString(seq)) {
452
32
            st->st_cur->ste_has_docstring = 1;
453
32
        }
454
25.2k
        for (i = 0; i < asdl_seq_LEN(seq); i++)
455
22.4k
            if (!symtable_visit_stmt(st,
456
22.4k
                        (stmt_ty)asdl_seq_GET(seq, i)))
457
48
                goto error;
458
2.80k
        break;
459
2.80k
    case Expression_kind:
460
945
        if (!symtable_visit_expr(st, mod->v.Expression.body))
461
6
            goto error;
462
939
        break;
463
939
    case Interactive_kind:
464
912
        seq = mod->v.Interactive.body;
465
2.06k
        for (i = 0; i < asdl_seq_LEN(seq); i++)
466
1.16k
            if (!symtable_visit_stmt(st,
467
1.16k
                        (stmt_ty)asdl_seq_GET(seq, i)))
468
8
                goto error;
469
904
        break;
470
904
    case FunctionType_kind:
471
0
        PyErr_SetString(PyExc_RuntimeError,
472
0
                        "this compiler does not handle FunctionTypes");
473
0
        goto error;
474
4.71k
    }
475
4.64k
    if (!symtable_exit_block(st)) {
476
0
        _PySymtable_Free(st);
477
0
        return NULL;
478
0
    }
479
    /* Make the second symbol analysis pass */
480
4.64k
    if (symtable_analyze(st)) {
481
#if _PY_DUMP_SYMTABLE
482
        dump_symtable(st->st_top);
483
#endif
484
4.63k
        return st;
485
4.63k
    }
486
9
    _PySymtable_Free(st);
487
9
    return NULL;
488
62
 error:
489
62
    (void) symtable_exit_block(st);
490
62
    _PySymtable_Free(st);
491
62
    return NULL;
492
4.64k
}
493
494
495
void
496
_PySymtable_Free(struct symtable *st)
497
4.71k
{
498
4.71k
    Py_XDECREF(st->st_filename);
499
4.71k
    Py_XDECREF(st->st_blocks);
500
4.71k
    Py_XDECREF(st->st_stack);
501
4.71k
    PyMem_Free((void *)st);
502
4.71k
}
503
504
PySTEntryObject *
505
_PySymtable_Lookup(struct symtable *st, void *key)
506
21.6k
{
507
21.6k
    PyObject *k, *v;
508
509
21.6k
    k = PyLong_FromVoidPtr(key);
510
21.6k
    if (k == NULL)
511
0
        return NULL;
512
21.6k
    if (PyDict_GetItemRef(st->st_blocks, k, &v) == 0) {
513
0
        PyErr_SetString(PyExc_KeyError,
514
0
                        "unknown symbol table entry");
515
0
    }
516
21.6k
    Py_DECREF(k);
517
518
21.6k
    assert(v == NULL || PySTEntry_Check(v));
519
21.6k
    return (PySTEntryObject *)v;
520
21.6k
}
521
522
int
523
_PySymtable_LookupOptional(struct symtable *st, void *key,
524
                           PySTEntryObject **out)
525
4.08k
{
526
4.08k
    PyObject *k = PyLong_FromVoidPtr(key);
527
4.08k
    if (k == NULL) {
528
0
        *out = NULL;
529
0
        return -1;
530
0
    }
531
4.08k
    int result = PyDict_GetItemRef(st->st_blocks, k, (PyObject **)out);
532
4.08k
    Py_DECREF(k);
533
4.08k
    assert(*out == NULL || PySTEntry_Check(*out));
534
4.08k
    return result;
535
4.08k
}
536
537
long
538
_PyST_GetSymbol(PySTEntryObject *ste, PyObject *name)
539
178k
{
540
178k
    PyObject *v;
541
178k
    if (PyDict_GetItemRef(ste->ste_symbols, name, &v) < 0) {
542
0
        return -1;
543
0
    }
544
178k
    if (!v) {
545
50.2k
        return 0;
546
50.2k
    }
547
128k
    long symbol = PyLong_AsLong(v);
548
128k
    Py_DECREF(v);
549
128k
    if (symbol < 0) {
550
0
        if (!PyErr_Occurred()) {
551
0
            PyErr_SetString(PyExc_SystemError, "invalid symbol");
552
0
        }
553
0
        return -1;
554
0
    }
555
128k
    return symbol;
556
128k
}
557
558
int
559
_PyST_GetScope(PySTEntryObject *ste, PyObject *name)
560
152k
{
561
152k
    long symbol = _PyST_GetSymbol(ste, name);
562
152k
    if (symbol < 0) {
563
0
        return -1;
564
0
    }
565
152k
    return SYMBOL_TO_SCOPE(symbol);
566
152k
}
567
568
int
569
_PyST_IsFunctionLike(PySTEntryObject *ste)
570
280k
{
571
280k
    return ste->ste_type == FunctionBlock
572
189k
        || ste->ste_type == AnnotationBlock
573
153k
        || ste->ste_type == TypeVariableBlock
574
153k
        || ste->ste_type == TypeAliasBlock
575
152k
        || ste->ste_type == TypeParametersBlock;
576
280k
}
577
578
static int
579
error_at_directive(PySTEntryObject *ste, PyObject *name)
580
9
{
581
9
    Py_ssize_t i;
582
9
    PyObject *data;
583
9
    assert(ste->ste_directives);
584
10
    for (i = 0; i < PyList_GET_SIZE(ste->ste_directives); i++) {
585
10
        data = PyList_GET_ITEM(ste->ste_directives, i);
586
10
        assert(PyTuple_CheckExact(data));
587
10
        assert(PyUnicode_CheckExact(PyTuple_GET_ITEM(data, 0)));
588
10
        if (PyUnicode_Compare(PyTuple_GET_ITEM(data, 0), name) == 0) {
589
9
            PyErr_RangedSyntaxLocationObject(ste->ste_table->st_filename,
590
9
                                             PyLong_AsLong(PyTuple_GET_ITEM(data, 1)),
591
9
                                             PyLong_AsLong(PyTuple_GET_ITEM(data, 2)) + 1,
592
9
                                             PyLong_AsLong(PyTuple_GET_ITEM(data, 3)),
593
9
                                             PyLong_AsLong(PyTuple_GET_ITEM(data, 4)) + 1);
594
595
0
            return 0;
596
9
        }
597
10
    }
598
0
    PyErr_SetString(PyExc_RuntimeError,
599
0
                    "BUG: internal directive bookkeeping broken");
600
0
    return 0;
601
9
}
602
603
604
/* Analyze raw symbol information to determine scope of each name.
605
606
   The next several functions are helpers for symtable_analyze(),
607
   which determines whether a name is local, global, or free.  In addition,
608
   it determines which local variables are cell variables; they provide
609
   bindings that are used for free variables in enclosed blocks.
610
611
   There are also two kinds of global variables, implicit and explicit.  An
612
   explicit global is declared with the global statement.  An implicit
613
   global is a free variable for which the compiler has found no binding
614
   in an enclosing function scope.  The implicit global is either a global
615
   or a builtin.  Python's module and class blocks use the xxx_NAME opcodes
616
   to handle these names to implement slightly odd semantics.  In such a
617
   block, the name is treated as global until it is assigned to; then it
618
   is treated as a local.
619
620
   The symbol table requires two passes to determine the scope of each name.
621
   The first pass collects raw facts from the AST via the symtable_visit_*
622
   functions: the name is a parameter here, the name is used but not defined
623
   here, etc.  The second pass analyzes these facts during a pass over the
624
   PySTEntryObjects created during pass 1.
625
626
   When a function is entered during the second pass, the parent passes
627
   the set of all name bindings visible to its children.  These bindings
628
   are used to determine if non-local variables are free or implicit globals.
629
   Names which are explicitly declared nonlocal must exist in this set of
630
   visible names - if they do not, a syntax error is raised. After doing
631
   the local analysis, it analyzes each of its child blocks using an
632
   updated set of name bindings.
633
634
   The children update the free variable set.  If a local variable is added to
635
   the free variable set by the child, the variable is marked as a cell.  The
636
   function object being defined must provide runtime storage for the variable
637
   that may outlive the function's frame.  Cell variables are removed from the
638
   free set before the analyze function returns to its parent.
639
640
   During analysis, the names are:
641
      symbols: dict mapping from symbol names to flag values (including offset scope values)
642
      scopes: dict mapping from symbol names to scope values (no offset)
643
      local: set of all symbol names local to the current scope
644
      bound: set of all symbol names local to a containing function scope
645
      free: set of all symbol names referenced but not bound in child scopes
646
      global: set of all symbol names explicitly declared as global
647
*/
648
649
#define SET_SCOPE(DICT, NAME, I) \
650
88.6k
    do { \
651
88.6k
        PyObject *o = PyLong_FromLong(I); \
652
88.6k
        if (!o) \
653
88.6k
            return 0; \
654
88.6k
        if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
655
0
            Py_DECREF(o); \
656
0
            return 0; \
657
0
        } \
658
88.6k
        Py_DECREF(o); \
659
88.6k
    } while(0)
660
661
/* Decide on scope of name, given flags.
662
663
   The namespace dictionaries may be modified to record information
664
   about the new name.  For example, a new global will add an entry to
665
   global.  A name that was global can be changed to local.
666
*/
667
668
static int
669
analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags,
670
             PyObject *bound, PyObject *local, PyObject *free,
671
             PyObject *global, PyObject *type_params, PySTEntryObject *class_entry)
672
87.5k
{
673
87.5k
    int contains;
674
87.5k
    if (flags & DEF_GLOBAL) {
675
80
        if (flags & DEF_NONLOCAL) {
676
0
            PyErr_Format(PyExc_SyntaxError,
677
0
                         "name '%U' is nonlocal and global",
678
0
                         name);
679
0
            return error_at_directive(ste, name);
680
0
        }
681
80
        SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
682
80
        if (PySet_Add(global, name) < 0)
683
0
            return 0;
684
80
        if (bound && (PySet_Discard(bound, name) < 0))
685
0
            return 0;
686
80
        return 1;
687
80
    }
688
87.4k
    if (flags & DEF_NONLOCAL) {
689
956
        if (!bound) {
690
7
            PyErr_Format(PyExc_SyntaxError,
691
7
                         "nonlocal declaration not allowed at module level");
692
7
            return error_at_directive(ste, name);
693
7
        }
694
949
        contains = PySet_Contains(bound, name);
695
949
        if (contains < 0) {
696
0
            return 0;
697
0
        }
698
949
        if (!contains) {
699
2
            PyErr_Format(PyExc_SyntaxError,
700
2
                         "no binding for nonlocal '%U' found",
701
2
                         name);
702
703
2
            return error_at_directive(ste, name);
704
2
        }
705
947
        contains = PySet_Contains(type_params, name);
706
947
        if (contains < 0) {
707
0
            return 0;
708
0
        }
709
947
        if (contains) {
710
0
            PyErr_Format(PyExc_SyntaxError,
711
0
                         "nonlocal binding not allowed for type parameter '%U'",
712
0
                         name);
713
0
            return error_at_directive(ste, name);
714
0
        }
715
947
        SET_SCOPE(scopes, name, FREE);
716
947
        return PySet_Add(free, name) >= 0;
717
947
    }
718
86.4k
    if (flags & DEF_BOUND) {
719
44.1k
        SET_SCOPE(scopes, name, LOCAL);
720
44.1k
        if (PySet_Add(local, name) < 0)
721
0
            return 0;
722
44.1k
        if (PySet_Discard(global, name) < 0)
723
0
            return 0;
724
44.1k
        if (flags & DEF_TYPE_PARAM) {
725
4.68k
            if (PySet_Add(type_params, name) < 0)
726
0
                return 0;
727
4.68k
        }
728
39.5k
        else {
729
39.5k
            if (PySet_Discard(type_params, name) < 0)
730
0
                return 0;
731
39.5k
        }
732
44.1k
        return 1;
733
44.1k
    }
734
    // If we were passed class_entry (i.e., we're in an ste_can_see_class_scope scope)
735
    // and the bound name is in that set, then the name is potentially bound both by
736
    // the immediately enclosing class namespace, and also by an outer function namespace.
737
    // In that case, we want the runtime name resolution to look at only the class
738
    // namespace and the globals (not the namespace providing the bound).
739
    // Similarly, if the name is explicitly global in the class namespace (through the
740
    // global statement), we want to also treat it as a global in this scope.
741
42.3k
    if (class_entry != NULL) {
742
8.45k
        long class_flags = _PyST_GetSymbol(class_entry, name);
743
8.45k
        if (class_flags < 0) {
744
0
            return 0;
745
0
        }
746
8.45k
        if (class_flags & DEF_GLOBAL) {
747
0
            SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
748
0
            return 1;
749
0
        }
750
8.45k
        else if ((class_flags & DEF_BOUND) && !(class_flags & DEF_NONLOCAL)) {
751
39
            SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
752
39
            return 1;
753
39
        }
754
8.45k
    }
755
    /* If an enclosing block has a binding for this name, it
756
       is a free variable rather than a global variable.
757
       Note that having a non-NULL bound implies that the block
758
       is nested.
759
    */
760
42.2k
    if (bound) {
761
34.2k
        contains = PySet_Contains(bound, name);
762
34.2k
        if (contains < 0) {
763
0
            return 0;
764
0
        }
765
34.2k
        if (contains) {
766
3.39k
            SET_SCOPE(scopes, name, FREE);
767
3.39k
            return PySet_Add(free, name) >= 0;
768
3.39k
        }
769
34.2k
    }
770
    /* If a parent has a global statement, then call it global
771
       explicit?  It could also be global implicit.
772
     */
773
38.8k
    if (global) {
774
38.8k
        contains = PySet_Contains(global, name);
775
38.8k
        if (contains < 0) {
776
0
            return 0;
777
0
        }
778
38.8k
        if (contains) {
779
0
            SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
780
0
            return 1;
781
0
        }
782
38.8k
    }
783
38.8k
    SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
784
38.8k
    return 1;
785
38.8k
}
786
787
static int
788
is_free_in_any_child(PySTEntryObject *entry, PyObject *key)
789
1.65k
{
790
1.65k
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(entry->ste_children); i++) {
791
0
        PySTEntryObject *child_ste = (PySTEntryObject *)PyList_GET_ITEM(
792
0
            entry->ste_children, i);
793
0
        long scope = _PyST_GetScope(child_ste, key);
794
0
        if (scope < 0) {
795
0
            return -1;
796
0
        }
797
0
        if (scope == FREE) {
798
0
            return 1;
799
0
        }
800
0
    }
801
1.65k
    return 0;
802
1.65k
}
803
804
static int
805
inline_comprehension(PySTEntryObject *ste, PySTEntryObject *comp,
806
                     PyObject *scopes, PyObject *comp_free,
807
                     PyObject *inlined_cells)
808
1.23k
{
809
1.23k
    PyObject *k, *v;
810
1.23k
    Py_ssize_t pos = 0;
811
1.23k
    int remove_dunder_class = 0;
812
1.23k
    int remove_dunder_classdict = 0;
813
1.23k
    int remove_dunder_cond_annotations = 0;
814
815
6.03k
    while (PyDict_Next(comp->ste_symbols, &pos, &k, &v)) {
816
        // skip comprehension parameter
817
4.80k
        long comp_flags = PyLong_AsLong(v);
818
4.80k
        if (comp_flags == -1 && PyErr_Occurred()) {
819
0
            return 0;
820
0
        }
821
4.80k
        if (comp_flags & DEF_PARAM) {
822
1.23k
            assert(_PyUnicode_EqualToASCIIString(k, ".0"));
823
1.23k
            continue;
824
1.23k
        }
825
3.57k
        int scope = SYMBOL_TO_SCOPE(comp_flags);
826
3.57k
        int only_flags = comp_flags & ((1 << SCOPE_OFFSET) - 1);
827
3.57k
        if (scope == CELL || only_flags & DEF_COMP_CELL) {
828
0
            if (PySet_Add(inlined_cells, k) < 0) {
829
0
                return 0;
830
0
            }
831
0
        }
832
3.57k
        PyObject *existing = PyDict_GetItemWithError(ste->ste_symbols, k);
833
3.57k
        if (existing == NULL && PyErr_Occurred()) {
834
0
            return 0;
835
0
        }
836
        // __class__, __classdict__ and __conditional_annotations__ are
837
        // never allowed to be free through a class scope (see
838
        // drop_class_free)
839
3.57k
        if (scope == FREE && ste->ste_type == ClassBlock &&
840
0
                (_PyUnicode_EqualToASCIIString(k, "__class__") ||
841
0
                 _PyUnicode_EqualToASCIIString(k, "__classdict__") ||
842
0
                 _PyUnicode_EqualToASCIIString(k, "__conditional_annotations__"))) {
843
0
            scope = GLOBAL_IMPLICIT;
844
0
            if (PySet_Discard(comp_free, k) < 0) {
845
0
                return 0;
846
0
            }
847
848
0
            if (_PyUnicode_EqualToASCIIString(k, "__class__")) {
849
0
                remove_dunder_class = 1;
850
0
            }
851
0
            else if (_PyUnicode_EqualToASCIIString(k, "__conditional_annotations__")) {
852
0
                remove_dunder_cond_annotations = 1;
853
0
            }
854
0
            else {
855
0
                remove_dunder_classdict = 1;
856
0
            }
857
0
        }
858
3.57k
        if (!existing) {
859
            // name does not exist in scope, copy from comprehension
860
1.11k
            assert(scope != FREE || PySet_Contains(comp_free, k) == 1);
861
1.11k
            PyObject *v_flags = PyLong_FromLong(only_flags);
862
1.11k
            if (v_flags == NULL) {
863
0
                return 0;
864
0
            }
865
1.11k
            int ok = PyDict_SetItem(ste->ste_symbols, k, v_flags);
866
1.11k
            Py_DECREF(v_flags);
867
1.11k
            if (ok < 0) {
868
0
                return 0;
869
0
            }
870
1.11k
            SET_SCOPE(scopes, k, scope);
871
1.11k
        }
872
2.46k
        else {
873
2.46k
            long flags = PyLong_AsLong(existing);
874
2.46k
            if (flags == -1 && PyErr_Occurred()) {
875
0
                return 0;
876
0
            }
877
2.46k
            if ((flags & DEF_BOUND) && ste->ste_type != ClassBlock) {
878
                // free vars in comprehension that are locals in outer scope can
879
                // now simply be locals, unless they are free in comp children,
880
                // or if the outer scope is a class block
881
1.65k
                int ok = is_free_in_any_child(comp, k);
882
1.65k
                if (ok < 0) {
883
0
                    return 0;
884
0
                }
885
1.65k
                if (!ok) {
886
1.65k
                    if (PySet_Discard(comp_free, k) < 0) {
887
0
                        return 0;
888
0
                    }
889
1.65k
                }
890
1.65k
            }
891
2.46k
        }
892
3.57k
    }
893
1.23k
    if (remove_dunder_class && PyDict_DelItemString(comp->ste_symbols, "__class__") < 0) {
894
0
        return 0;
895
0
    }
896
1.23k
    if (remove_dunder_classdict && PyDict_DelItemString(comp->ste_symbols, "__classdict__") < 0) {
897
0
        return 0;
898
0
    }
899
1.23k
    if (remove_dunder_cond_annotations && PyDict_DelItemString(comp->ste_symbols, "__conditional_annotations__") < 0) {
900
0
        return 0;
901
0
    }
902
1.23k
    return 1;
903
1.23k
}
904
905
#undef SET_SCOPE
906
907
/* If a name is defined in free and also in locals, then this block
908
   provides the binding for the free variable.  The name should be
909
   marked CELL in this block and removed from the free list.
910
911
   Note that the current block's free variables are included in free.
912
   That's safe because no name can be free and local in the same scope.
913
*/
914
915
static int
916
analyze_cells(PyObject *scopes, PyObject *free, PyObject *inlined_cells)
917
13.5k
{
918
13.5k
    PyObject *name, *v, *v_cell;
919
13.5k
    int success = 0;
920
13.5k
    Py_ssize_t pos = 0;
921
922
13.5k
    v_cell = PyLong_FromLong(CELL);
923
13.5k
    if (!v_cell)
924
0
        return 0;
925
65.5k
    while (PyDict_Next(scopes, &pos, &name, &v)) {
926
52.0k
        long scope = PyLong_AsLong(v);
927
52.0k
        if (scope == -1 && PyErr_Occurred()) {
928
0
            goto error;
929
0
        }
930
52.0k
        if (scope != LOCAL)
931
22.1k
            continue;
932
29.8k
        int contains = PySet_Contains(free, name);
933
29.8k
        if (contains < 0) {
934
0
            goto error;
935
0
        }
936
29.8k
        if (!contains) {
937
29.5k
            contains = PySet_Contains(inlined_cells, name);
938
29.5k
            if (contains < 0) {
939
0
                goto error;
940
0
            }
941
29.5k
            if (!contains) {
942
29.5k
                continue;
943
29.5k
            }
944
29.5k
        }
945
        /* Replace LOCAL with CELL for this name, and remove
946
           from free. It is safe to replace the value of name
947
           in the dict, because it will not cause a resize.
948
         */
949
312
        if (PyDict_SetItem(scopes, name, v_cell) < 0)
950
0
            goto error;
951
312
        if (PySet_Discard(free, name) < 0)
952
0
            goto error;
953
312
    }
954
13.5k
    success = 1;
955
13.5k
 error:
956
13.5k
    Py_DECREF(v_cell);
957
13.5k
    return success;
958
13.5k
}
959
960
static int
961
drop_class_free(PySTEntryObject *ste, PyObject *free)
962
4.98k
{
963
4.98k
    int res;
964
4.98k
    res = PySet_Discard(free, &_Py_ID(__class__));
965
4.98k
    if (res < 0)
966
0
        return 0;
967
4.98k
    if (res)
968
0
        ste->ste_needs_class_closure = 1;
969
4.98k
    res = PySet_Discard(free, &_Py_ID(__classdict__));
970
4.98k
    if (res < 0)
971
0
        return 0;
972
4.98k
    if (res)
973
3.05k
        ste->ste_needs_classdict = 1;
974
4.98k
    res = PySet_Discard(free, &_Py_ID(__conditional_annotations__));
975
4.98k
    if (res < 0)
976
0
        return 0;
977
4.98k
    if (res) {
978
117
        ste->ste_has_conditional_annotations = 1;
979
117
    }
980
4.98k
    return 1;
981
4.98k
}
982
983
/* Enter the final scope information into the ste_symbols dict.
984
 *
985
 * All arguments are dicts.  Modifies symbols, others are read-only.
986
*/
987
static int
988
update_symbols(PyObject *symbols, PyObject *scopes,
989
               PyObject *bound, PyObject *free,
990
               PyObject *inlined_cells, int classflag)
991
23.1k
{
992
23.1k
    PyObject *name = NULL, *itr = NULL;
993
23.1k
    PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
994
23.1k
    Py_ssize_t pos = 0;
995
996
    /* Update scope information for all symbols in this scope */
997
111k
    while (PyDict_Next(symbols, &pos, &name, &v)) {
998
88.5k
        long flags = PyLong_AsLong(v);
999
88.5k
        if (flags == -1 && PyErr_Occurred()) {
1000
0
            return 0;
1001
0
        }
1002
88.5k
        int contains = PySet_Contains(inlined_cells, name);
1003
88.5k
        if (contains < 0) {
1004
0
            return 0;
1005
0
        }
1006
88.5k
        if (contains) {
1007
0
            flags |= DEF_COMP_CELL;
1008
0
        }
1009
88.5k
        if (PyDict_GetItemRef(scopes, name, &v_scope) < 0) {
1010
0
            return 0;
1011
0
        }
1012
88.5k
        if (!v_scope) {
1013
0
            PyErr_SetObject(PyExc_KeyError, name);
1014
0
            return 0;
1015
0
        }
1016
88.5k
        long scope = PyLong_AsLong(v_scope);
1017
88.5k
        Py_DECREF(v_scope);
1018
88.5k
        if (scope == -1 && PyErr_Occurred()) {
1019
0
            return 0;
1020
0
        }
1021
88.5k
        flags |= (scope << SCOPE_OFFSET);
1022
88.5k
        v_new = PyLong_FromLong(flags);
1023
88.5k
        if (!v_new)
1024
0
            return 0;
1025
88.5k
        if (PyDict_SetItem(symbols, name, v_new) < 0) {
1026
0
            Py_DECREF(v_new);
1027
0
            return 0;
1028
0
        }
1029
88.5k
        Py_DECREF(v_new);
1030
88.5k
    }
1031
1032
    /* Record not yet resolved free variables from children (if any) */
1033
23.1k
    v_free = PyLong_FromLong(FREE << SCOPE_OFFSET);
1034
23.1k
    if (!v_free)
1035
0
        return 0;
1036
1037
23.1k
    itr = PyObject_GetIter(free);
1038
23.1k
    if (itr == NULL) {
1039
0
        Py_DECREF(v_free);
1040
0
        return 0;
1041
0
    }
1042
1043
23.5k
    while ((name = PyIter_Next(itr))) {
1044
341
        v = PyDict_GetItemWithError(symbols, name);
1045
1046
        /* Handle symbol that already exists in this scope */
1047
341
        if (v) {
1048
            /* Handle a free variable in a method of
1049
               the class that has the same name as a local
1050
               or global in the class scope.
1051
            */
1052
259
            if  (classflag) {
1053
17
                long flags = PyLong_AsLong(v);
1054
17
                if (flags == -1 && PyErr_Occurred()) {
1055
0
                    goto error;
1056
0
                }
1057
17
                flags |= DEF_FREE_CLASS;
1058
17
                v_new = PyLong_FromLong(flags);
1059
17
                if (!v_new) {
1060
0
                    goto error;
1061
0
                }
1062
17
                if (PyDict_SetItem(symbols, name, v_new) < 0) {
1063
0
                    Py_DECREF(v_new);
1064
0
                    goto error;
1065
0
                }
1066
17
                Py_DECREF(v_new);
1067
17
            }
1068
            /* It's a cell, or already free in this scope */
1069
259
            Py_DECREF(name);
1070
259
            continue;
1071
259
        }
1072
82
        else if (PyErr_Occurred()) {
1073
0
            goto error;
1074
0
        }
1075
        /* Handle global symbol */
1076
82
        if (bound) {
1077
82
            int contains = PySet_Contains(bound, name);
1078
82
            if (contains < 0) {
1079
0
                goto error;
1080
0
            }
1081
82
            if (!contains) {
1082
0
                Py_DECREF(name);
1083
0
                continue;       /* it's a global */
1084
0
            }
1085
82
        }
1086
        /* Propagate new free symbol up the lexical stack */
1087
82
        if (PyDict_SetItem(symbols, name, v_free) < 0) {
1088
0
            goto error;
1089
0
        }
1090
82
        Py_DECREF(name);
1091
82
    }
1092
1093
    /* Check if loop ended because of exception in PyIter_Next */
1094
23.1k
    if (PyErr_Occurred()) {
1095
0
        goto error;
1096
0
    }
1097
1098
23.1k
    Py_DECREF(itr);
1099
23.1k
    Py_DECREF(v_free);
1100
23.1k
    return 1;
1101
0
error:
1102
0
    Py_XDECREF(v_free);
1103
0
    Py_XDECREF(itr);
1104
0
    Py_XDECREF(name);
1105
0
    return 0;
1106
23.1k
}
1107
1108
/* Make final symbol table decisions for block of ste.
1109
1110
   Arguments:
1111
   ste -- current symtable entry (input/output)
1112
   bound -- set of variables bound in enclosing scopes (input).  bound
1113
       is NULL for module blocks.
1114
   free -- set of free variables in enclosed scopes (output)
1115
   globals -- set of declared global variables in enclosing scopes (input)
1116
1117
   The implementation uses two mutually recursive functions,
1118
   analyze_block() and analyze_child_block().  analyze_block() is
1119
   responsible for analyzing the individual names defined in a block.
1120
   analyze_child_block() prepares temporary namespace dictionaries
1121
   used to evaluated nested blocks.
1122
1123
   The two functions exist because a child block should see the name
1124
   bindings of its enclosing blocks, but those bindings should not
1125
   propagate back to a parent block.
1126
*/
1127
1128
static int
1129
analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
1130
                    PyObject *global, PyObject *type_params,
1131
                    PySTEntryObject *class_entry, PyObject **child_free);
1132
1133
static int
1134
analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
1135
              PyObject *global, PyObject *type_params,
1136
              PySTEntryObject *class_entry)
1137
23.1k
{
1138
23.1k
    PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
1139
23.1k
    PyObject *newglobal = NULL, *newfree = NULL, *inlined_cells = NULL;
1140
23.1k
    PyObject *temp;
1141
23.1k
    int success = 0;
1142
23.1k
    Py_ssize_t i, pos = 0;
1143
1144
23.1k
    local = PySet_New(NULL);  /* collect new names bound in block */
1145
23.1k
    if (!local)
1146
0
        goto error;
1147
23.1k
    scopes = PyDict_New();  /* collect scopes defined for each name */
1148
23.1k
    if (!scopes)
1149
0
        goto error;
1150
1151
    /* Allocate new global, bound and free variable sets.  These
1152
       sets hold the names visible in nested blocks.  For
1153
       ClassBlocks, the bound and global names are initialized
1154
       before analyzing names, because class bindings aren't
1155
       visible in methods.  For other blocks, they are initialized
1156
       after names are analyzed.
1157
     */
1158
1159
    /* TODO(jhylton): Package these dicts in a struct so that we
1160
       can write reasonable helper functions?
1161
    */
1162
23.1k
    newglobal = PySet_New(NULL);
1163
23.1k
    if (!newglobal)
1164
0
        goto error;
1165
23.1k
    newfree = PySet_New(NULL);
1166
23.1k
    if (!newfree)
1167
0
        goto error;
1168
23.1k
    newbound = PySet_New(NULL);
1169
23.1k
    if (!newbound)
1170
0
        goto error;
1171
23.1k
    inlined_cells = PySet_New(NULL);
1172
23.1k
    if (!inlined_cells)
1173
0
        goto error;
1174
1175
    /* Class namespace has no effect on names visible in
1176
       nested functions, so populate the global and bound
1177
       sets to be passed to child blocks before analyzing
1178
       this one.
1179
     */
1180
23.1k
    if (ste->ste_type == ClassBlock) {
1181
        /* Pass down known globals */
1182
4.99k
        temp = PyNumber_InPlaceOr(newglobal, global);
1183
4.99k
        if (!temp)
1184
0
            goto error;
1185
4.99k
        Py_DECREF(temp);
1186
        /* Pass down previously bound symbols */
1187
4.99k
        if (bound) {
1188
4.99k
            temp = PyNumber_InPlaceOr(newbound, bound);
1189
4.99k
            if (!temp)
1190
0
                goto error;
1191
4.99k
            Py_DECREF(temp);
1192
4.99k
        }
1193
4.99k
    }
1194
1195
110k
    while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
1196
87.5k
        long flags = PyLong_AsLong(v);
1197
87.5k
        if (flags == -1 && PyErr_Occurred()) {
1198
0
            goto error;
1199
0
        }
1200
87.5k
        if (!analyze_name(ste, scopes, name, flags,
1201
87.5k
                          bound, local, free, global, type_params, class_entry))
1202
9
            goto error;
1203
87.5k
    }
1204
1205
    /* Populate global and bound sets to be passed to children. */
1206
23.1k
    if (ste->ste_type != ClassBlock) {
1207
        /* Add function locals to bound set */
1208
18.1k
        if (_PyST_IsFunctionLike(ste)) {
1209
13.5k
            temp = PyNumber_InPlaceOr(newbound, local);
1210
13.5k
            if (!temp)
1211
0
                goto error;
1212
13.5k
            Py_DECREF(temp);
1213
13.5k
        }
1214
        /* Pass down previously bound symbols */
1215
18.1k
        if (bound) {
1216
13.5k
            temp = PyNumber_InPlaceOr(newbound, bound);
1217
13.5k
            if (!temp)
1218
0
                goto error;
1219
13.5k
            Py_DECREF(temp);
1220
13.5k
        }
1221
        /* Pass down known globals */
1222
18.1k
        temp = PyNumber_InPlaceOr(newglobal, global);
1223
18.1k
        if (!temp)
1224
0
            goto error;
1225
18.1k
        Py_DECREF(temp);
1226
18.1k
    }
1227
4.98k
    else {
1228
        /* Special-case __class__ and __classdict__ */
1229
4.98k
        if (PySet_Add(newbound, &_Py_ID(__class__)) < 0)
1230
0
            goto error;
1231
4.98k
        if (PySet_Add(newbound, &_Py_ID(__classdict__)) < 0)
1232
0
            goto error;
1233
4.98k
        if (PySet_Add(newbound, &_Py_ID(__conditional_annotations__)) < 0)
1234
0
            goto error;
1235
4.98k
    }
1236
1237
    /* Recursively call analyze_child_block() on each child block.
1238
1239
       newbound, newglobal now contain the names visible in
1240
       nested blocks.  The free variables in the children will
1241
       be added to newfree.
1242
    */
1243
41.6k
    for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
1244
18.5k
        PyObject *child_free = NULL;
1245
18.5k
        PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
1246
0
        PySTEntryObject* entry;
1247
18.5k
        assert(c && PySTEntry_Check(c));
1248
18.5k
        entry = (PySTEntryObject*)c;
1249
1250
18.5k
        PySTEntryObject *new_class_entry = NULL;
1251
18.5k
        if (entry->ste_can_see_class_scope) {
1252
3.07k
            if (ste->ste_type == ClassBlock) {
1253
3.05k
                new_class_entry = ste;
1254
3.05k
            }
1255
17
            else if (class_entry) {
1256
17
                new_class_entry = class_entry;
1257
17
            }
1258
3.07k
        }
1259
1260
        // we inline all non-generator-expression comprehensions,
1261
        // except those in annotation scopes that are nested in classes
1262
18.5k
        int inline_comp =
1263
18.5k
            entry->ste_comprehension &&
1264
1.23k
            !entry->ste_generator &&
1265
1.23k
            !ste->ste_can_see_class_scope;
1266
1267
18.5k
        if (!analyze_child_block(entry, newbound, newfree, newglobal,
1268
18.5k
                                 type_params, new_class_entry, &child_free))
1269
3
        {
1270
3
            goto error;
1271
3
        }
1272
18.5k
        if (inline_comp) {
1273
1.23k
            if (!inline_comprehension(ste, entry, scopes, child_free, inlined_cells)) {
1274
0
                Py_DECREF(child_free);
1275
0
                goto error;
1276
0
            }
1277
1.23k
            entry->ste_comp_inlined = 1;
1278
1.23k
        }
1279
18.5k
        temp = PyNumber_InPlaceOr(newfree, child_free);
1280
18.5k
        Py_DECREF(child_free);
1281
18.5k
        if (!temp)
1282
0
            goto error;
1283
18.5k
        Py_DECREF(temp);
1284
18.5k
    }
1285
1286
    /* Splice children of inlined comprehensions into our children list */
1287
41.6k
    for (i = PyList_GET_SIZE(ste->ste_children) - 1; i >= 0; --i) {
1288
18.5k
        PyObject* c = PyList_GET_ITEM(ste->ste_children, i);
1289
0
        PySTEntryObject* entry;
1290
18.5k
        assert(c && PySTEntry_Check(c));
1291
18.5k
        entry = (PySTEntryObject*)c;
1292
18.5k
        if (entry->ste_comp_inlined &&
1293
1.23k
            PyList_SetSlice(ste->ste_children, i, i + 1,
1294
1.23k
                            entry->ste_children) < 0)
1295
0
        {
1296
0
            goto error;
1297
0
        }
1298
18.5k
    }
1299
1300
    /* Check if any local variables must be converted to cell variables */
1301
23.1k
    if (_PyST_IsFunctionLike(ste) && !analyze_cells(scopes, newfree, inlined_cells))
1302
0
        goto error;
1303
23.1k
    else if (ste->ste_type == ClassBlock && !drop_class_free(ste, newfree))
1304
0
        goto error;
1305
    /* Records the results of the analysis in the symbol table entry */
1306
23.1k
    if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, inlined_cells,
1307
23.1k
                        (ste->ste_type == ClassBlock) || ste->ste_can_see_class_scope))
1308
0
        goto error;
1309
1310
23.1k
    temp = PyNumber_InPlaceOr(free, newfree);
1311
23.1k
    if (!temp)
1312
0
        goto error;
1313
23.1k
    Py_DECREF(temp);
1314
23.1k
    success = 1;
1315
23.1k
 error:
1316
23.1k
    Py_XDECREF(scopes);
1317
23.1k
    Py_XDECREF(local);
1318
23.1k
    Py_XDECREF(newbound);
1319
23.1k
    Py_XDECREF(newglobal);
1320
23.1k
    Py_XDECREF(newfree);
1321
23.1k
    Py_XDECREF(inlined_cells);
1322
23.1k
    if (!success)
1323
23.1k
        assert(PyErr_Occurred());
1324
23.1k
    return success;
1325
23.1k
}
1326
1327
static int
1328
analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
1329
                    PyObject *global, PyObject *type_params,
1330
                    PySTEntryObject *class_entry, PyObject** child_free)
1331
18.5k
{
1332
18.5k
    PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
1333
18.5k
    PyObject *temp_type_params = NULL;
1334
1335
    /* Copy the bound/global/free sets.
1336
1337
       These sets are used by all blocks enclosed by the
1338
       current block.  The analyze_block() call modifies these
1339
       sets.
1340
1341
    */
1342
18.5k
    temp_bound = PySet_New(bound);
1343
18.5k
    if (!temp_bound)
1344
0
        goto error;
1345
18.5k
    temp_free = PySet_New(free);
1346
18.5k
    if (!temp_free)
1347
0
        goto error;
1348
18.5k
    temp_global = PySet_New(global);
1349
18.5k
    if (!temp_global)
1350
0
        goto error;
1351
18.5k
    temp_type_params = PySet_New(type_params);
1352
18.5k
    if (!temp_type_params)
1353
0
        goto error;
1354
1355
18.5k
    if (!analyze_block(entry, temp_bound, temp_free, temp_global,
1356
18.5k
                       temp_type_params, class_entry))
1357
3
        goto error;
1358
18.5k
    *child_free = temp_free;
1359
18.5k
    Py_DECREF(temp_bound);
1360
18.5k
    Py_DECREF(temp_global);
1361
18.5k
    Py_DECREF(temp_type_params);
1362
18.5k
    return 1;
1363
3
 error:
1364
3
    Py_XDECREF(temp_bound);
1365
3
    Py_XDECREF(temp_free);
1366
3
    Py_XDECREF(temp_global);
1367
3
    Py_XDECREF(temp_type_params);
1368
3
    return 0;
1369
18.5k
}
1370
1371
static int
1372
symtable_analyze(struct symtable *st)
1373
4.64k
{
1374
4.64k
    PyObject *free, *global, *type_params;
1375
4.64k
    int r;
1376
1377
4.64k
    free = PySet_New(NULL);
1378
4.64k
    if (!free)
1379
0
        return 0;
1380
4.64k
    global = PySet_New(NULL);
1381
4.64k
    if (!global) {
1382
0
        Py_DECREF(free);
1383
0
        return 0;
1384
0
    }
1385
4.64k
    type_params = PySet_New(NULL);
1386
4.64k
    if (!type_params) {
1387
0
        Py_DECREF(free);
1388
0
        Py_DECREF(global);
1389
0
        return 0;
1390
0
    }
1391
4.64k
    r = analyze_block(st->st_top, NULL, free, global, type_params, NULL);
1392
4.64k
    Py_DECREF(free);
1393
4.64k
    Py_DECREF(global);
1394
4.64k
    Py_DECREF(type_params);
1395
4.64k
    return r;
1396
4.64k
}
1397
1398
/* symtable_enter_block() gets a reference via ste_new.
1399
   This reference is released when the block is exited, via the DECREF
1400
   in symtable_exit_block().
1401
*/
1402
1403
static int
1404
symtable_exit_block(struct symtable *st)
1405
35.0k
{
1406
35.0k
    Py_ssize_t size;
1407
1408
35.0k
    st->st_cur = NULL;
1409
35.0k
    size = PyList_GET_SIZE(st->st_stack);
1410
35.0k
    if (size) {
1411
35.0k
        if (PyList_SetSlice(st->st_stack, size - 1, size, NULL) < 0)
1412
0
            return 0;
1413
35.0k
        if (--size)
1414
30.3k
            st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, size - 1);
1415
35.0k
    }
1416
35.0k
    return 1;
1417
35.0k
}
1418
1419
static int
1420
symtable_enter_existing_block(struct symtable *st, PySTEntryObject* ste, bool add_to_children)
1421
35.0k
{
1422
35.0k
    if (PyList_Append(st->st_stack, (PyObject *)ste) < 0) {
1423
0
        return 0;
1424
0
    }
1425
35.0k
    PySTEntryObject *prev = st->st_cur;
1426
    /* bpo-37757: For now, disallow *all* assignment expressions in the
1427
     * outermost iterator expression of a comprehension, even those inside
1428
     * a nested comprehension or a lambda expression.
1429
     */
1430
35.0k
    if (prev) {
1431
30.3k
        ste->ste_comp_iter_expr = prev->ste_comp_iter_expr;
1432
30.3k
    }
1433
    /* No need to inherit ste_mangled_names in classes, where all names
1434
     * are mangled. */
1435
35.0k
    if (prev && prev->ste_mangled_names != NULL && ste->ste_type != ClassBlock) {
1436
29
        ste->ste_mangled_names = Py_NewRef(prev->ste_mangled_names);
1437
29
    }
1438
    /* The entry is owned by the stack. Borrow it for st_cur. */
1439
35.0k
    st->st_cur = ste;
1440
1441
    /* If "from __future__ import annotations" is active,
1442
     * annotation blocks shouldn't have any affect on the symbol table since in
1443
     * the compilation stage, they will all be transformed to strings. */
1444
35.0k
    if (st->st_future->ff_features & CO_FUTURE_ANNOTATIONS && ste->ste_type == AnnotationBlock) {
1445
6.08k
        return 1;
1446
6.08k
    }
1447
1448
28.9k
    if (ste->ste_type == ModuleBlock)
1449
4.71k
        st->st_global = st->st_cur->ste_symbols;
1450
1451
28.9k
    if (add_to_children && prev) {
1452
18.8k
        if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) {
1453
0
            return 0;
1454
0
        }
1455
18.8k
    }
1456
28.9k
    return 1;
1457
28.9k
}
1458
1459
static int
1460
symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
1461
                     void *ast, _Py_SourceLocation loc)
1462
24.5k
{
1463
24.5k
    PySTEntryObject *ste = ste_new(st, name, block, ast, loc);
1464
24.5k
    if (ste == NULL)
1465
0
        return 0;
1466
24.5k
    int result = symtable_enter_existing_block(st, ste, /* add_to_children */true);
1467
24.5k
    Py_DECREF(ste);
1468
24.5k
    if (block == AnnotationBlock || block == TypeVariableBlock || block == TypeAliasBlock) {
1469
10.5k
        _Py_DECLARE_STR(format, ".format");
1470
        // We need to insert code that reads this "parameter" to the function.
1471
10.5k
        if (!symtable_add_def(st, &_Py_STR(format), DEF_PARAM, loc)) {
1472
0
            return 0;
1473
0
        }
1474
10.5k
        if (!symtable_add_def(st, &_Py_STR(format), USE, loc)) {
1475
0
            return 0;
1476
0
        }
1477
10.5k
    }
1478
24.5k
    return result;
1479
24.5k
}
1480
1481
static long
1482
symtable_lookup_entry(struct symtable *st, PySTEntryObject *ste, PyObject *name)
1483
14.2k
{
1484
14.2k
    PyObject *mangled = _Py_MaybeMangle(st->st_private, ste, name);
1485
14.2k
    if (!mangled)
1486
0
        return -1;
1487
14.2k
    long ret = _PyST_GetSymbol(ste, mangled);
1488
14.2k
    Py_DECREF(mangled);
1489
14.2k
    if (ret < 0) {
1490
0
        return -1;
1491
0
    }
1492
14.2k
    return ret;
1493
14.2k
}
1494
1495
static long
1496
symtable_lookup(struct symtable *st, PyObject *name)
1497
12.3k
{
1498
12.3k
    return symtable_lookup_entry(st, st->st_cur, name);
1499
12.3k
}
1500
1501
static int
1502
symtable_add_def_helper(struct symtable *st, PyObject *name, int flag, struct _symtable_entry *ste,
1503
                        _Py_SourceLocation loc)
1504
168k
{
1505
168k
    PyObject *o;
1506
168k
    PyObject *dict;
1507
168k
    long val;
1508
168k
    PyObject *mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1509
1510
168k
    if (!mangled)
1511
0
        return 0;
1512
168k
    dict = ste->ste_symbols;
1513
168k
    if ((o = PyDict_GetItemWithError(dict, mangled))) {
1514
73.6k
        val = PyLong_AsLong(o);
1515
73.6k
        if (val == -1 && PyErr_Occurred()) {
1516
0
            goto error;
1517
0
        }
1518
73.6k
        if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
1519
            /* Is it better to use 'mangled' or 'name' here? */
1520
9
            PyErr_Format(PyExc_SyntaxError, DUPLICATE_PARAMETER, name);
1521
9
            SET_ERROR_LOCATION(st->st_filename, loc);
1522
9
            goto error;
1523
9
        }
1524
73.6k
        if ((flag & DEF_TYPE_PARAM) && (val & DEF_TYPE_PARAM)) {
1525
0
            PyErr_Format(PyExc_SyntaxError, DUPLICATE_TYPE_PARAM, name);
1526
0
            SET_ERROR_LOCATION(st->st_filename, loc);
1527
0
            goto error;
1528
0
        }
1529
73.6k
        val |= flag;
1530
73.6k
    }
1531
95.0k
    else if (PyErr_Occurred()) {
1532
0
        goto error;
1533
0
    }
1534
95.0k
    else {
1535
95.0k
        val = flag;
1536
95.0k
    }
1537
168k
    if (ste->ste_comp_iter_target) {
1538
        /* This name is an iteration variable in a comprehension,
1539
         * so check for a binding conflict with any named expressions.
1540
         * Otherwise, mark it as an iteration variable so subsequent
1541
         * named expressions can check for conflicts.
1542
         */
1543
1.27k
        if (val & (DEF_GLOBAL | DEF_NONLOCAL)) {
1544
0
            PyErr_Format(PyExc_SyntaxError,
1545
0
                NAMED_EXPR_COMP_INNER_LOOP_CONFLICT, name);
1546
0
            SET_ERROR_LOCATION(st->st_filename, loc);
1547
0
            goto error;
1548
0
        }
1549
1.27k
        val |= DEF_COMP_ITER;
1550
1.27k
    }
1551
168k
    o = PyLong_FromLong(val);
1552
168k
    if (o == NULL)
1553
0
        goto error;
1554
168k
    if (PyDict_SetItem(dict, mangled, o) < 0) {
1555
0
        Py_DECREF(o);
1556
0
        goto error;
1557
0
    }
1558
168k
    Py_DECREF(o);
1559
1560
168k
    if (flag & DEF_PARAM) {
1561
16.0k
        if (PyList_Append(ste->ste_varnames, mangled) < 0)
1562
0
            goto error;
1563
152k
    } else if (flag & DEF_GLOBAL) {
1564
        /* XXX need to update DEF_GLOBAL for other flags too;
1565
           perhaps only DEF_FREE_GLOBAL */
1566
82
        val = 0;
1567
82
        if ((o = PyDict_GetItemWithError(st->st_global, mangled))) {
1568
54
            val = PyLong_AsLong(o);
1569
54
            if (val == -1 && PyErr_Occurred()) {
1570
0
                goto error;
1571
0
            }
1572
54
        }
1573
28
        else if (PyErr_Occurred()) {
1574
0
            goto error;
1575
0
        }
1576
82
        val |= flag;
1577
82
        o = PyLong_FromLong(val);
1578
82
        if (o == NULL)
1579
0
            goto error;
1580
82
        if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
1581
0
            Py_DECREF(o);
1582
0
            goto error;
1583
0
        }
1584
82
        Py_DECREF(o);
1585
82
    }
1586
168k
    Py_DECREF(mangled);
1587
168k
    return 1;
1588
1589
9
error:
1590
9
    Py_DECREF(mangled);
1591
9
    return 0;
1592
168k
}
1593
1594
static int
1595
check_name(struct symtable *st, PyObject *name, _Py_SourceLocation loc,
1596
           expr_context_ty ctx)
1597
79.0k
{
1598
79.0k
    if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
1599
0
        PyErr_SetString(PyExc_SyntaxError, "cannot assign to __debug__");
1600
0
        SET_ERROR_LOCATION(st->st_filename, loc);
1601
0
        return 0;
1602
0
    }
1603
79.0k
    if (ctx == Del && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
1604
0
        PyErr_SetString(PyExc_SyntaxError, "cannot delete __debug__");
1605
0
        SET_ERROR_LOCATION(st->st_filename, loc);
1606
0
        return 0;
1607
0
    }
1608
79.0k
    return 1;
1609
79.0k
}
1610
1611
static int
1612
check_keywords(struct symtable *st, asdl_keyword_seq *keywords)
1613
7.72k
{
1614
7.97k
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(keywords); i++) {
1615
246
        keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
1616
246
        if (key->arg  && !check_name(st, key->arg, LOCATION(key), Store)) {
1617
0
            return 0;
1618
0
        }
1619
246
    }
1620
7.72k
    return 1;
1621
7.72k
}
1622
1623
static int
1624
check_kwd_patterns(struct symtable *st, pattern_ty p)
1625
7
{
1626
7
    assert(p->kind == MatchClass_kind);
1627
7
    asdl_identifier_seq *kwd_attrs = p->v.MatchClass.kwd_attrs;
1628
7
    asdl_pattern_seq *kwd_patterns = p->v.MatchClass.kwd_patterns;
1629
7
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(kwd_attrs); i++) {
1630
0
        _Py_SourceLocation loc = LOCATION(asdl_seq_GET(kwd_patterns, i));
1631
0
        if (!check_name(st, asdl_seq_GET(kwd_attrs, i), loc, Store)) {
1632
0
            return 0;
1633
0
        }
1634
0
    }
1635
7
    return 1;
1636
7
}
1637
1638
static int
1639
symtable_add_def_ctx(struct symtable *st, PyObject *name, int flag,
1640
                     _Py_SourceLocation loc, expr_context_ty ctx)
1641
167k
{
1642
167k
    int write_mask = DEF_PARAM | DEF_LOCAL | DEF_IMPORT;
1643
167k
    if ((flag & write_mask) && !check_name(st, name, loc, ctx)) {
1644
0
        return 0;
1645
0
    }
1646
167k
    if ((flag & DEF_TYPE_PARAM) && st->st_cur->ste_mangled_names != NULL) {
1647
133
        if(PySet_Add(st->st_cur->ste_mangled_names, name) < 0) {
1648
0
            return 0;
1649
0
        }
1650
133
    }
1651
167k
    return symtable_add_def_helper(st, name, flag, st->st_cur, loc);
1652
167k
}
1653
1654
static int
1655
symtable_add_def(struct symtable *st, PyObject *name, int flag,
1656
                 _Py_SourceLocation loc)
1657
63.5k
{
1658
63.5k
    return symtable_add_def_ctx(st, name, flag, loc,
1659
63.5k
                                flag == USE ? Load : Store);
1660
63.5k
}
1661
1662
static int
1663
symtable_enter_type_param_block(struct symtable *st, identifier name,
1664
                               void *ast, int has_defaults, int has_kwdefaults,
1665
                               enum _stmt_kind kind, _Py_SourceLocation loc)
1666
2.54k
{
1667
2.54k
    _Py_block_ty current_type = st->st_cur->ste_type;
1668
2.54k
    if(!symtable_enter_block(st, name, TypeParametersBlock, ast, loc)) {
1669
0
        return 0;
1670
0
    }
1671
2.54k
    if (current_type == ClassBlock) {
1672
95
        st->st_cur->ste_can_see_class_scope = 1;
1673
95
        if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, loc)) {
1674
0
            return 0;
1675
0
        }
1676
95
    }
1677
2.54k
    if (kind == ClassDef_kind) {
1678
124
        _Py_DECLARE_STR(type_params, ".type_params");
1679
        // It gets "set" when we create the type params tuple and
1680
        // "used" when we build up the bases.
1681
124
        if (!symtable_add_def(st, &_Py_STR(type_params), DEF_LOCAL, loc)) {
1682
0
            return 0;
1683
0
        }
1684
124
        if (!symtable_add_def(st, &_Py_STR(type_params), USE, loc)) {
1685
0
            return 0;
1686
0
        }
1687
        // This is used for setting the generic base
1688
124
        _Py_DECLARE_STR(generic_base, ".generic_base");
1689
124
        if (!symtable_add_def(st, &_Py_STR(generic_base), DEF_LOCAL, loc)) {
1690
0
            return 0;
1691
0
        }
1692
124
        if (!symtable_add_def(st, &_Py_STR(generic_base), USE, loc)) {
1693
0
            return 0;
1694
0
        }
1695
124
    }
1696
2.54k
    if (has_defaults) {
1697
2.42k
        _Py_DECLARE_STR(defaults, ".defaults");
1698
2.42k
        if (!symtable_add_def(st, &_Py_STR(defaults), DEF_PARAM, loc)) {
1699
0
            return 0;
1700
0
        }
1701
2.42k
    }
1702
2.54k
    if (has_kwdefaults) {
1703
0
        _Py_DECLARE_STR(kwdefaults, ".kwdefaults");
1704
0
        if (!symtable_add_def(st, &_Py_STR(kwdefaults), DEF_PARAM, loc)) {
1705
0
            return 0;
1706
0
        }
1707
0
    }
1708
2.54k
    return 1;
1709
2.54k
}
1710
1711
/* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument.
1712
   They use the ASDL name to synthesize the name of the C type and the visit
1713
   function.
1714
1715
   VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is
1716
   useful if the first node in the sequence requires special treatment.
1717
1718
   ENTER_RECURSIVE macro increments the current recursion depth counter.
1719
   It should be used at the beginning of the recursive function.
1720
1721
   LEAVE_RECURSIVE macro decrements the current recursion depth counter.
1722
   It should be used at the end of the recursive function.
1723
*/
1724
1725
#define VISIT(ST, TYPE, V) \
1726
650k
    do { \
1727
650k
        if (!symtable_visit_ ## TYPE((ST), (V))) { \
1728
523
            return 0; \
1729
523
        } \
1730
650k
    } while(0)
1731
1732
#define VISIT_SEQ(ST, TYPE, SEQ) \
1733
64.5k
    do { \
1734
64.5k
        Py_ssize_t i; \
1735
64.5k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1736
205k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1737
141k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1738
141k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1739
141k
                return 0;                 \
1740
141k
        } \
1741
64.5k
    } while(0)
1742
1743
#define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) \
1744
1.26k
    do { \
1745
1.26k
        Py_ssize_t i; \
1746
1.26k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1747
1.27k
        for (i = (START); i < asdl_seq_LEN(seq); i++) { \
1748
14
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1749
14
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1750
14
                return 0;                 \
1751
14
        } \
1752
1.26k
    } while(0)
1753
1754
#define VISIT_SEQ_WITH_NULL(ST, TYPE, SEQ) \
1755
7.51k
    do { \
1756
7.51k
        int i = 0; \
1757
7.51k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1758
8.05k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1759
550
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1760
550
            if (!elt) continue; /* can be NULL */ \
1761
550
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1762
373
                return 0;             \
1763
373
        } \
1764
7.51k
    } while(0)
1765
1766
#define ENTER_CONDITIONAL_BLOCK(ST) \
1767
3.60k
    int in_conditional_block = (ST)->st_cur->ste_in_conditional_block; \
1768
3.60k
    (ST)->st_cur->ste_in_conditional_block = 1;
1769
1770
#define LEAVE_CONDITIONAL_BLOCK(ST) \
1771
3.60k
    (ST)->st_cur->ste_in_conditional_block = in_conditional_block;
1772
1773
#define ENTER_TRY_BLOCK(ST) \
1774
848
    int in_try_block = (ST)->st_cur->ste_in_try_block; \
1775
848
    (ST)->st_cur->ste_in_try_block = 1;
1776
1777
#define LEAVE_TRY_BLOCK(ST) \
1778
846
    (ST)->st_cur->ste_in_try_block = in_try_block;
1779
1780
815k
#define ENTER_RECURSIVE() \
1781
815k
if (Py_EnterRecursiveCall(" during compilation")) { \
1782
0
    return 0; \
1783
0
}
1784
1785
814k
#define LEAVE_RECURSIVE() Py_LeaveRecursiveCall();
1786
1787
1788
static int
1789
symtable_record_directive(struct symtable *st, identifier name, _Py_SourceLocation loc)
1790
1.11k
{
1791
1.11k
    PyObject *data, *mangled;
1792
1.11k
    int res;
1793
1.11k
    if (!st->st_cur->ste_directives) {
1794
988
        st->st_cur->ste_directives = PyList_New(0);
1795
988
        if (!st->st_cur->ste_directives)
1796
0
            return 0;
1797
988
    }
1798
1.11k
    mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1799
1.11k
    if (!mangled)
1800
0
        return 0;
1801
1.11k
    data = Py_BuildValue("(Niiii)", mangled, loc.lineno, loc.col_offset,
1802
1.11k
                                    loc.end_lineno, loc.end_col_offset);
1803
1.11k
    if (!data)
1804
0
        return 0;
1805
1.11k
    res = PyList_Append(st->st_cur->ste_directives, data);
1806
1.11k
    Py_DECREF(data);
1807
1.11k
    return res == 0;
1808
1.11k
}
1809
1810
static int
1811
has_kwonlydefaults(asdl_arg_seq *kwonlyargs, asdl_expr_seq *kw_defaults)
1812
2.42k
{
1813
2.42k
    for (int i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1814
0
        expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1815
0
        if (default_) {
1816
0
            return 1;
1817
0
        }
1818
0
    }
1819
2.42k
    return 0;
1820
2.42k
}
1821
1822
static int
1823
check_import_from(struct symtable *st, stmt_ty s)
1824
567
{
1825
567
    assert(s->kind == ImportFrom_kind);
1826
567
    _Py_SourceLocation fut = st->st_future->ff_location;
1827
567
    if (s->v.ImportFrom.module && s->v.ImportFrom.level == 0 &&
1828
551
        _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__") &&
1829
458
        ((s->lineno > fut.lineno) ||
1830
455
         ((s->lineno == fut.end_lineno) && (s->col_offset > fut.end_col_offset))))
1831
3
    {
1832
3
        PyErr_SetString(PyExc_SyntaxError,
1833
3
                        "from __future__ imports must occur "
1834
3
                        "at the beginning of the file");
1835
3
        SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
1836
3
        return 0;
1837
3
    }
1838
564
    return 1;
1839
567
}
1840
1841
static int
1842
check_lazy_import_context(struct symtable *st, stmt_ty s,
1843
                          const char* import_type)
1844
0
{
1845
    // Check if inside try/except block.
1846
0
    if (st->st_cur->ste_in_try_block) {
1847
0
        PyErr_Format(PyExc_SyntaxError,
1848
0
                     "lazy %s not allowed inside try/except blocks",
1849
0
                     import_type);
1850
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
1851
0
        return 0;
1852
0
    }
1853
1854
    // Check if inside function scope.
1855
0
    if (st->st_cur->ste_type == FunctionBlock) {
1856
0
        PyErr_Format(PyExc_SyntaxError,
1857
0
                     "lazy %s not allowed inside functions", import_type);
1858
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
1859
0
        return 0;
1860
0
    }
1861
1862
    // Check if inside class scope.
1863
0
    if (st->st_cur->ste_type == ClassBlock) {
1864
0
        PyErr_Format(PyExc_SyntaxError,
1865
0
                     "lazy %s not allowed inside classes", import_type);
1866
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
1867
0
        return 0;
1868
0
    }
1869
1870
0
    return 1;
1871
0
}
1872
1873
static bool
1874
allows_top_level_await(struct symtable *st)
1875
907
{
1876
907
    return (st->st_future->ff_features & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
1877
567
            st->st_cur->ste_type == ModuleBlock;
1878
907
}
1879
1880
1881
static void
1882
maybe_set_ste_coroutine_for_module(struct symtable *st, stmt_ty s)
1883
826
{
1884
826
    if (allows_top_level_await(st)) {
1885
5
        st->st_cur->ste_coroutine = 1;
1886
5
    }
1887
826
}
1888
1889
static int
1890
symtable_visit_stmt(struct symtable *st, stmt_ty s)
1891
61.2k
{
1892
61.2k
    ENTER_RECURSIVE();
1893
61.2k
    switch (s->kind) {
1894
3.40k
    case FunctionDef_kind: {
1895
3.40k
        if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL, LOCATION(s)))
1896
0
            return 0;
1897
3.40k
        if (s->v.FunctionDef.args->defaults)
1898
3.40k
            VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
1899
3.40k
        if (s->v.FunctionDef.args->kw_defaults)
1900
3.40k
            VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults);
1901
3.40k
        if (s->v.FunctionDef.decorator_list)
1902
27
            VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
1903
3.40k
        if (asdl_seq_LEN(s->v.FunctionDef.type_params) > 0) {
1904
2.42k
            if (!symtable_enter_type_param_block(
1905
2.42k
                    st, s->v.FunctionDef.name,
1906
2.42k
                    (void *)s->v.FunctionDef.type_params,
1907
2.42k
                    s->v.FunctionDef.args->defaults != NULL,
1908
2.42k
                    has_kwonlydefaults(s->v.FunctionDef.args->kwonlyargs,
1909
2.42k
                                       s->v.FunctionDef.args->kw_defaults),
1910
2.42k
                    s->kind,
1911
2.42k
                    LOCATION(s))) {
1912
0
                return 0;
1913
0
            }
1914
2.42k
            VISIT_SEQ(st, type_param, s->v.FunctionDef.type_params);
1915
2.42k
        }
1916
3.40k
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
1917
3.40k
                                           LOCATION(s));
1918
3.40k
        if (!new_ste) {
1919
0
            return 0;
1920
0
        }
1921
1922
3.40k
        if (_PyAST_GetDocString(s->v.FunctionDef.body)) {
1923
491
            new_ste->ste_has_docstring = 1;
1924
491
        }
1925
1926
3.40k
        if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args,
1927
3.40k
                                        s->v.FunctionDef.returns, new_ste)) {
1928
0
            Py_DECREF(new_ste);
1929
0
            return 0;
1930
0
        }
1931
3.40k
        if (!symtable_enter_existing_block(st, new_ste, /* add_to_children */true)) {
1932
0
            Py_DECREF(new_ste);
1933
0
            return 0;
1934
0
        }
1935
3.40k
        Py_DECREF(new_ste);
1936
3.40k
        VISIT(st, arguments, s->v.FunctionDef.args);
1937
3.40k
        VISIT_SEQ(st, stmt, s->v.FunctionDef.body);
1938
3.40k
        if (!symtable_exit_block(st))
1939
0
            return 0;
1940
3.40k
        if (asdl_seq_LEN(s->v.FunctionDef.type_params) > 0) {
1941
2.42k
            if (!symtable_exit_block(st))
1942
0
                return 0;
1943
2.42k
        }
1944
3.40k
        break;
1945
3.40k
    }
1946
5.01k
    case ClassDef_kind: {
1947
5.01k
        PyObject *tmp;
1948
5.01k
        if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL, LOCATION(s)))
1949
0
            return 0;
1950
5.01k
        if (s->v.ClassDef.decorator_list)
1951
38
            VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
1952
5.01k
        tmp = st->st_private;
1953
5.01k
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
1954
124
            if (!symtable_enter_type_param_block(st, s->v.ClassDef.name,
1955
124
                                                (void *)s->v.ClassDef.type_params,
1956
124
                                                false, false, s->kind,
1957
124
                                                LOCATION(s))) {
1958
0
                return 0;
1959
0
            }
1960
124
            st->st_private = s->v.ClassDef.name;
1961
124
            st->st_cur->ste_mangled_names = PySet_New(NULL);
1962
124
            if (!st->st_cur->ste_mangled_names) {
1963
0
                return 0;
1964
0
            }
1965
124
            VISIT_SEQ(st, type_param, s->v.ClassDef.type_params);
1966
124
        }
1967
5.01k
        VISIT_SEQ(st, expr, s->v.ClassDef.bases);
1968
5.01k
        if (!check_keywords(st, s->v.ClassDef.keywords)) {
1969
0
            return 0;
1970
0
        }
1971
5.01k
        VISIT_SEQ(st, keyword, s->v.ClassDef.keywords);
1972
5.01k
        if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
1973
5.01k
                                  (void *)s, LOCATION(s))) {
1974
0
            return 0;
1975
0
        }
1976
5.01k
        st->st_private = s->v.ClassDef.name;
1977
5.01k
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
1978
124
            if (!symtable_add_def(st, &_Py_ID(__type_params__),
1979
124
                                  DEF_LOCAL, LOCATION(s))) {
1980
0
                return 0;
1981
0
            }
1982
124
            _Py_DECLARE_STR(type_params, ".type_params");
1983
124
            if (!symtable_add_def(st, &_Py_STR(type_params),
1984
124
                                  USE, LOCATION(s))) {
1985
0
                return 0;
1986
0
            }
1987
124
        }
1988
1989
5.01k
        if (_PyAST_GetDocString(s->v.ClassDef.body)) {
1990
259
            st->st_cur->ste_has_docstring = 1;
1991
259
        }
1992
1993
5.01k
        VISIT_SEQ(st, stmt, s->v.ClassDef.body);
1994
5.01k
        if (!symtable_exit_block(st))
1995
0
            return 0;
1996
5.01k
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
1997
124
            if (!symtable_exit_block(st))
1998
0
                return 0;
1999
124
        }
2000
5.01k
        st->st_private = tmp;
2001
5.01k
        break;
2002
5.01k
    }
2003
31
    case TypeAlias_kind: {
2004
31
        VISIT(st, expr, s->v.TypeAlias.name);
2005
31
        assert(s->v.TypeAlias.name->kind == Name_kind);
2006
31
        PyObject *name = s->v.TypeAlias.name->v.Name.id;
2007
31
        int is_in_class = st->st_cur->ste_type == ClassBlock;
2008
31
        int is_generic = asdl_seq_LEN(s->v.TypeAlias.type_params) > 0;
2009
31
        if (is_generic) {
2010
0
            if (!symtable_enter_type_param_block(
2011
0
                    st, name,
2012
0
                    (void *)s->v.TypeAlias.type_params,
2013
0
                    false, false, s->kind,
2014
0
                    LOCATION(s))) {
2015
0
                return 0;
2016
0
            }
2017
0
            VISIT_SEQ(st, type_param, s->v.TypeAlias.type_params);
2018
0
        }
2019
31
        if (!symtable_enter_block(st, name, TypeAliasBlock,
2020
31
                                  (void *)s, LOCATION(s))) {
2021
0
            return 0;
2022
0
        }
2023
31
        st->st_cur->ste_can_see_class_scope = is_in_class;
2024
31
        if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(s->v.TypeAlias.value))) {
2025
0
            return 0;
2026
0
        }
2027
31
        VISIT(st, expr, s->v.TypeAlias.value);
2028
31
        if (!symtable_exit_block(st))
2029
0
            return 0;
2030
31
        if (is_generic) {
2031
0
            if (!symtable_exit_block(st))
2032
0
                return 0;
2033
0
        }
2034
31
        break;
2035
31
    }
2036
250
    case Return_kind:
2037
250
        if (s->v.Return.value) {
2038
20
            VISIT(st, expr, s->v.Return.value);
2039
20
            st->st_cur->ste_returns_value = 1;
2040
20
        }
2041
250
        break;
2042
294
    case Delete_kind:
2043
294
        VISIT_SEQ(st, expr, s->v.Delete.targets);
2044
294
        break;
2045
2.08k
    case Assign_kind:
2046
2.08k
        VISIT_SEQ(st, expr, s->v.Assign.targets);
2047
2.08k
        VISIT(st, expr, s->v.Assign.value);
2048
2.08k
        break;
2049
12.4k
    case AnnAssign_kind:
2050
12.4k
        st->st_cur->ste_annotations_used = 1;
2051
12.4k
        if (s->v.AnnAssign.target->kind == Name_kind) {
2052
12.1k
            expr_ty e_name = s->v.AnnAssign.target;
2053
12.1k
            long cur = symtable_lookup(st, e_name->v.Name.id);
2054
12.1k
            if (cur < 0) {
2055
0
                return 0;
2056
0
            }
2057
12.1k
            if ((cur & (DEF_GLOBAL | DEF_NONLOCAL))
2058
0
                && (st->st_cur->ste_symbols != st->st_global)
2059
0
                && s->v.AnnAssign.simple) {
2060
0
                PyErr_Format(PyExc_SyntaxError,
2061
0
                             cur & DEF_GLOBAL ? GLOBAL_ANNOT : NONLOCAL_ANNOT,
2062
0
                             e_name->v.Name.id);
2063
0
                SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
2064
0
                return 0;
2065
0
            }
2066
12.1k
            if (s->v.AnnAssign.simple &&
2067
11.9k
                !symtable_add_def(st, e_name->v.Name.id,
2068
11.9k
                                  DEF_ANNOT | DEF_LOCAL, LOCATION(e_name))) {
2069
0
                return 0;
2070
0
            }
2071
12.1k
            else {
2072
12.1k
                if (s->v.AnnAssign.value
2073
212
                    && !symtable_add_def(st, e_name->v.Name.id, DEF_LOCAL, LOCATION(e_name))) {
2074
0
                    return 0;
2075
0
                }
2076
12.1k
            }
2077
12.1k
        }
2078
256
        else {
2079
256
            VISIT(st, expr, s->v.AnnAssign.target);
2080
256
        }
2081
12.4k
        if (!symtable_visit_annotation(st, s->v.AnnAssign.annotation,
2082
12.4k
                                       (void *)((uintptr_t)st->st_cur->ste_id + 1))) {
2083
6
            return 0;
2084
6
        }
2085
2086
12.4k
        if (s->v.AnnAssign.value) {
2087
230
            VISIT(st, expr, s->v.AnnAssign.value);
2088
230
        }
2089
12.4k
        break;
2090
12.4k
    case AugAssign_kind: {
2091
1.49k
        VISIT(st, expr, s->v.AugAssign.target);
2092
1.49k
        VISIT(st, expr, s->v.AugAssign.value);
2093
1.49k
        break;
2094
1.49k
    }
2095
1.49k
    case For_kind: {
2096
233
        VISIT(st, expr, s->v.For.target);
2097
233
        VISIT(st, expr, s->v.For.iter);
2098
233
        ENTER_CONDITIONAL_BLOCK(st);
2099
233
        VISIT_SEQ(st, stmt, s->v.For.body);
2100
233
        if (s->v.For.orelse)
2101
11
            VISIT_SEQ(st, stmt, s->v.For.orelse);
2102
233
        LEAVE_CONDITIONAL_BLOCK(st);
2103
233
        break;
2104
233
    }
2105
1.13k
    case While_kind: {
2106
1.13k
        VISIT(st, expr, s->v.While.test);
2107
1.13k
        ENTER_CONDITIONAL_BLOCK(st);
2108
1.13k
        VISIT_SEQ(st, stmt, s->v.While.body);
2109
1.13k
        if (s->v.While.orelse)
2110
0
            VISIT_SEQ(st, stmt, s->v.While.orelse);
2111
1.13k
        LEAVE_CONDITIONAL_BLOCK(st);
2112
1.13k
        break;
2113
1.13k
    }
2114
484
    case If_kind: {
2115
        /* XXX if 0: and lookup_yield() hacks */
2116
484
        VISIT(st, expr, s->v.If.test);
2117
484
        ENTER_CONDITIONAL_BLOCK(st);
2118
484
        VISIT_SEQ(st, stmt, s->v.If.body);
2119
484
        if (s->v.If.orelse)
2120
64
            VISIT_SEQ(st, stmt, s->v.If.orelse);
2121
484
        LEAVE_CONDITIONAL_BLOCK(st);
2122
484
        break;
2123
484
    }
2124
46
    case Match_kind: {
2125
46
        VISIT(st, expr, s->v.Match.subject);
2126
46
        ENTER_CONDITIONAL_BLOCK(st);
2127
46
        VISIT_SEQ(st, match_case, s->v.Match.cases);
2128
46
        LEAVE_CONDITIONAL_BLOCK(st);
2129
46
        break;
2130
46
    }
2131
34
    case Raise_kind:
2132
34
        if (s->v.Raise.exc) {
2133
10
            VISIT(st, expr, s->v.Raise.exc);
2134
9
            if (s->v.Raise.cause) {
2135
7
                VISIT(st, expr, s->v.Raise.cause);
2136
7
            }
2137
9
        }
2138
32
        break;
2139
594
    case Try_kind: {
2140
594
        ENTER_CONDITIONAL_BLOCK(st);
2141
594
        ENTER_TRY_BLOCK(st);
2142
594
        VISIT_SEQ(st, stmt, s->v.Try.body);
2143
594
        VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
2144
594
        VISIT_SEQ(st, stmt, s->v.Try.orelse);
2145
594
        VISIT_SEQ(st, stmt, s->v.Try.finalbody);
2146
593
        LEAVE_TRY_BLOCK(st);
2147
593
        LEAVE_CONDITIONAL_BLOCK(st);
2148
593
        break;
2149
594
    }
2150
254
    case TryStar_kind: {
2151
254
        ENTER_CONDITIONAL_BLOCK(st);
2152
254
        ENTER_TRY_BLOCK(st);
2153
254
        VISIT_SEQ(st, stmt, s->v.TryStar.body);
2154
254
        VISIT_SEQ(st, excepthandler, s->v.TryStar.handlers);
2155
253
        VISIT_SEQ(st, stmt, s->v.TryStar.orelse);
2156
253
        VISIT_SEQ(st, stmt, s->v.TryStar.finalbody);
2157
253
        LEAVE_TRY_BLOCK(st);
2158
253
        LEAVE_CONDITIONAL_BLOCK(st);
2159
253
        break;
2160
253
    }
2161
786
    case Assert_kind:
2162
786
        VISIT(st, expr, s->v.Assert.test);
2163
785
        if (s->v.Assert.msg)
2164
51
            VISIT(st, expr, s->v.Assert.msg);
2165
785
        break;
2166
845
    case Import_kind:
2167
845
        if (s->v.Import.is_lazy) {
2168
0
            if (!check_lazy_import_context(st, s, "import")) {
2169
0
                return 0;
2170
0
            }
2171
0
        }
2172
845
        VISIT_SEQ(st, alias, s->v.Import.names);
2173
845
        break;
2174
845
    case ImportFrom_kind:
2175
568
        if (s->v.ImportFrom.is_lazy) {
2176
0
            if (!check_lazy_import_context(st, s, "from ... import")) {
2177
0
                return 0;
2178
0
            }
2179
2180
            // Check for import *
2181
0
            for (Py_ssize_t i = 0; i < asdl_seq_LEN(s->v.ImportFrom.names);
2182
0
                 i++) {
2183
0
                alias_ty alias = (alias_ty)asdl_seq_GET(
2184
0
                    s->v.ImportFrom.names, i);
2185
0
                if (alias->name &&
2186
0
                        _PyUnicode_EqualToASCIIString(alias->name, "*")) {
2187
0
                    PyErr_SetString(PyExc_SyntaxError,
2188
0
                                    "lazy from ... import * is not allowed");
2189
0
                    SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
2190
0
                    return 0;
2191
0
                }
2192
0
            }
2193
0
        }
2194
568
        VISIT_SEQ(st, alias, s->v.ImportFrom.names);
2195
567
        if (!check_import_from(st, s)) {
2196
3
            return 0;
2197
3
        }
2198
564
        break;
2199
564
    case Global_kind: {
2200
69
        Py_ssize_t i;
2201
69
        asdl_identifier_seq *seq = s->v.Global.names;
2202
149
        for (i = 0; i < asdl_seq_LEN(seq); i++) {
2203
85
            identifier name = (identifier)asdl_seq_GET(seq, i);
2204
85
            long cur = symtable_lookup(st, name);
2205
85
            if (cur < 0)
2206
0
                return 0;
2207
85
            if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) {
2208
5
                const char* msg;
2209
5
                if (cur & DEF_PARAM) {
2210
0
                    msg = GLOBAL_PARAM;
2211
5
                } else if (cur & USE) {
2212
4
                    msg = GLOBAL_AFTER_USE;
2213
4
                } else if (cur & DEF_ANNOT) {
2214
0
                    msg = GLOBAL_ANNOT;
2215
1
                } else {  /* DEF_LOCAL */
2216
1
                    msg = GLOBAL_AFTER_ASSIGN;
2217
1
                }
2218
5
                PyErr_Format(PyExc_SyntaxError,
2219
5
                             msg, name);
2220
5
                SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
2221
5
                return 0;
2222
5
            }
2223
80
            if (!symtable_add_def(st, name, DEF_GLOBAL, LOCATION(s))) {
2224
0
                return 0;
2225
0
            }
2226
80
            if (!symtable_record_directive(st, name, LOCATION(s))) {
2227
0
                return 0;
2228
0
            }
2229
80
        }
2230
64
        break;
2231
69
    }
2232
64
    case Nonlocal_kind: {
2233
40
        Py_ssize_t i;
2234
40
        asdl_identifier_seq *seq = s->v.Nonlocal.names;
2235
112
        for (i = 0; i < asdl_seq_LEN(seq); i++) {
2236
73
            identifier name = (identifier)asdl_seq_GET(seq, i);
2237
73
            long cur = symtable_lookup(st, name);
2238
73
            if (cur < 0)
2239
0
                return 0;
2240
73
            if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) {
2241
1
                const char* msg;
2242
1
                if (cur & DEF_PARAM) {
2243
0
                    msg = NONLOCAL_PARAM;
2244
1
                } else if (cur & USE) {
2245
1
                    msg = NONLOCAL_AFTER_USE;
2246
1
                } else if (cur & DEF_ANNOT) {
2247
0
                    msg = NONLOCAL_ANNOT;
2248
0
                } else {  /* DEF_LOCAL */
2249
0
                    msg = NONLOCAL_AFTER_ASSIGN;
2250
0
                }
2251
1
                PyErr_Format(PyExc_SyntaxError, msg, name);
2252
1
                SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
2253
1
                return 0;
2254
1
            }
2255
72
            if (!symtable_add_def(st, name, DEF_NONLOCAL, LOCATION(s)))
2256
0
                return 0;
2257
72
            if (!symtable_record_directive(st, name, LOCATION(s))) {
2258
0
                return 0;
2259
0
            }
2260
72
        }
2261
39
        break;
2262
40
    }
2263
29.0k
    case Expr_kind:
2264
29.0k
        VISIT(st, expr, s->v.Expr.value);
2265
29.0k
        break;
2266
29.0k
    case Pass_kind:
2267
163
    case Break_kind:
2268
460
    case Continue_kind:
2269
        /* nothing to do here */
2270
460
        break;
2271
31
    case With_kind: {
2272
31
        ENTER_CONDITIONAL_BLOCK(st);
2273
31
        VISIT_SEQ(st, withitem, s->v.With.items);
2274
31
        VISIT_SEQ(st, stmt, s->v.With.body);
2275
30
        LEAVE_CONDITIONAL_BLOCK(st);
2276
30
        break;
2277
31
    }
2278
848
    case AsyncFunctionDef_kind: {
2279
848
        if (!symtable_add_def(st, s->v.AsyncFunctionDef.name, DEF_LOCAL, LOCATION(s)))
2280
0
            return 0;
2281
848
        if (s->v.AsyncFunctionDef.args->defaults)
2282
848
            VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.args->defaults);
2283
848
        if (s->v.AsyncFunctionDef.args->kw_defaults)
2284
848
            VISIT_SEQ_WITH_NULL(st, expr,
2285
848
                                s->v.AsyncFunctionDef.args->kw_defaults);
2286
848
        if (s->v.AsyncFunctionDef.decorator_list)
2287
13
            VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.decorator_list);
2288
848
        if (asdl_seq_LEN(s->v.AsyncFunctionDef.type_params) > 0) {
2289
0
            if (!symtable_enter_type_param_block(
2290
0
                    st, s->v.AsyncFunctionDef.name,
2291
0
                    (void *)s->v.AsyncFunctionDef.type_params,
2292
0
                    s->v.AsyncFunctionDef.args->defaults != NULL,
2293
0
                    has_kwonlydefaults(s->v.AsyncFunctionDef.args->kwonlyargs,
2294
0
                                       s->v.AsyncFunctionDef.args->kw_defaults),
2295
0
                    s->kind,
2296
0
                    LOCATION(s))) {
2297
0
                return 0;
2298
0
            }
2299
0
            VISIT_SEQ(st, type_param, s->v.AsyncFunctionDef.type_params);
2300
0
        }
2301
848
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
2302
848
                                           LOCATION(s));
2303
848
        if (!new_ste) {
2304
0
            return 0;
2305
0
        }
2306
2307
848
        if (_PyAST_GetDocString(s->v.AsyncFunctionDef.body)) {
2308
0
            new_ste->ste_has_docstring = 1;
2309
0
        }
2310
2311
848
        if (!symtable_visit_annotations(st, s, s->v.AsyncFunctionDef.args,
2312
848
                                        s->v.AsyncFunctionDef.returns, new_ste)) {
2313
1
            Py_DECREF(new_ste);
2314
1
            return 0;
2315
1
        }
2316
847
        if (!symtable_enter_existing_block(st, new_ste, /* add_to_children */true)) {
2317
0
            Py_DECREF(new_ste);
2318
0
            return 0;
2319
0
        }
2320
847
        Py_DECREF(new_ste);
2321
2322
847
        st->st_cur->ste_coroutine = 1;
2323
847
        VISIT(st, arguments, s->v.AsyncFunctionDef.args);
2324
847
        VISIT_SEQ(st, stmt, s->v.AsyncFunctionDef.body);
2325
843
        if (!symtable_exit_block(st))
2326
0
            return 0;
2327
843
        if (asdl_seq_LEN(s->v.AsyncFunctionDef.type_params) > 0) {
2328
0
            if (!symtable_exit_block(st))
2329
0
                return 0;
2330
0
        }
2331
843
        break;
2332
843
    }
2333
843
    case AsyncWith_kind: {
2334
820
        maybe_set_ste_coroutine_for_module(st, s);
2335
820
        if (!symtable_raise_if_not_coroutine(st, ASYNC_WITH_OUTSIDE_ASYNC_FUNC, LOCATION(s))) {
2336
1
            return 0;
2337
1
        }
2338
819
        ENTER_CONDITIONAL_BLOCK(st);
2339
819
        VISIT_SEQ(st, withitem, s->v.AsyncWith.items);
2340
819
        VISIT_SEQ(st, stmt, s->v.AsyncWith.body);
2341
818
        LEAVE_CONDITIONAL_BLOCK(st);
2342
818
        break;
2343
819
    }
2344
6
    case AsyncFor_kind: {
2345
6
        maybe_set_ste_coroutine_for_module(st, s);
2346
6
        if (!symtable_raise_if_not_coroutine(st, ASYNC_FOR_OUTSIDE_ASYNC_FUNC, LOCATION(s))) {
2347
1
            return 0;
2348
1
        }
2349
5
        VISIT(st, expr, s->v.AsyncFor.target);
2350
5
        VISIT(st, expr, s->v.AsyncFor.iter);
2351
5
        ENTER_CONDITIONAL_BLOCK(st);
2352
5
        VISIT_SEQ(st, stmt, s->v.AsyncFor.body);
2353
5
        if (s->v.AsyncFor.orelse)
2354
2
            VISIT_SEQ(st, stmt, s->v.AsyncFor.orelse);
2355
5
        LEAVE_CONDITIONAL_BLOCK(st);
2356
5
        break;
2357
5
    }
2358
61.2k
    }
2359
61.2k
    LEAVE_RECURSIVE();
2360
61.2k
    return 1;
2361
61.2k
}
2362
2363
static int
2364
symtable_extend_namedexpr_scope(struct symtable *st, expr_ty e)
2365
963
{
2366
963
    assert(st->st_stack);
2367
963
    assert(e->kind == Name_kind);
2368
2369
963
    PyObject *target_name = e->v.Name.id;
2370
963
    Py_ssize_t i, size;
2371
963
    struct _symtable_entry *ste;
2372
963
    size = PyList_GET_SIZE(st->st_stack);
2373
963
    assert(size);
2374
2375
    /* Iterate over the stack in reverse and add to the nearest adequate scope */
2376
2.67k
    for (i = size - 1; i >= 0; i--) {
2377
2.67k
        ste = (struct _symtable_entry *) PyList_GET_ITEM(st->st_stack, i);
2378
2379
        /* If we find a comprehension scope, check for a target
2380
         * binding conflict with iteration variables, otherwise skip it
2381
         */
2382
2.67k
        if (ste->ste_comprehension) {
2383
963
            long target_in_scope = symtable_lookup_entry(st, ste, target_name);
2384
963
            if (target_in_scope < 0) {
2385
0
                return 0;
2386
0
            }
2387
963
            if ((target_in_scope & DEF_COMP_ITER) &&
2388
0
                (target_in_scope & DEF_LOCAL)) {
2389
0
                PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_CONFLICT, target_name);
2390
0
                SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
2391
0
                return 0;
2392
0
            }
2393
963
            continue;
2394
963
        }
2395
2396
        /* If we find a FunctionBlock entry, add as GLOBAL/LOCAL or NONLOCAL/LOCAL */
2397
1.71k
        if (ste->ste_type == FunctionBlock) {
2398
962
            long target_in_scope = symtable_lookup_entry(st, ste, target_name);
2399
962
            if (target_in_scope < 0) {
2400
0
                return 0;
2401
0
            }
2402
962
            if (target_in_scope & DEF_GLOBAL) {
2403
0
                if (!symtable_add_def(st, target_name, DEF_GLOBAL, LOCATION(e)))
2404
0
                    return 0;
2405
962
            } else {
2406
962
                if (!symtable_add_def(st, target_name, DEF_NONLOCAL, LOCATION(e))) {
2407
0
                    return 0;
2408
0
                }
2409
962
            }
2410
962
            if (!symtable_record_directive(st, target_name, LOCATION(e))) {
2411
0
                return 0;
2412
0
            }
2413
2414
962
            return symtable_add_def_helper(st, target_name, DEF_LOCAL, ste, LOCATION(e));
2415
962
        }
2416
        /* If we find a ModuleBlock entry, add as GLOBAL */
2417
750
        if (ste->ste_type == ModuleBlock) {
2418
1
            if (!symtable_add_def(st, target_name, DEF_GLOBAL, LOCATION(e))) {
2419
0
                return 0;
2420
0
            }
2421
1
            if (!symtable_record_directive(st, target_name, LOCATION(e))) {
2422
0
                return 0;
2423
0
            }
2424
2425
1
            return symtable_add_def_helper(st, target_name, DEF_GLOBAL, ste, LOCATION(e));
2426
1
        }
2427
        /* Disallow usage in ClassBlock and type scopes */
2428
749
        if (ste->ste_type == ClassBlock ||
2429
749
            ste->ste_type == TypeParametersBlock ||
2430
749
            ste->ste_type == TypeAliasBlock ||
2431
749
            ste->ste_type == TypeVariableBlock) {
2432
0
            switch (ste->ste_type) {
2433
0
                case ClassBlock:
2434
0
                    PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_IN_CLASS);
2435
0
                    break;
2436
0
                case TypeParametersBlock:
2437
0
                    PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_IN_TYPEPARAM);
2438
0
                    break;
2439
0
                case TypeAliasBlock:
2440
0
                    PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_IN_TYPEALIAS);
2441
0
                    break;
2442
0
                case TypeVariableBlock:
2443
0
                    PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_IN_TYPEVAR_BOUND);
2444
0
                    break;
2445
0
                default:
2446
0
                    Py_UNREACHABLE();
2447
0
            }
2448
0
            SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
2449
0
            return 0;
2450
0
        }
2451
749
    }
2452
2453
    /* We should always find either a function-like block, ModuleBlock or ClassBlock
2454
       and should never fall to this case
2455
    */
2456
963
    Py_UNREACHABLE();
2457
0
    return 0;
2458
963
}
2459
2460
static int
2461
symtable_handle_namedexpr(struct symtable *st, expr_ty e)
2462
1.01k
{
2463
1.01k
    if (st->st_cur->ste_comp_iter_expr > 0) {
2464
        /* Assignment isn't allowed in a comprehension iterable expression */
2465
0
        PyErr_Format(PyExc_SyntaxError, NAMED_EXPR_COMP_ITER_EXPR);
2466
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
2467
0
        return 0;
2468
0
    }
2469
1.01k
    if (st->st_cur->ste_comprehension) {
2470
        /* Inside a comprehension body, so find the right target scope */
2471
963
        if (!symtable_extend_namedexpr_scope(st, e->v.NamedExpr.target))
2472
0
            return 0;
2473
963
    }
2474
1.01k
    VISIT(st, expr, e->v.NamedExpr.value);
2475
1.01k
    VISIT(st, expr, e->v.NamedExpr.target);
2476
1.01k
    return 1;
2477
1.01k
}
2478
2479
static int
2480
symtable_visit_expr(struct symtable *st, expr_ty e)
2481
748k
{
2482
748k
    ENTER_RECURSIVE();
2483
748k
    switch (e->kind) {
2484
1.02k
    case NamedExpr_kind:
2485
1.02k
        if (!symtable_raise_if_annotation_block(st, "named expression", e)) {
2486
2
            return 0;
2487
2
        }
2488
1.01k
        if(!symtable_handle_namedexpr(st, e))
2489
0
            return 0;
2490
1.01k
        break;
2491
1.38k
    case BoolOp_kind:
2492
1.38k
        VISIT_SEQ(st, expr, e->v.BoolOp.values);
2493
1.37k
        break;
2494
241k
    case BinOp_kind:
2495
241k
        VISIT(st, expr, e->v.BinOp.left);
2496
241k
        VISIT(st, expr, e->v.BinOp.right);
2497
241k
        break;
2498
241k
    case UnaryOp_kind:
2499
88.7k
        VISIT(st, expr, e->v.UnaryOp.operand);
2500
88.7k
        break;
2501
88.7k
    case Lambda_kind: {
2502
508
        if (e->v.Lambda.args->defaults)
2503
508
            VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
2504
508
        if (e->v.Lambda.args->kw_defaults)
2505
508
            VISIT_SEQ_WITH_NULL(st, expr, e->v.Lambda.args->kw_defaults);
2506
508
        if (!symtable_enter_block(st, &_Py_STR(anon_lambda),
2507
508
                                  FunctionBlock, (void *)e, LOCATION(e))) {
2508
0
            return 0;
2509
0
        }
2510
508
        VISIT(st, arguments, e->v.Lambda.args);
2511
500
        VISIT(st, expr, e->v.Lambda.body);
2512
491
        if (!symtable_exit_block(st))
2513
0
            return 0;
2514
491
        break;
2515
491
    }
2516
491
    case IfExp_kind:
2517
330
        VISIT(st, expr, e->v.IfExp.test);
2518
328
        VISIT(st, expr, e->v.IfExp.body);
2519
327
        VISIT(st, expr, e->v.IfExp.orelse);
2520
323
        break;
2521
323
    case Dict_kind:
2522
34
        VISIT_SEQ_WITH_NULL(st, expr, e->v.Dict.keys);
2523
34
        VISIT_SEQ(st, expr, e->v.Dict.values);
2524
34
        break;
2525
400
    case Set_kind:
2526
400
        VISIT_SEQ(st, expr, e->v.Set.elts);
2527
396
        break;
2528
396
    case GeneratorExp_kind:
2529
6
        if (!symtable_visit_genexp(st, e))
2530
0
            return 0;
2531
6
        break;
2532
6
    case ListComp_kind:
2533
1
        if (!symtable_visit_listcomp(st, e))
2534
0
            return 0;
2535
1
        break;
2536
1.13k
    case SetComp_kind:
2537
1.13k
        if (!symtable_visit_setcomp(st, e))
2538
5
            return 0;
2539
1.12k
        break;
2540
1.12k
    case DictComp_kind:
2541
123
        if (!symtable_visit_dictcomp(st, e))
2542
2
            return 0;
2543
121
        break;
2544
121
    case Yield_kind:
2545
84
        if (!symtable_raise_if_annotation_block(st, "yield expression", e)) {
2546
1
            return 0;
2547
1
        }
2548
83
        if (e->v.Yield.value)
2549
8
            VISIT(st, expr, e->v.Yield.value);
2550
83
        st->st_cur->ste_generator = 1;
2551
83
        if (st->st_cur->ste_comprehension) {
2552
0
            return symtable_raise_if_comprehension_block(st, e);
2553
0
        }
2554
83
        break;
2555
83
    case YieldFrom_kind:
2556
0
        if (!symtable_raise_if_annotation_block(st, "yield expression", e)) {
2557
0
            return 0;
2558
0
        }
2559
0
        VISIT(st, expr, e->v.YieldFrom.value);
2560
0
        st->st_cur->ste_generator = 1;
2561
0
        if (st->st_cur->ste_comprehension) {
2562
0
            return symtable_raise_if_comprehension_block(st, e);
2563
0
        }
2564
0
        break;
2565
80
    case Await_kind:
2566
80
        if (!symtable_raise_if_annotation_block(st, "await expression", e)) {
2567
3
            return 0;
2568
3
        }
2569
77
        if (!allows_top_level_await(st)) {
2570
44
            if (!_PyST_IsFunctionLike(st->st_cur)) {
2571
28
                PyErr_SetString(PyExc_SyntaxError,
2572
28
                                "'await' outside function");
2573
28
                SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
2574
28
                return 0;
2575
28
            }
2576
16
            if (!IS_ASYNC_DEF(st) && st->st_cur->ste_comprehension == NoComprehension) {
2577
3
                PyErr_SetString(PyExc_SyntaxError,
2578
3
                                "'await' outside async function");
2579
3
                SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
2580
3
                return 0;
2581
3
            }
2582
16
        }
2583
46
        VISIT(st, expr, e->v.Await.value);
2584
46
        st->st_cur->ste_coroutine = 1;
2585
46
        break;
2586
6.42k
    case Compare_kind:
2587
6.42k
        VISIT(st, expr, e->v.Compare.left);
2588
6.41k
        VISIT_SEQ(st, expr, e->v.Compare.comparators);
2589
6.41k
        break;
2590
6.41k
    case Call_kind:
2591
2.71k
        VISIT(st, expr, e->v.Call.func);
2592
2.71k
        VISIT_SEQ(st, expr, e->v.Call.args);
2593
2.71k
        if (!check_keywords(st, e->v.Call.keywords)) {
2594
0
            return 0;
2595
0
        }
2596
2.71k
        VISIT_SEQ_WITH_NULL(st, keyword, e->v.Call.keywords);
2597
2.71k
        break;
2598
2.71k
    case FormattedValue_kind:
2599
319
        VISIT(st, expr, e->v.FormattedValue.value);
2600
316
        if (e->v.FormattedValue.format_spec)
2601
75
            VISIT(st, expr, e->v.FormattedValue.format_spec);
2602
316
        break;
2603
316
    case Interpolation_kind:
2604
194
        VISIT(st, expr, e->v.Interpolation.value);
2605
194
        if (e->v.Interpolation.format_spec)
2606
15
            VISIT(st, expr, e->v.Interpolation.format_spec);
2607
194
        break;
2608
370
    case JoinedStr_kind:
2609
370
        VISIT_SEQ(st, expr, e->v.JoinedStr.values);
2610
367
        break;
2611
367
    case TemplateStr_kind:
2612
192
        VISIT_SEQ(st, expr, e->v.TemplateStr.values);
2613
192
        break;
2614
270k
    case Constant_kind:
2615
        /* Nothing to do here. */
2616
270k
        break;
2617
    /* The following exprs can be assignment targets. */
2618
5.02k
    case Attribute_kind:
2619
5.02k
        if (!check_name(st, e->v.Attribute.attr, LOCATION(e), e->v.Attribute.ctx)) {
2620
0
            return 0;
2621
0
        }
2622
5.02k
        VISIT(st, expr, e->v.Attribute.value);
2623
5.02k
        break;
2624
5.02k
    case Subscript_kind:
2625
2.12k
        VISIT(st, expr, e->v.Subscript.value);
2626
2.12k
        VISIT(st, expr, e->v.Subscript.slice);
2627
2.11k
        break;
2628
2.11k
    case Starred_kind:
2629
1.03k
        VISIT(st, expr, e->v.Starred.value);
2630
1.03k
        break;
2631
2.02k
    case Slice_kind:
2632
2.02k
        if (e->v.Slice.lower)
2633
1.61k
            VISIT(st, expr, e->v.Slice.lower);
2634
2.02k
        if (e->v.Slice.upper)
2635
435
            VISIT(st, expr, e->v.Slice.upper);
2636
2.02k
        if (e->v.Slice.step)
2637
857
            VISIT(st, expr, e->v.Slice.step);
2638
2.01k
        break;
2639
109k
    case Name_kind:
2640
109k
        if (!st->st_cur->ste_in_unevaluated_annotation) {
2641
104k
            if (!symtable_add_def_ctx(st, e->v.Name.id,
2642
104k
                                    e->v.Name.ctx == Load ? USE : DEF_LOCAL,
2643
104k
                                    LOCATION(e), e->v.Name.ctx)) {
2644
0
                return 0;
2645
0
            }
2646
            /* Special-case super: it counts as a use of __class__ */
2647
104k
            if (e->v.Name.ctx == Load &&
2648
76.9k
                _PyST_IsFunctionLike(st->st_cur) &&
2649
40.0k
                _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
2650
211
                if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
2651
0
                    return 0;
2652
211
            }
2653
104k
        }
2654
109k
        break;
2655
    /* child nodes of List and Tuple will have expr_context set */
2656
109k
    case List_kind:
2657
205
        VISIT_SEQ(st, expr, e->v.List.elts);
2658
200
        break;
2659
13.1k
    case Tuple_kind:
2660
13.1k
        VISIT_SEQ(st, expr, e->v.Tuple.elts);
2661
13.1k
        break;
2662
748k
    }
2663
748k
    LEAVE_RECURSIVE();
2664
748k
    return 1;
2665
748k
}
2666
2667
static int
2668
symtable_visit_type_param_bound_or_default(
2669
    struct symtable *st, expr_ty e, identifier name,
2670
    type_param_ty tp, const char *ste_scope_info)
2671
9.72k
{
2672
9.72k
    if (_PyUnicode_Equal(name, &_Py_ID(__classdict__))) {
2673
2674
0
        PyObject *error_msg = PyUnicode_FromFormat("reserved name '%U' cannot be "
2675
0
                                                   "used for type parameter", name);
2676
0
        PyErr_SetObject(PyExc_SyntaxError, error_msg);
2677
0
        Py_DECREF(error_msg);
2678
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(tp));
2679
0
        return 0;
2680
0
    }
2681
2682
9.72k
    if (e) {
2683
47
        int is_in_class = st->st_cur->ste_can_see_class_scope;
2684
47
        if (!symtable_enter_block(st, name, TypeVariableBlock, (void *)tp, LOCATION(e))) {
2685
0
            return 0;
2686
0
        }
2687
2688
47
        st->st_cur->ste_can_see_class_scope = is_in_class;
2689
47
        if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(e))) {
2690
0
            return 0;
2691
0
        }
2692
2693
47
        assert(ste_scope_info != NULL);
2694
47
        st->st_cur->ste_scope_info = ste_scope_info;
2695
47
        VISIT(st, expr, e);
2696
2697
47
        if (!symtable_exit_block(st)) {
2698
0
            return 0;
2699
0
        }
2700
47
    }
2701
9.72k
    return 1;
2702
9.72k
}
2703
2704
static int
2705
symtable_visit_type_param(struct symtable *st, type_param_ty tp)
2706
4.86k
{
2707
4.86k
    ENTER_RECURSIVE();
2708
4.86k
    switch(tp->kind) {
2709
4.86k
    case TypeVar_kind:
2710
4.86k
        if (!symtable_add_def(st, tp->v.TypeVar.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp)))
2711
0
            return 0;
2712
2713
4.86k
        const char *ste_scope_info = NULL;
2714
4.86k
        const expr_ty bound = tp->v.TypeVar.bound;
2715
4.86k
        if (bound != NULL) {
2716
37
            ste_scope_info = bound->kind == Tuple_kind ? "a TypeVar constraint" : "a TypeVar bound";
2717
37
        }
2718
2719
        // We must use a different key for the bound and default. The obvious choice would be to
2720
        // use the .bound and .default_value pointers, but that fails when the expression immediately
2721
        // inside the bound or default is a comprehension: we would reuse the same key for
2722
        // the comprehension scope. Therefore, use the address + 1 as the second key.
2723
        // The only requirement for the key is that it is unique and it matches the logic in
2724
        // compile.c where the scope is retrieved.
2725
4.86k
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVar.bound, tp->v.TypeVar.name,
2726
4.86k
                                                        tp, ste_scope_info)) {
2727
0
            return 0;
2728
0
        }
2729
2730
4.86k
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVar.default_value, tp->v.TypeVar.name,
2731
4.86k
                                                        (type_param_ty)((uintptr_t)tp + 1), "a TypeVar default")) {
2732
0
            return 0;
2733
0
        }
2734
4.86k
        break;
2735
4.86k
    case TypeVarTuple_kind:
2736
4
        if (!symtable_add_def(st, tp->v.TypeVarTuple.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) {
2737
0
            return 0;
2738
0
        }
2739
2740
4
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVarTuple.default_value, tp->v.TypeVarTuple.name,
2741
4
                                                        tp, "a TypeVarTuple default")) {
2742
0
            return 0;
2743
0
        }
2744
4
        break;
2745
4
    case ParamSpec_kind:
2746
0
        if (!symtable_add_def(st, tp->v.ParamSpec.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) {
2747
0
            return 0;
2748
0
        }
2749
2750
0
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.ParamSpec.default_value, tp->v.ParamSpec.name,
2751
0
                                                        tp, "a ParamSpec default")) {
2752
0
            return 0;
2753
0
        }
2754
0
        break;
2755
4.86k
    }
2756
4.86k
    LEAVE_RECURSIVE();
2757
4.86k
    return 1;
2758
4.86k
}
2759
2760
static int
2761
symtable_visit_pattern(struct symtable *st, pattern_ty p)
2762
387
{
2763
387
    ENTER_RECURSIVE();
2764
387
    switch (p->kind) {
2765
33
    case MatchValue_kind:
2766
33
        VISIT(st, expr, p->v.MatchValue.value);
2767
33
        break;
2768
33
    case MatchSingleton_kind:
2769
        /* Nothing to do here. */
2770
16
        break;
2771
79
    case MatchSequence_kind:
2772
79
        VISIT_SEQ(st, pattern, p->v.MatchSequence.patterns);
2773
79
        break;
2774
79
    case MatchStar_kind:
2775
11
        if (p->v.MatchStar.name) {
2776
11
            if (!symtable_add_def(st, p->v.MatchStar.name, DEF_LOCAL, LOCATION(p))) {
2777
0
                return 0;
2778
0
            }
2779
11
        }
2780
11
        break;
2781
11
    case MatchMapping_kind:
2782
0
        VISIT_SEQ(st, expr, p->v.MatchMapping.keys);
2783
0
        VISIT_SEQ(st, pattern, p->v.MatchMapping.patterns);
2784
0
        if (p->v.MatchMapping.rest) {
2785
0
            if (!symtable_add_def(st, p->v.MatchMapping.rest, DEF_LOCAL, LOCATION(p))) {
2786
0
                return 0;
2787
0
            }
2788
0
        }
2789
0
        break;
2790
7
    case MatchClass_kind:
2791
7
        VISIT(st, expr, p->v.MatchClass.cls);
2792
7
        VISIT_SEQ(st, pattern, p->v.MatchClass.patterns);
2793
7
        if (!check_kwd_patterns(st, p)) {
2794
0
            return 0;
2795
0
        }
2796
7
        VISIT_SEQ(st, pattern, p->v.MatchClass.kwd_patterns);
2797
7
        break;
2798
234
    case MatchAs_kind:
2799
234
        if (p->v.MatchAs.pattern) {
2800
19
            VISIT(st, pattern, p->v.MatchAs.pattern);
2801
19
        }
2802
234
        if (p->v.MatchAs.name) {
2803
227
            if (!symtable_add_def(st, p->v.MatchAs.name, DEF_LOCAL, LOCATION(p))) {
2804
0
                return 0;
2805
0
            }
2806
227
        }
2807
234
        break;
2808
234
    case MatchOr_kind:
2809
7
        VISIT_SEQ(st, pattern, p->v.MatchOr.patterns);
2810
7
        break;
2811
387
    }
2812
387
    LEAVE_RECURSIVE();
2813
387
    return 1;
2814
387
}
2815
2816
static int
2817
symtable_implicit_arg(struct symtable *st, int pos)
2818
1.26k
{
2819
1.26k
    PyObject *id = PyUnicode_FromFormat(".%d", pos);
2820
1.26k
    if (id == NULL)
2821
0
        return 0;
2822
1.26k
    if (!symtable_add_def(st, id, DEF_PARAM, st->st_cur->ste_loc)) {
2823
0
        Py_DECREF(id);
2824
0
        return 0;
2825
0
    }
2826
1.26k
    Py_DECREF(id);
2827
1.26k
    return 1;
2828
1.26k
}
2829
2830
static int
2831
symtable_visit_params(struct symtable *st, asdl_arg_seq *args)
2832
14.2k
{
2833
14.2k
    Py_ssize_t i;
2834
2835
15.3k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2836
1.11k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2837
1.11k
        if (!symtable_add_def(st, arg->arg, DEF_PARAM, LOCATION(arg)))
2838
8
            return 0;
2839
1.11k
    }
2840
2841
14.2k
    return 1;
2842
14.2k
}
2843
2844
static int
2845
symtable_visit_annotation(struct symtable *st, expr_ty annotation, void *key)
2846
12.4k
{
2847
    // Annotations in local scopes are not executed and should not affect the symtable
2848
12.4k
    bool is_unevaluated = st->st_cur->ste_type == FunctionBlock;
2849
2850
    // Module-level annotations are always considered conditional because the module
2851
    // may be partially executed.
2852
12.4k
    if ((((st->st_cur->ste_type == ClassBlock && st->st_cur->ste_in_conditional_block)
2853
11.5k
            || st->st_cur->ste_type == ModuleBlock))
2854
2.76k
            && !st->st_cur->ste_has_conditional_annotations)
2855
1.49k
    {
2856
1.49k
        st->st_cur->ste_has_conditional_annotations = 1;
2857
1.49k
        if (!symtable_add_def(st, &_Py_ID(__conditional_annotations__), USE, LOCATION(annotation))) {
2858
0
            return 0;
2859
0
        }
2860
1.49k
    }
2861
12.4k
    struct _symtable_entry *parent_ste = st->st_cur;
2862
12.4k
    if (parent_ste->ste_annotation_block == NULL) {
2863
6.20k
        _Py_block_ty current_type = parent_ste->ste_type;
2864
6.20k
        if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2865
6.20k
                                    key, LOCATION(annotation))) {
2866
0
            return 0;
2867
0
        }
2868
6.20k
        parent_ste->ste_annotation_block =
2869
6.20k
            (struct _symtable_entry *)Py_NewRef(st->st_cur);
2870
6.20k
        int future_annotations = st->st_future->ff_features & CO_FUTURE_ANNOTATIONS;
2871
6.20k
        if (current_type == ClassBlock && !future_annotations) {
2872
2.98k
            st->st_cur->ste_can_see_class_scope = 1;
2873
2.98k
            if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(annotation))) {
2874
0
                return 0;
2875
0
            }
2876
2.98k
        }
2877
6.20k
    }
2878
6.22k
    else {
2879
6.22k
        if (!symtable_enter_existing_block(st, parent_ste->ste_annotation_block,
2880
6.22k
                                           /* add_to_children */false)) {
2881
0
            return 0;
2882
0
        }
2883
6.22k
    }
2884
12.4k
    if (is_unevaluated) {
2885
2.98k
        st->st_cur->ste_in_unevaluated_annotation = 1;
2886
2.98k
    }
2887
12.4k
    int rc = symtable_visit_expr(st, annotation);
2888
12.4k
    if (is_unevaluated) {
2889
2.98k
        st->st_cur->ste_in_unevaluated_annotation = 0;
2890
2.98k
    }
2891
12.4k
    if (!symtable_exit_block(st)) {
2892
0
        return 0;
2893
0
    }
2894
12.4k
    return rc;
2895
12.4k
}
2896
2897
static int
2898
symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args)
2899
12.7k
{
2900
12.7k
    Py_ssize_t i;
2901
2902
13.3k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2903
585
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2904
585
        if (arg->annotation) {
2905
54
            st->st_cur->ste_annotations_used = 1;
2906
54
            VISIT(st, expr, arg->annotation);
2907
54
        }
2908
585
    }
2909
2910
12.7k
    return 1;
2911
12.7k
}
2912
2913
static int
2914
symtable_visit_annotations(struct symtable *st, stmt_ty o, arguments_ty a, expr_ty returns,
2915
                           struct _symtable_entry *function_ste)
2916
4.25k
{
2917
4.25k
    int is_in_class = st->st_cur->ste_can_see_class_scope;
2918
4.25k
    _Py_block_ty current_type = st->st_cur->ste_type;
2919
4.25k
    if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2920
4.25k
                              (void *)a, LOCATION(o))) {
2921
0
        return 0;
2922
0
    }
2923
4.25k
    Py_XSETREF(st->st_cur->ste_function_name, Py_NewRef(function_ste->ste_name));
2924
4.25k
    if (is_in_class || current_type == ClassBlock) {
2925
0
        st->st_cur->ste_can_see_class_scope = 1;
2926
0
        if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(o))) {
2927
0
            return 0;
2928
0
        }
2929
0
    }
2930
4.25k
    if (a->posonlyargs && !symtable_visit_argannotations(st, a->posonlyargs))
2931
0
        return 0;
2932
4.25k
    if (a->args && !symtable_visit_argannotations(st, a->args))
2933
0
        return 0;
2934
4.25k
    if (a->vararg && a->vararg->annotation) {
2935
105
        st->st_cur->ste_annotations_used = 1;
2936
105
        VISIT(st, expr, a->vararg->annotation);
2937
105
    }
2938
4.25k
    if (a->kwarg && a->kwarg->annotation) {
2939
289
        st->st_cur->ste_annotations_used = 1;
2940
289
        VISIT(st, expr, a->kwarg->annotation);
2941
289
    }
2942
4.25k
    if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs))
2943
0
        return 0;
2944
4.25k
    if (returns) {
2945
933
        st->st_cur->ste_annotations_used = 1;
2946
933
        VISIT(st, expr, returns);
2947
933
    }
2948
4.25k
    if (!symtable_exit_block(st)) {
2949
0
        return 0;
2950
0
    }
2951
4.25k
    return 1;
2952
4.25k
}
2953
2954
static int
2955
symtable_visit_arguments(struct symtable *st, arguments_ty a)
2956
4.76k
{
2957
    /* skip default arguments inside function block
2958
       XXX should ast be different?
2959
    */
2960
4.76k
    if (a->posonlyargs && !symtable_visit_params(st, a->posonlyargs))
2961
4
        return 0;
2962
4.76k
    if (a->args && !symtable_visit_params(st, a->args))
2963
1
        return 0;
2964
4.75k
    if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs))
2965
3
        return 0;
2966
4.75k
    if (a->vararg) {
2967
309
        if (!symtable_add_def(st, a->vararg->arg, DEF_PARAM, LOCATION(a->vararg)))
2968
1
            return 0;
2969
308
        st->st_cur->ste_varargs = 1;
2970
308
    }
2971
4.75k
    if (a->kwarg) {
2972
373
        if (!symtable_add_def(st, a->kwarg->arg, DEF_PARAM, LOCATION(a->kwarg)))
2973
0
            return 0;
2974
373
        st->st_cur->ste_varkeywords = 1;
2975
373
    }
2976
4.75k
    return 1;
2977
4.75k
}
2978
2979
2980
static int
2981
symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
2982
675
{
2983
675
    if (eh->v.ExceptHandler.type)
2984
360
        VISIT(st, expr, eh->v.ExceptHandler.type);
2985
675
    if (eh->v.ExceptHandler.name)
2986
3
        if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL, LOCATION(eh)))
2987
0
            return 0;
2988
675
    VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
2989
674
    return 1;
2990
675
}
2991
2992
static int
2993
symtable_visit_withitem(struct symtable *st, withitem_ty item)
2994
4.65k
{
2995
4.65k
    VISIT(st, expr, item->context_expr);
2996
4.65k
    if (item->optional_vars) {
2997
27
        VISIT(st, expr, item->optional_vars);
2998
27
    }
2999
4.65k
    return 1;
3000
4.65k
}
3001
3002
static int
3003
symtable_visit_match_case(struct symtable *st, match_case_ty m)
3004
87
{
3005
87
    VISIT(st, pattern, m->pattern);
3006
87
    if (m->guard) {
3007
2
        VISIT(st, expr, m->guard);
3008
2
    }
3009
87
    VISIT_SEQ(st, stmt, m->body);
3010
87
    return 1;
3011
87
}
3012
3013
static int
3014
symtable_visit_alias(struct symtable *st, alias_ty a)
3015
3.78k
{
3016
    /* Compute store_name, the name actually bound by the import
3017
       operation.  It is different than a->name when a->name is a
3018
       dotted package name (e.g. spam.eggs)
3019
    */
3020
3.78k
    PyObject *store_name;
3021
3.78k
    PyObject *name = (a->asname == NULL) ? a->name : a->asname;
3022
3.78k
    Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
3023
3.78k
                                        PyUnicode_GET_LENGTH(name), 1);
3024
3.78k
    if (dot != -1) {
3025
1.20k
        store_name = PyUnicode_Substring(name, 0, dot);
3026
1.20k
        if (!store_name)
3027
0
            return 0;
3028
1.20k
    }
3029
2.58k
    else {
3030
2.58k
        store_name = Py_NewRef(name);
3031
2.58k
    }
3032
3.78k
    if (!_PyUnicode_EqualToASCIIString(name, "*")) {
3033
3.78k
        int r = symtable_add_def(st, store_name, DEF_IMPORT, LOCATION(a));
3034
3.78k
        Py_DECREF(store_name);
3035
3.78k
        return r;
3036
3.78k
    }
3037
2
    else {
3038
2
        if (st->st_cur->ste_type != ModuleBlock) {
3039
1
            PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING);
3040
1
            SET_ERROR_LOCATION(st->st_filename, LOCATION(a));
3041
1
            Py_DECREF(store_name);
3042
1
            return 0;
3043
1
        }
3044
1
        Py_DECREF(store_name);
3045
1
        return 1;
3046
2
    }
3047
3.78k
}
3048
3049
3050
static int
3051
symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
3052
14
{
3053
14
    st->st_cur->ste_comp_iter_target = 1;
3054
14
    VISIT(st, expr, lc->target);
3055
14
    st->st_cur->ste_comp_iter_target = 0;
3056
14
    st->st_cur->ste_comp_iter_expr++;
3057
14
    VISIT(st, expr, lc->iter);
3058
14
    st->st_cur->ste_comp_iter_expr--;
3059
14
    VISIT_SEQ(st, expr, lc->ifs);
3060
14
    if (lc->is_async) {
3061
3
        st->st_cur->ste_coroutine = 1;
3062
3
    }
3063
14
    return 1;
3064
14
}
3065
3066
3067
static int
3068
symtable_visit_keyword(struct symtable *st, keyword_ty k)
3069
246
{
3070
246
    VISIT(st, expr, k->value);
3071
245
    return 1;
3072
246
}
3073
3074
3075
static int
3076
symtable_handle_comprehension(struct symtable *st, expr_ty e,
3077
                              identifier scope_name, asdl_comprehension_seq *generators,
3078
                              expr_ty elt, expr_ty value)
3079
1.26k
{
3080
1.26k
    int is_generator = (e->kind == GeneratorExp_kind);
3081
1.26k
    comprehension_ty outermost = ((comprehension_ty)
3082
1.26k
                                    asdl_seq_GET(generators, 0));
3083
    /* Outermost iterator is evaluated in current scope */
3084
1.26k
    st->st_cur->ste_comp_iter_expr++;
3085
1.26k
    VISIT(st, expr, outermost->iter);
3086
1.26k
    st->st_cur->ste_comp_iter_expr--;
3087
    /* Create comprehension scope for the rest */
3088
1.26k
    if (!scope_name ||
3089
1.26k
        !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, LOCATION(e))) {
3090
0
        return 0;
3091
0
    }
3092
1.26k
    switch(e->kind) {
3093
1
        case ListComp_kind:
3094
1
            st->st_cur->ste_comprehension = ListComprehension;
3095
1
            break;
3096
1.13k
        case SetComp_kind:
3097
1.13k
            st->st_cur->ste_comprehension = SetComprehension;
3098
1.13k
            break;
3099
122
        case DictComp_kind:
3100
122
            st->st_cur->ste_comprehension = DictComprehension;
3101
122
            break;
3102
6
        default:
3103
6
            st->st_cur->ste_comprehension = GeneratorExpression;
3104
6
            break;
3105
1.26k
    }
3106
1.26k
    if (outermost->is_async) {
3107
248
        st->st_cur->ste_coroutine = 1;
3108
248
    }
3109
3110
    /* Outermost iter is received as an argument */
3111
1.26k
    if (!symtable_implicit_arg(st, 0)) {
3112
0
        symtable_exit_block(st);
3113
0
        return 0;
3114
0
    }
3115
    /* Visit iteration variable target, and mark them as such */
3116
1.26k
    st->st_cur->ste_comp_iter_target = 1;
3117
1.26k
    VISIT(st, expr, outermost->target);
3118
1.26k
    st->st_cur->ste_comp_iter_target = 0;
3119
    /* Visit the rest of the comprehension body */
3120
1.26k
    VISIT_SEQ(st, expr, outermost->ifs);
3121
1.26k
    VISIT_SEQ_TAIL(st, comprehension, generators, 1);
3122
1.26k
    if (value)
3123
29
        VISIT(st, expr, value);
3124
1.26k
    VISIT(st, expr, elt);
3125
1.26k
    st->st_cur->ste_generator = is_generator;
3126
1.26k
    int is_async = st->st_cur->ste_coroutine && !is_generator;
3127
1.26k
    if (!symtable_exit_block(st)) {
3128
0
        return 0;
3129
0
    }
3130
1.26k
    if (is_async &&
3131
251
        !IS_ASYNC_DEF(st) &&
3132
5
        st->st_cur->ste_comprehension == NoComprehension &&
3133
4
        !allows_top_level_await(st))
3134
4
    {
3135
4
        PyErr_SetString(PyExc_SyntaxError, "asynchronous comprehension outside of "
3136
4
                                           "an asynchronous function");
3137
4
        SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3138
4
        return 0;
3139
4
    }
3140
1.25k
    if (is_async) {
3141
247
        st->st_cur->ste_coroutine = 1;
3142
247
    }
3143
1.25k
    return 1;
3144
1.26k
}
3145
3146
static int
3147
symtable_visit_genexp(struct symtable *st, expr_ty e)
3148
6
{
3149
6
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_genexpr),
3150
6
                                         e->v.GeneratorExp.generators,
3151
6
                                         e->v.GeneratorExp.elt, NULL);
3152
6
}
3153
3154
static int
3155
symtable_visit_listcomp(struct symtable *st, expr_ty e)
3156
1
{
3157
1
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_listcomp),
3158
1
                                         e->v.ListComp.generators,
3159
1
                                         e->v.ListComp.elt, NULL);
3160
1
}
3161
3162
static int
3163
symtable_visit_setcomp(struct symtable *st, expr_ty e)
3164
1.13k
{
3165
1.13k
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_setcomp),
3166
1.13k
                                         e->v.SetComp.generators,
3167
1.13k
                                         e->v.SetComp.elt, NULL);
3168
1.13k
}
3169
3170
static int
3171
symtable_visit_dictcomp(struct symtable *st, expr_ty e)
3172
123
{
3173
123
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_dictcomp),
3174
123
                                         e->v.DictComp.generators,
3175
123
                                         e->v.DictComp.key,
3176
123
                                         e->v.DictComp.value);
3177
123
}
3178
3179
static int
3180
symtable_raise_if_annotation_block(struct symtable *st, const char *name, expr_ty e)
3181
1.18k
{
3182
1.18k
    _Py_block_ty type = st->st_cur->ste_type;
3183
1.18k
    if (type == AnnotationBlock)
3184
6
        PyErr_Format(PyExc_SyntaxError, ANNOTATION_NOT_ALLOWED, name);
3185
1.17k
    else if (type == TypeVariableBlock) {
3186
0
        const char *info = st->st_cur->ste_scope_info;
3187
0
        assert(info != NULL); // e.g., info == "a ParamSpec default"
3188
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_VARIABLE, name, info);
3189
0
    }
3190
1.17k
    else if (type == TypeAliasBlock) {
3191
        // for now, we do not have any extra information
3192
0
        assert(st->st_cur->ste_scope_info == NULL);
3193
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_ALIAS, name);
3194
0
    }
3195
1.17k
    else if (type == TypeParametersBlock) {
3196
        // for now, we do not have any extra information
3197
0
        assert(st->st_cur->ste_scope_info == NULL);
3198
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_PARAMETERS, name);
3199
0
    }
3200
1.17k
    else
3201
1.17k
        return 1;
3202
3203
6
    SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3204
6
    return 0;
3205
1.18k
}
3206
3207
static int
3208
0
symtable_raise_if_comprehension_block(struct symtable *st, expr_ty e) {
3209
0
    _Py_comprehension_ty type = st->st_cur->ste_comprehension;
3210
0
    PyErr_SetString(PyExc_SyntaxError,
3211
0
            (type == ListComprehension) ? "'yield' inside list comprehension" :
3212
0
            (type == SetComprehension) ? "'yield' inside set comprehension" :
3213
0
            (type == DictComprehension) ? "'yield' inside dict comprehension" :
3214
0
            "'yield' inside generator expression");
3215
0
    SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3216
0
    return 0;
3217
0
}
3218
3219
static int
3220
826
symtable_raise_if_not_coroutine(struct symtable *st, const char *msg, _Py_SourceLocation loc) {
3221
826
    if (!st->st_cur->ste_coroutine) {
3222
2
        PyErr_SetString(PyExc_SyntaxError, msg);
3223
2
        SET_ERROR_LOCATION(st->st_filename, loc);
3224
2
        return 0;
3225
2
    }
3226
824
    return 1;
3227
826
}
3228
3229
struct symtable *
3230
_Py_SymtableStringObjectFlags(const char *str, PyObject *filename,
3231
                              int start, PyCompilerFlags *flags, PyObject *module)
3232
0
{
3233
0
    struct symtable *st;
3234
0
    mod_ty mod;
3235
0
    PyArena *arena;
3236
3237
0
    arena = _PyArena_New();
3238
0
    if (arena == NULL)
3239
0
        return NULL;
3240
3241
0
    mod = _PyParser_ASTFromString(str, filename, start, flags, arena, module);
3242
0
    if (mod == NULL) {
3243
0
        _PyArena_Free(arena);
3244
0
        return NULL;
3245
0
    }
3246
0
    _PyFutureFeatures future;
3247
0
    if (!_PyFuture_FromAST(mod, filename, &future)) {
3248
0
        _PyArena_Free(arena);
3249
0
        return NULL;
3250
0
    }
3251
0
    future.ff_features |= flags->cf_flags;
3252
0
    st = _PySymtable_Build(mod, filename, &future);
3253
0
    _PyArena_Free(arena);
3254
0
    return st;
3255
0
}
3256
3257
PyObject *
3258
_Py_MaybeMangle(PyObject *privateobj, PySTEntryObject *ste, PyObject *name)
3259
352k
{
3260
    /* Special case for type parameter blocks around generic classes:
3261
     * we want to mangle type parameter names (so a type param with a private
3262
     * name can be used inside the class body), but we don't want to mangle
3263
     * any other names that appear within the type parameter scope.
3264
     */
3265
352k
    if (ste->ste_mangled_names != NULL) {
3266
1.05k
        int result = PySet_Contains(ste->ste_mangled_names, name);
3267
1.05k
        if (result < 0) {
3268
0
            return NULL;
3269
0
        }
3270
1.05k
        if (result == 0) {
3271
765
            return Py_NewRef(name);
3272
765
        }
3273
1.05k
    }
3274
351k
    return _Py_Mangle(privateobj, name);
3275
352k
}
3276
3277
int
3278
_Py_IsPrivateName(PyObject *ident)
3279
0
{
3280
0
    if (!PyUnicode_Check(ident)) {
3281
0
        return 0;
3282
0
    }
3283
0
    Py_ssize_t nlen = PyUnicode_GET_LENGTH(ident);
3284
0
    if (nlen < 3 ||
3285
0
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3286
0
        PyUnicode_READ_CHAR(ident, 1) != '_')
3287
0
    {
3288
0
        return 0;
3289
0
    }
3290
0
    if (PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3291
0
        PyUnicode_READ_CHAR(ident, nlen-2) == '_')
3292
0
    {
3293
0
        return 0; /* Don't mangle __whatever__ */
3294
0
    }
3295
0
    return 1;
3296
0
}
3297
3298
PyObject *
3299
_Py_Mangle(PyObject *privateobj, PyObject *ident)
3300
359k
{
3301
    /* Name mangling: __private becomes _classname__private.
3302
       This is independent from how the name is used. */
3303
359k
    if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
3304
116k
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3305
292k
        PyUnicode_READ_CHAR(ident, 1) != '_') {
3306
292k
        return Py_NewRef(ident);
3307
292k
    }
3308
67.3k
    size_t nlen = PyUnicode_GET_LENGTH(ident);
3309
67.3k
    size_t plen = PyUnicode_GET_LENGTH(privateobj);
3310
    /* Don't mangle __id__ or names with dots.
3311
3312
       The only time a name with a dot can occur is when
3313
       we are compiling an import statement that has a
3314
       package name.
3315
3316
       TODO(jhylton): Decide whether we want to support
3317
       mangling of the module name, e.g. __M.X.
3318
    */
3319
67.3k
    if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3320
39.1k
         PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
3321
39.0k
        PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
3322
39.0k
        return Py_NewRef(ident); /* Don't mangle __whatever__ */
3323
39.0k
    }
3324
    /* Strip leading underscores from class name */
3325
28.3k
    size_t ipriv = 0;
3326
63.6k
    while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_') {
3327
35.3k
        ipriv++;
3328
35.3k
    }
3329
28.3k
    if (ipriv == plen) {
3330
340
        return Py_NewRef(ident); /* Don't mangle if class is just underscores */
3331
340
    }
3332
3333
27.9k
    if (nlen + (plen - ipriv) >= PY_SSIZE_T_MAX - 1) {
3334
0
        PyErr_SetString(PyExc_OverflowError,
3335
0
                        "private identifier too large to be mangled");
3336
0
        return NULL;
3337
0
    }
3338
3339
27.9k
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(1 + nlen + (plen - ipriv));
3340
27.9k
    if (!writer) {
3341
0
        return NULL;
3342
0
    }
3343
    // ident = "_" + priv[ipriv:] + ident
3344
27.9k
    if (PyUnicodeWriter_WriteChar(writer, '_') < 0) {
3345
0
        goto error;
3346
0
    }
3347
27.9k
    if (PyUnicodeWriter_WriteSubstring(writer, privateobj, ipriv, plen) < 0) {
3348
0
        goto error;
3349
0
    }
3350
27.9k
    if (PyUnicodeWriter_WriteStr(writer, ident) < 0) {
3351
0
        goto error;
3352
0
    }
3353
27.9k
    return PyUnicodeWriter_Finish(writer);
3354
3355
0
error:
3356
0
    PyUnicodeWriter_Discard(writer);
3357
    return NULL;
3358
27.9k
}