Coverage Report

Created: 2026-03-19 06:23

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