Coverage Report

Created: 2026-03-23 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/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
0
#define GLOBAL_AFTER_ASSIGN \
23
0
"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
0
#define GLOBAL_AFTER_USE \
29
0
"name '%U' is used prior to global declaration"
30
31
0
#define NONLOCAL_AFTER_USE \
32
0
"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
0
#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
0
#define ANNOTATION_NOT_ALLOWED \
64
0
"%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
5
#define ASYNC_WITH_OUTSIDE_ASYNC_FUNC \
79
5
"'async with' outside async function"
80
81
0
#define ASYNC_FOR_OUTSIDE_ASYNC_FUNC \
82
0
"'async for' outside async function"
83
84
88.8k
#define LOCATION(x) SRC_LOCATION_FROM_AST(x)
85
86
#define SET_ERROR_LOCATION(FNAME, L) \
87
0
    PyErr_RangedSyntaxLocationObject((FNAME), \
88
0
        (L).lineno, (L).col_offset + 1, (L).end_lineno, (L).end_col_offset + 1)
89
90
340
#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
8.95k
{
96
8.95k
    PySTEntryObject *ste = NULL;
97
8.95k
    PyObject *k = NULL;
98
99
8.95k
    k = PyLong_FromVoidPtr(key);
100
8.95k
    if (k == NULL)
101
0
        goto fail;
102
8.95k
    ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
103
8.95k
    if (ste == NULL) {
104
0
        Py_DECREF(k);
105
0
        goto fail;
106
0
    }
107
8.95k
    ste->ste_table = st;
108
8.95k
    ste->ste_id = k; /* ste owns reference to k */
109
110
8.95k
    ste->ste_name = Py_NewRef(name);
111
112
8.95k
    ste->ste_symbols = NULL;
113
8.95k
    ste->ste_varnames = NULL;
114
8.95k
    ste->ste_children = NULL;
115
116
8.95k
    ste->ste_directives = NULL;
117
8.95k
    ste->ste_mangled_names = NULL;
118
119
8.95k
    ste->ste_type = block;
120
8.95k
    ste->ste_scope_info = NULL;
121
122
8.95k
    ste->ste_nested = 0;
123
8.95k
    ste->ste_varargs = 0;
124
8.95k
    ste->ste_varkeywords = 0;
125
8.95k
    ste->ste_annotations_used = 0;
126
8.95k
    ste->ste_loc = loc;
127
128
8.95k
    if (st->st_cur != NULL &&
129
8.13k
        (st->st_cur->ste_nested ||
130
8.11k
         _PyST_IsFunctionLike(st->st_cur)))
131
2.07k
        ste->ste_nested = 1;
132
8.95k
    ste->ste_generator = 0;
133
8.95k
    ste->ste_coroutine = 0;
134
8.95k
    ste->ste_comprehension = NoComprehension;
135
8.95k
    ste->ste_returns_value = 0;
136
8.95k
    ste->ste_needs_class_closure = 0;
137
8.95k
    ste->ste_comp_inlined = 0;
138
8.95k
    ste->ste_comp_iter_target = 0;
139
8.95k
    ste->ste_can_see_class_scope = 0;
140
8.95k
    ste->ste_comp_iter_expr = 0;
141
8.95k
    ste->ste_needs_classdict = 0;
142
8.95k
    ste->ste_has_conditional_annotations = 0;
143
8.95k
    ste->ste_in_conditional_block = 0;
144
8.95k
    ste->ste_in_try_block = 0;
145
8.95k
    ste->ste_in_unevaluated_annotation = 0;
146
8.95k
    ste->ste_annotation_block = NULL;
147
148
8.95k
    ste->ste_has_docstring = 0;
149
150
8.95k
    ste->ste_method = 0;
151
8.95k
    if (st->st_cur != NULL &&
152
8.13k
        st->st_cur->ste_type == ClassBlock &&
153
3.57k
        block == FunctionBlock) {
154
1.78k
        ste->ste_method = 1;
155
1.78k
    }
156
157
8.95k
    ste->ste_symbols = PyDict_New();
158
8.95k
    ste->ste_varnames = PyList_New(0);
159
8.95k
    ste->ste_children = PyList_New(0);
160
8.95k
    if (ste->ste_symbols == NULL
161
8.95k
        || ste->ste_varnames == NULL
162
8.95k
        || ste->ste_children == NULL)
163
0
        goto fail;
164
165
8.95k
    if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
166
0
        goto fail;
167
168
8.95k
    return ste;
169
0
 fail:
170
0
    Py_XDECREF(ste);
171
0
    return NULL;
172
8.95k
}
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
8.95k
{
185
8.95k
    PySTEntryObject *ste = (PySTEntryObject *)op;
186
8.95k
    ste->ste_table = NULL;
187
8.95k
    Py_XDECREF(ste->ste_id);
188
8.95k
    Py_XDECREF(ste->ste_name);
189
8.95k
    Py_XDECREF(ste->ste_symbols);
190
8.95k
    Py_XDECREF(ste->ste_varnames);
191
8.95k
    Py_XDECREF(ste->ste_children);
192
8.95k
    Py_XDECREF(ste->ste_directives);
193
8.95k
    Py_XDECREF(ste->ste_annotation_block);
194
8.95k
    Py_XDECREF(ste->ste_mangled_names);
195
8.95k
    PyObject_Free(ste);
196
8.95k
}
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
0
#define DUPLICATE_PARAMETER \
385
0
"duplicate parameter '%U' in function definition"
386
387
static struct symtable *
388
symtable_new(void)
389
825
{
390
825
    struct symtable *st;
391
392
825
    st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
393
825
    if (st == NULL) {
394
0
        PyErr_NoMemory();
395
0
        return NULL;
396
0
    }
397
398
825
    st->st_filename = NULL;
399
825
    st->st_blocks = NULL;
400
401
825
    if ((st->st_stack = PyList_New(0)) == NULL)
402
0
        goto fail;
403
825
    if ((st->st_blocks = PyDict_New()) == NULL)
404
0
        goto fail;
405
825
    st->st_cur = NULL;
406
825
    st->st_private = NULL;
407
825
    return st;
408
0
 fail:
409
0
    _PySymtable_Free(st);
410
0
    return NULL;
411
825
}
412
413
struct symtable *
414
_PySymtable_Build(mod_ty mod, PyObject *filename, _PyFutureFeatures *future)
415
825
{
416
825
    struct symtable *st = symtable_new();
417
825
    asdl_stmt_seq *seq;
418
825
    Py_ssize_t i;
419
825
    PyThreadState *tstate;
420
421
825
    if (st == NULL)
422
0
        return NULL;
423
825
    if (filename == NULL) {
424
0
        _PySymtable_Free(st);
425
0
        return NULL;
426
0
    }
427
825
    st->st_filename = Py_NewRef(filename);
428
825
    st->st_future = future;
429
430
    /* Setup recursion depth check counters */
431
825
    tstate = _PyThreadState_GET();
432
825
    if (!tstate) {
433
0
        _PySymtable_Free(st);
434
0
        return NULL;
435
0
    }
436
437
    /* Make the initial symbol information gathering pass */
438
439
825
    _Py_SourceLocation loc0 = {0, 0, 0, 0};
440
825
    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
825
    st->st_top = st->st_cur;
446
825
    switch (mod->kind) {
447
583
    case Module_kind:
448
583
        seq = mod->v.Module.body;
449
583
        if (_PyAST_GetDocString(seq)) {
450
115
            st->st_cur->ste_has_docstring = 1;
451
115
        }
452
3.53k
        for (i = 0; i < asdl_seq_LEN(seq); i++)
453
2.95k
            if (!symtable_visit_stmt(st,
454
2.95k
                        (stmt_ty)asdl_seq_GET(seq, i)))
455
0
                goto error;
456
583
        break;
457
583
    case Expression_kind:
458
242
        if (!symtable_visit_expr(st, mod->v.Expression.body))
459
0
            goto error;
460
242
        break;
461
242
    case Interactive_kind:
462
0
        seq = mod->v.Interactive.body;
463
0
        for (i = 0; i < asdl_seq_LEN(seq); i++)
464
0
            if (!symtable_visit_stmt(st,
465
0
                        (stmt_ty)asdl_seq_GET(seq, i)))
466
0
                goto error;
467
0
        break;
468
0
    case FunctionType_kind:
469
0
        PyErr_SetString(PyExc_RuntimeError,
470
0
                        "this compiler does not handle FunctionTypes");
471
0
        goto error;
472
825
    }
473
825
    if (!symtable_exit_block(st)) {
474
0
        _PySymtable_Free(st);
475
0
        return NULL;
476
0
    }
477
    /* Make the second symbol analysis pass */
478
825
    if (symtable_analyze(st)) {
479
#if _PY_DUMP_SYMTABLE
480
        dump_symtable(st->st_top);
481
#endif
482
825
        return st;
483
825
    }
484
0
    _PySymtable_Free(st);
485
0
    return NULL;
486
0
 error:
487
0
    (void) symtable_exit_block(st);
488
0
    _PySymtable_Free(st);
489
0
    return NULL;
490
825
}
491
492
493
void
494
_PySymtable_Free(struct symtable *st)
495
825
{
496
825
    Py_XDECREF(st->st_filename);
497
825
    Py_XDECREF(st->st_blocks);
498
825
    Py_XDECREF(st->st_stack);
499
825
    PyMem_Free((void *)st);
500
825
}
501
502
PySTEntryObject *
503
_PySymtable_Lookup(struct symtable *st, void *key)
504
5.54k
{
505
5.54k
    PyObject *k, *v;
506
507
5.54k
    k = PyLong_FromVoidPtr(key);
508
5.54k
    if (k == NULL)
509
0
        return NULL;
510
5.54k
    if (PyDict_GetItemRef(st->st_blocks, k, &v) == 0) {
511
0
        PyErr_SetString(PyExc_KeyError,
512
0
                        "unknown symbol table entry");
513
0
    }
514
5.54k
    Py_DECREF(k);
515
516
5.54k
    assert(v == NULL || PySTEntry_Check(v));
517
5.54k
    return (PySTEntryObject *)v;
518
5.54k
}
519
520
int
521
_PySymtable_LookupOptional(struct symtable *st, void *key,
522
                           PySTEntryObject **out)
523
3.52k
{
524
3.52k
    PyObject *k = PyLong_FromVoidPtr(key);
525
3.52k
    if (k == NULL) {
526
0
        *out = NULL;
527
0
        return -1;
528
0
    }
529
3.52k
    int result = PyDict_GetItemRef(st->st_blocks, k, (PyObject **)out);
530
3.52k
    Py_DECREF(k);
531
3.52k
    assert(*out == NULL || PySTEntry_Check(*out));
532
3.52k
    return result;
533
3.52k
}
534
535
long
536
_PyST_GetSymbol(PySTEntryObject *ste, PyObject *name)
537
65.8k
{
538
65.8k
    PyObject *v;
539
65.8k
    if (PyDict_GetItemRef(ste->ste_symbols, name, &v) < 0) {
540
0
        return -1;
541
0
    }
542
65.8k
    if (!v) {
543
9.86k
        return 0;
544
9.86k
    }
545
55.9k
    long symbol = PyLong_AsLong(v);
546
55.9k
    Py_DECREF(v);
547
55.9k
    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
55.9k
    return symbol;
554
55.9k
}
555
556
int
557
_PyST_GetScope(PySTEntryObject *ste, PyObject *name)
558
58.8k
{
559
58.8k
    long symbol = _PyST_GetSymbol(ste, name);
560
58.8k
    if (symbol < 0) {
561
0
        return -1;
562
0
    }
563
58.8k
    return SYMBOL_TO_SCOPE(symbol);
564
58.8k
}
565
566
int
567
_PyST_IsFunctionLike(PySTEntryObject *ste)
568
121k
{
569
121k
    return ste->ste_type == FunctionBlock
570
26.4k
        || ste->ste_type == AnnotationBlock
571
19.0k
        || ste->ste_type == TypeVariableBlock
572
19.0k
        || ste->ste_type == TypeAliasBlock
573
19.0k
        || ste->ste_type == TypeParametersBlock;
574
121k
}
575
576
static int
577
error_at_directive(PySTEntryObject *ste, PyObject *name)
578
0
{
579
0
    Py_ssize_t i;
580
0
    PyObject *data;
581
0
    assert(ste->ste_directives);
582
0
    for (i = 0; i < PyList_GET_SIZE(ste->ste_directives); i++) {
583
0
        data = PyList_GET_ITEM(ste->ste_directives, i);
584
0
        assert(PyTuple_CheckExact(data));
585
0
        assert(PyUnicode_CheckExact(PyTuple_GET_ITEM(data, 0)));
586
0
        if (PyUnicode_Compare(PyTuple_GET_ITEM(data, 0), name) == 0) {
587
0
            PyErr_RangedSyntaxLocationObject(ste->ste_table->st_filename,
588
0
                                             PyLong_AsLong(PyTuple_GET_ITEM(data, 1)),
589
0
                                             PyLong_AsLong(PyTuple_GET_ITEM(data, 2)) + 1,
590
0
                                             PyLong_AsLong(PyTuple_GET_ITEM(data, 3)),
591
0
                                             PyLong_AsLong(PyTuple_GET_ITEM(data, 4)) + 1);
592
593
0
            return 0;
594
0
        }
595
0
    }
596
0
    PyErr_SetString(PyExc_RuntimeError,
597
0
                    "BUG: internal directive bookkeeping broken");
598
0
    return 0;
599
0
}
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
31.6k
    do { \
649
31.6k
        PyObject *o = PyLong_FromLong(I); \
650
31.6k
        if (!o) \
651
31.6k
            return 0; \
652
31.6k
        if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
653
0
            Py_DECREF(o); \
654
0
            return 0; \
655
0
        } \
656
31.6k
        Py_DECREF(o); \
657
31.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
31.5k
{
671
31.5k
    int contains;
672
31.5k
    if (flags & DEF_GLOBAL) {
673
20
        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
20
        SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
680
20
        if (PySet_Add(global, name) < 0)
681
0
            return 0;
682
20
        if (bound && (PySet_Discard(bound, name) < 0))
683
0
            return 0;
684
20
        return 1;
685
20
    }
686
31.5k
    if (flags & DEF_NONLOCAL) {
687
6
        if (!bound) {
688
0
            PyErr_Format(PyExc_SyntaxError,
689
0
                         "nonlocal declaration not allowed at module level");
690
0
            return error_at_directive(ste, name);
691
0
        }
692
6
        contains = PySet_Contains(bound, name);
693
6
        if (contains < 0) {
694
0
            return 0;
695
0
        }
696
6
        if (!contains) {
697
0
            PyErr_Format(PyExc_SyntaxError,
698
0
                         "no binding for nonlocal '%U' found",
699
0
                         name);
700
701
0
            return error_at_directive(ste, name);
702
0
        }
703
6
        contains = PySet_Contains(type_params, name);
704
6
        if (contains < 0) {
705
0
            return 0;
706
0
        }
707
6
        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
6
        SET_SCOPE(scopes, name, FREE);
714
6
        return PySet_Add(free, name) >= 0;
715
6
    }
716
31.5k
    if (flags & DEF_BOUND) {
717
22.3k
        SET_SCOPE(scopes, name, LOCAL);
718
22.3k
        if (PySet_Add(local, name) < 0)
719
0
            return 0;
720
22.3k
        if (PySet_Discard(global, name) < 0)
721
0
            return 0;
722
22.3k
        if (flags & DEF_TYPE_PARAM) {
723
0
            if (PySet_Add(type_params, name) < 0)
724
0
                return 0;
725
0
        }
726
22.3k
        else {
727
22.3k
            if (PySet_Discard(type_params, name) < 0)
728
0
                return 0;
729
22.3k
        }
730
22.3k
        return 1;
731
22.3k
    }
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
9.21k
    if (class_entry != NULL) {
740
1.83k
        long class_flags = _PyST_GetSymbol(class_entry, name);
741
1.83k
        if (class_flags < 0) {
742
0
            return 0;
743
0
        }
744
1.83k
        if (class_flags & DEF_GLOBAL) {
745
0
            SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
746
0
            return 1;
747
0
        }
748
1.83k
        else if ((class_flags & DEF_BOUND) && !(class_flags & DEF_NONLOCAL)) {
749
0
            SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
750
0
            return 1;
751
0
        }
752
1.83k
    }
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
9.21k
    if (bound) {
759
9.07k
        contains = PySet_Contains(bound, name);
760
9.07k
        if (contains < 0) {
761
0
            return 0;
762
0
        }
763
9.07k
        if (contains) {
764
2.82k
            SET_SCOPE(scopes, name, FREE);
765
2.82k
            return PySet_Add(free, name) >= 0;
766
2.82k
        }
767
9.07k
    }
768
    /* If a parent has a global statement, then call it global
769
       explicit?  It could also be global implicit.
770
     */
771
6.39k
    if (global) {
772
6.39k
        contains = PySet_Contains(global, name);
773
6.39k
        if (contains < 0) {
774
0
            return 0;
775
0
        }
776
6.39k
        if (contains) {
777
4
            SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
778
4
            return 1;
779
4
        }
780
6.39k
    }
781
6.38k
    SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
782
6.38k
    return 1;
783
6.38k
}
784
785
static int
786
is_free_in_any_child(PySTEntryObject *entry, PyObject *key)
787
44
{
788
44
    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
44
    return 0;
800
44
}
801
802
static int
803
inline_comprehension(PySTEntryObject *ste, PySTEntryObject *comp,
804
                     PyObject *scopes, PyObject *comp_free,
805
                     PyObject *inlined_cells)
806
56
{
807
56
    PyObject *k, *v;
808
56
    Py_ssize_t pos = 0;
809
56
    int remove_dunder_class = 0;
810
56
    int remove_dunder_classdict = 0;
811
56
    int remove_dunder_cond_annotations = 0;
812
813
230
    while (PyDict_Next(comp->ste_symbols, &pos, &k, &v)) {
814
        // skip comprehension parameter
815
174
        long comp_flags = PyLong_AsLong(v);
816
174
        if (comp_flags == -1 && PyErr_Occurred()) {
817
0
            return 0;
818
0
        }
819
174
        if (comp_flags & DEF_PARAM) {
820
56
            assert(_PyUnicode_EqualToASCIIString(k, ".0"));
821
56
            continue;
822
56
        }
823
118
        int scope = SYMBOL_TO_SCOPE(comp_flags);
824
118
        int only_flags = comp_flags & ((1 << SCOPE_OFFSET) - 1);
825
118
        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
118
        PyObject *existing = PyDict_GetItemWithError(ste->ste_symbols, k);
831
118
        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
118
        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
118
        if (!existing) {
857
            // name does not exist in scope, copy from comprehension
858
70
            assert(scope != FREE || PySet_Contains(comp_free, k) == 1);
859
70
            PyObject *v_flags = PyLong_FromLong(only_flags);
860
70
            if (v_flags == NULL) {
861
0
                return 0;
862
0
            }
863
70
            int ok = PyDict_SetItem(ste->ste_symbols, k, v_flags);
864
70
            Py_DECREF(v_flags);
865
70
            if (ok < 0) {
866
0
                return 0;
867
0
            }
868
70
            SET_SCOPE(scopes, k, scope);
869
70
        }
870
48
        else {
871
48
            long flags = PyLong_AsLong(existing);
872
48
            if (flags == -1 && PyErr_Occurred()) {
873
0
                return 0;
874
0
            }
875
48
            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
44
                int ok = is_free_in_any_child(comp, k);
880
44
                if (ok < 0) {
881
0
                    return 0;
882
0
                }
883
44
                if (!ok) {
884
44
                    if (PySet_Discard(comp_free, k) < 0) {
885
0
                        return 0;
886
0
                    }
887
44
                }
888
44
            }
889
48
        }
890
118
    }
891
56
    if (remove_dunder_class && PyDict_DelItemString(comp->ste_symbols, "__class__") < 0) {
892
0
        return 0;
893
0
    }
894
56
    if (remove_dunder_classdict && PyDict_DelItemString(comp->ste_symbols, "__classdict__") < 0) {
895
0
        return 0;
896
0
    }
897
56
    if (remove_dunder_cond_annotations && PyDict_DelItemString(comp->ste_symbols, "__conditional_annotations__") < 0) {
898
0
        return 0;
899
0
    }
900
56
    return 1;
901
56
}
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
7.41k
{
916
7.41k
    PyObject *name, *v, *v_cell;
917
7.41k
    int success = 0;
918
7.41k
    Py_ssize_t pos = 0;
919
920
7.41k
    v_cell = PyLong_FromLong(CELL);
921
7.41k
    if (!v_cell)
922
0
        return 0;
923
33.7k
    while (PyDict_Next(scopes, &pos, &name, &v)) {
924
26.3k
        long scope = PyLong_AsLong(v);
925
26.3k
        if (scope == -1 && PyErr_Occurred()) {
926
0
            goto error;
927
0
        }
928
26.3k
        if (scope != LOCAL)
929
8.94k
            continue;
930
17.4k
        int contains = PySet_Contains(free, name);
931
17.4k
        if (contains < 0) {
932
0
            goto error;
933
0
        }
934
17.4k
        if (!contains) {
935
16.7k
            contains = PySet_Contains(inlined_cells, name);
936
16.7k
            if (contains < 0) {
937
0
                goto error;
938
0
            }
939
16.7k
            if (!contains) {
940
16.7k
                continue;
941
16.7k
            }
942
16.7k
        }
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
711
        if (PyDict_SetItem(scopes, name, v_cell) < 0)
948
0
            goto error;
949
711
        if (PySet_Discard(free, name) < 0)
950
0
            goto error;
951
711
    }
952
7.41k
    success = 1;
953
7.41k
 error:
954
7.41k
    Py_DECREF(v_cell);
955
7.41k
    return success;
956
7.41k
}
957
958
static int
959
drop_class_free(PySTEntryObject *ste, PyObject *free)
960
720
{
961
720
    int res;
962
720
    res = PySet_Discard(free, &_Py_ID(__class__));
963
720
    if (res < 0)
964
0
        return 0;
965
720
    if (res)
966
36
        ste->ste_needs_class_closure = 1;
967
720
    res = PySet_Discard(free, &_Py_ID(__classdict__));
968
720
    if (res < 0)
969
0
        return 0;
970
720
    if (res)
971
392
        ste->ste_needs_classdict = 1;
972
720
    res = PySet_Discard(free, &_Py_ID(__conditional_annotations__));
973
720
    if (res < 0)
974
0
        return 0;
975
720
    if (res) {
976
0
        ste->ste_has_conditional_annotations = 1;
977
0
    }
978
720
    return 1;
979
720
}
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
8.95k
{
990
8.95k
    PyObject *name = NULL, *itr = NULL;
991
8.95k
    PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
992
8.95k
    Py_ssize_t pos = 0;
993
994
    /* Update scope information for all symbols in this scope */
995
40.5k
    while (PyDict_Next(symbols, &pos, &name, &v)) {
996
31.6k
        long flags = PyLong_AsLong(v);
997
31.6k
        if (flags == -1 && PyErr_Occurred()) {
998
0
            return 0;
999
0
        }
1000
31.6k
        int contains = PySet_Contains(inlined_cells, name);
1001
31.6k
        if (contains < 0) {
1002
0
            return 0;
1003
0
        }
1004
31.6k
        if (contains) {
1005
0
            flags |= DEF_COMP_CELL;
1006
0
        }
1007
31.6k
        if (PyDict_GetItemRef(scopes, name, &v_scope) < 0) {
1008
0
            return 0;
1009
0
        }
1010
31.6k
        if (!v_scope) {
1011
0
            PyErr_SetObject(PyExc_KeyError, name);
1012
0
            return 0;
1013
0
        }
1014
31.6k
        long scope = PyLong_AsLong(v_scope);
1015
31.6k
        Py_DECREF(v_scope);
1016
31.6k
        if (scope == -1 && PyErr_Occurred()) {
1017
0
            return 0;
1018
0
        }
1019
31.6k
        flags |= (scope << SCOPE_OFFSET);
1020
31.6k
        v_new = PyLong_FromLong(flags);
1021
31.6k
        if (!v_new)
1022
0
            return 0;
1023
31.6k
        if (PyDict_SetItem(symbols, name, v_new) < 0) {
1024
0
            Py_DECREF(v_new);
1025
0
            return 0;
1026
0
        }
1027
31.6k
        Py_DECREF(v_new);
1028
31.6k
    }
1029
1030
    /* Record not yet resolved free variables from children (if any) */
1031
8.95k
    v_free = PyLong_FromLong(FREE << SCOPE_OFFSET);
1032
8.95k
    if (!v_free)
1033
0
        return 0;
1034
1035
8.95k
    itr = PyObject_GetIter(free);
1036
8.95k
    if (itr == NULL) {
1037
0
        Py_DECREF(v_free);
1038
0
        return 0;
1039
0
    }
1040
1041
8.96k
    while ((name = PyIter_Next(itr))) {
1042
7
        v = PyDict_GetItemWithError(symbols, name);
1043
1044
        /* Handle symbol that already exists in this scope */
1045
7
        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
2
            if  (classflag) {
1051
1
                long flags = PyLong_AsLong(v);
1052
1
                if (flags == -1 && PyErr_Occurred()) {
1053
0
                    goto error;
1054
0
                }
1055
1
                flags |= DEF_FREE_CLASS;
1056
1
                v_new = PyLong_FromLong(flags);
1057
1
                if (!v_new) {
1058
0
                    goto error;
1059
0
                }
1060
1
                if (PyDict_SetItem(symbols, name, v_new) < 0) {
1061
0
                    Py_DECREF(v_new);
1062
0
                    goto error;
1063
0
                }
1064
1
                Py_DECREF(v_new);
1065
1
            }
1066
            /* It's a cell, or already free in this scope */
1067
2
            Py_DECREF(name);
1068
2
            continue;
1069
2
        }
1070
5
        else if (PyErr_Occurred()) {
1071
0
            goto error;
1072
0
        }
1073
        /* Handle global symbol */
1074
5
        if (bound) {
1075
5
            int contains = PySet_Contains(bound, name);
1076
5
            if (contains < 0) {
1077
0
                goto error;
1078
0
            }
1079
5
            if (!contains) {
1080
0
                Py_DECREF(name);
1081
0
                continue;       /* it's a global */
1082
0
            }
1083
5
        }
1084
        /* Propagate new free symbol up the lexical stack */
1085
5
        if (PyDict_SetItem(symbols, name, v_free) < 0) {
1086
0
            goto error;
1087
0
        }
1088
5
        Py_DECREF(name);
1089
5
    }
1090
1091
    /* Check if loop ended because of exception in PyIter_Next */
1092
8.95k
    if (PyErr_Occurred()) {
1093
0
        goto error;
1094
0
    }
1095
1096
8.95k
    Py_DECREF(itr);
1097
8.95k
    Py_DECREF(v_free);
1098
8.95k
    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
8.95k
}
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
8.95k
{
1136
8.95k
    PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
1137
8.95k
    PyObject *newglobal = NULL, *newfree = NULL, *inlined_cells = NULL;
1138
8.95k
    PyObject *temp;
1139
8.95k
    int success = 0;
1140
8.95k
    Py_ssize_t i, pos = 0;
1141
1142
8.95k
    local = PySet_New(NULL);  /* collect new names bound in block */
1143
8.95k
    if (!local)
1144
0
        goto error;
1145
8.95k
    scopes = PyDict_New();  /* collect scopes defined for each name */
1146
8.95k
    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
8.95k
    newglobal = PySet_New(NULL);
1161
8.95k
    if (!newglobal)
1162
0
        goto error;
1163
8.95k
    newfree = PySet_New(NULL);
1164
8.95k
    if (!newfree)
1165
0
        goto error;
1166
8.95k
    newbound = PySet_New(NULL);
1167
8.95k
    if (!newbound)
1168
0
        goto error;
1169
8.95k
    inlined_cells = PySet_New(NULL);
1170
8.95k
    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
8.95k
    if (ste->ste_type == ClassBlock) {
1179
        /* Pass down known globals */
1180
720
        temp = PyNumber_InPlaceOr(newglobal, global);
1181
720
        if (!temp)
1182
0
            goto error;
1183
720
        Py_DECREF(temp);
1184
        /* Pass down previously bound symbols */
1185
720
        if (bound) {
1186
720
            temp = PyNumber_InPlaceOr(newbound, bound);
1187
720
            if (!temp)
1188
0
                goto error;
1189
720
            Py_DECREF(temp);
1190
720
        }
1191
720
    }
1192
1193
40.5k
    while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
1194
31.5k
        long flags = PyLong_AsLong(v);
1195
31.5k
        if (flags == -1 && PyErr_Occurred()) {
1196
0
            goto error;
1197
0
        }
1198
31.5k
        if (!analyze_name(ste, scopes, name, flags,
1199
31.5k
                          bound, local, free, global, type_params, class_entry))
1200
0
            goto error;
1201
31.5k
    }
1202
1203
    /* Populate global and bound sets to be passed to children. */
1204
8.95k
    if (ste->ste_type != ClassBlock) {
1205
        /* Add function locals to bound set */
1206
8.23k
        if (_PyST_IsFunctionLike(ste)) {
1207
7.41k
            temp = PyNumber_InPlaceOr(newbound, local);
1208
7.41k
            if (!temp)
1209
0
                goto error;
1210
7.41k
            Py_DECREF(temp);
1211
7.41k
        }
1212
        /* Pass down previously bound symbols */
1213
8.23k
        if (bound) {
1214
7.41k
            temp = PyNumber_InPlaceOr(newbound, bound);
1215
7.41k
            if (!temp)
1216
0
                goto error;
1217
7.41k
            Py_DECREF(temp);
1218
7.41k
        }
1219
        /* Pass down known globals */
1220
8.23k
        temp = PyNumber_InPlaceOr(newglobal, global);
1221
8.23k
        if (!temp)
1222
0
            goto error;
1223
8.23k
        Py_DECREF(temp);
1224
8.23k
    }
1225
720
    else {
1226
        /* Special-case __class__ and __classdict__ */
1227
720
        if (PySet_Add(newbound, &_Py_ID(__class__)) < 0)
1228
0
            goto error;
1229
720
        if (PySet_Add(newbound, &_Py_ID(__classdict__)) < 0)
1230
0
            goto error;
1231
720
        if (PySet_Add(newbound, &_Py_ID(__conditional_annotations__)) < 0)
1232
0
            goto error;
1233
720
    }
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
17.0k
    for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
1242
8.13k
        PyObject *child_free = NULL;
1243
8.13k
        PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
1244
8.13k
        PySTEntryObject* entry;
1245
8.13k
        assert(c && PySTEntry_Check(c));
1246
8.13k
        entry = (PySTEntryObject*)c;
1247
1248
8.13k
        PySTEntryObject *new_class_entry = NULL;
1249
8.13k
        if (entry->ste_can_see_class_scope) {
1250
1.78k
            if (ste->ste_type == ClassBlock) {
1251
1.78k
                new_class_entry = ste;
1252
1.78k
            }
1253
0
            else if (class_entry) {
1254
0
                new_class_entry = class_entry;
1255
0
            }
1256
1.78k
        }
1257
1258
        // we inline all non-generator-expression comprehensions,
1259
        // except those in annotation scopes that are nested in classes
1260
8.13k
        int inline_comp =
1261
8.13k
            entry->ste_comprehension &&
1262
94
            !entry->ste_generator &&
1263
56
            !ste->ste_can_see_class_scope;
1264
1265
8.13k
        if (!analyze_child_block(entry, newbound, newfree, newglobal,
1266
8.13k
                                 type_params, new_class_entry, &child_free))
1267
0
        {
1268
0
            goto error;
1269
0
        }
1270
8.13k
        if (inline_comp) {
1271
56
            if (!inline_comprehension(ste, entry, scopes, child_free, inlined_cells)) {
1272
0
                Py_DECREF(child_free);
1273
0
                goto error;
1274
0
            }
1275
56
            entry->ste_comp_inlined = 1;
1276
56
        }
1277
8.13k
        temp = PyNumber_InPlaceOr(newfree, child_free);
1278
8.13k
        Py_DECREF(child_free);
1279
8.13k
        if (!temp)
1280
0
            goto error;
1281
8.13k
        Py_DECREF(temp);
1282
8.13k
    }
1283
1284
    /* Splice children of inlined comprehensions into our children list */
1285
17.0k
    for (i = PyList_GET_SIZE(ste->ste_children) - 1; i >= 0; --i) {
1286
8.13k
        PyObject* c = PyList_GET_ITEM(ste->ste_children, i);
1287
8.13k
        PySTEntryObject* entry;
1288
8.13k
        assert(c && PySTEntry_Check(c));
1289
8.13k
        entry = (PySTEntryObject*)c;
1290
8.13k
        if (entry->ste_comp_inlined &&
1291
56
            PyList_SetSlice(ste->ste_children, i, i + 1,
1292
56
                            entry->ste_children) < 0)
1293
0
        {
1294
0
            goto error;
1295
0
        }
1296
8.13k
    }
1297
1298
    /* Check if any local variables must be converted to cell variables */
1299
8.95k
    if (_PyST_IsFunctionLike(ste) && !analyze_cells(scopes, newfree, inlined_cells))
1300
0
        goto error;
1301
8.95k
    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
8.95k
    if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, inlined_cells,
1305
8.95k
                        (ste->ste_type == ClassBlock) || ste->ste_can_see_class_scope))
1306
0
        goto error;
1307
1308
8.95k
    temp = PyNumber_InPlaceOr(free, newfree);
1309
8.95k
    if (!temp)
1310
0
        goto error;
1311
8.95k
    Py_DECREF(temp);
1312
8.95k
    success = 1;
1313
8.95k
 error:
1314
8.95k
    Py_XDECREF(scopes);
1315
8.95k
    Py_XDECREF(local);
1316
8.95k
    Py_XDECREF(newbound);
1317
8.95k
    Py_XDECREF(newglobal);
1318
8.95k
    Py_XDECREF(newfree);
1319
8.95k
    Py_XDECREF(inlined_cells);
1320
8.95k
    if (!success)
1321
8.95k
        assert(PyErr_Occurred());
1322
8.95k
    return success;
1323
8.95k
}
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
8.13k
{
1330
8.13k
    PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
1331
8.13k
    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
8.13k
    temp_bound = PySet_New(bound);
1341
8.13k
    if (!temp_bound)
1342
0
        goto error;
1343
8.13k
    temp_free = PySet_New(free);
1344
8.13k
    if (!temp_free)
1345
0
        goto error;
1346
8.13k
    temp_global = PySet_New(global);
1347
8.13k
    if (!temp_global)
1348
0
        goto error;
1349
8.13k
    temp_type_params = PySet_New(type_params);
1350
8.13k
    if (!temp_type_params)
1351
0
        goto error;
1352
1353
8.13k
    if (!analyze_block(entry, temp_bound, temp_free, temp_global,
1354
8.13k
                       temp_type_params, class_entry))
1355
0
        goto error;
1356
8.13k
    *child_free = temp_free;
1357
8.13k
    Py_DECREF(temp_bound);
1358
8.13k
    Py_DECREF(temp_global);
1359
8.13k
    Py_DECREF(temp_type_params);
1360
8.13k
    return 1;
1361
0
 error:
1362
0
    Py_XDECREF(temp_bound);
1363
0
    Py_XDECREF(temp_free);
1364
0
    Py_XDECREF(temp_global);
1365
0
    Py_XDECREF(temp_type_params);
1366
0
    return 0;
1367
8.13k
}
1368
1369
static int
1370
symtable_analyze(struct symtable *st)
1371
825
{
1372
825
    PyObject *free, *global, *type_params;
1373
825
    int r;
1374
1375
825
    free = PySet_New(NULL);
1376
825
    if (!free)
1377
0
        return 0;
1378
825
    global = PySet_New(NULL);
1379
825
    if (!global) {
1380
0
        Py_DECREF(free);
1381
0
        return 0;
1382
0
    }
1383
825
    type_params = PySet_New(NULL);
1384
825
    if (!type_params) {
1385
0
        Py_DECREF(free);
1386
0
        Py_DECREF(global);
1387
0
        return 0;
1388
0
    }
1389
825
    r = analyze_block(st->st_top, NULL, free, global, type_params, NULL);
1390
825
    Py_DECREF(free);
1391
825
    Py_DECREF(global);
1392
825
    Py_DECREF(type_params);
1393
825
    return r;
1394
825
}
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
8.96k
{
1404
8.96k
    Py_ssize_t size;
1405
1406
8.96k
    st->st_cur = NULL;
1407
8.96k
    size = PyList_GET_SIZE(st->st_stack);
1408
8.96k
    if (size) {
1409
8.96k
        if (PyList_SetSlice(st->st_stack, size - 1, size, NULL) < 0)
1410
0
            return 0;
1411
8.96k
        if (--size)
1412
8.14k
            st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, size - 1);
1413
8.96k
    }
1414
8.96k
    return 1;
1415
8.96k
}
1416
1417
static int
1418
symtable_enter_existing_block(struct symtable *st, PySTEntryObject* ste, bool add_to_children)
1419
8.96k
{
1420
8.96k
    if (PyList_Append(st->st_stack, (PyObject *)ste) < 0) {
1421
0
        return 0;
1422
0
    }
1423
8.96k
    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
8.96k
    if (prev) {
1429
8.14k
        ste->ste_comp_iter_expr = prev->ste_comp_iter_expr;
1430
8.14k
    }
1431
    /* No need to inherit ste_mangled_names in classes, where all names
1432
     * are mangled. */
1433
8.96k
    if (prev && prev->ste_mangled_names != NULL && ste->ste_type != ClassBlock) {
1434
0
        ste->ste_mangled_names = Py_NewRef(prev->ste_mangled_names);
1435
0
    }
1436
    /* The entry is owned by the stack. Borrow it for st_cur. */
1437
8.96k
    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
8.96k
    if (st->st_future->ff_features & CO_FUTURE_ANNOTATIONS && ste->ste_type == AnnotationBlock) {
1443
0
        return 1;
1444
0
    }
1445
1446
8.96k
    if (ste->ste_type == ModuleBlock)
1447
825
        st->st_global = st->st_cur->ste_symbols;
1448
1449
8.96k
    if (add_to_children && prev) {
1450
8.13k
        if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) {
1451
0
            return 0;
1452
0
        }
1453
8.13k
    }
1454
8.96k
    return 1;
1455
8.96k
}
1456
1457
static int
1458
symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
1459
                     void *ast, _Py_SourceLocation loc)
1460
5.43k
{
1461
5.43k
    PySTEntryObject *ste = ste_new(st, name, block, ast, loc);
1462
5.43k
    if (ste == NULL)
1463
0
        return 0;
1464
5.43k
    int result = symtable_enter_existing_block(st, ste, /* add_to_children */true);
1465
5.43k
    Py_DECREF(ste);
1466
5.43k
    if (block == AnnotationBlock || block == TypeVariableBlock || block == TypeAliasBlock) {
1467
3.53k
        _Py_DECLARE_STR(format, ".format");
1468
        // We need to insert code that reads this "parameter" to the function.
1469
3.53k
        if (!symtable_add_def(st, &_Py_STR(format), DEF_PARAM, loc)) {
1470
0
            return 0;
1471
0
        }
1472
3.53k
        if (!symtable_add_def(st, &_Py_STR(format), USE, loc)) {
1473
0
            return 0;
1474
0
        }
1475
3.53k
    }
1476
5.43k
    return result;
1477
5.43k
}
1478
1479
static long
1480
symtable_lookup_entry(struct symtable *st, PySTEntryObject *ste, PyObject *name)
1481
33
{
1482
33
    PyObject *mangled = _Py_MaybeMangle(st->st_private, ste, name);
1483
33
    if (!mangled)
1484
0
        return -1;
1485
33
    long ret = _PyST_GetSymbol(ste, mangled);
1486
33
    Py_DECREF(mangled);
1487
33
    if (ret < 0) {
1488
0
        return -1;
1489
0
    }
1490
33
    return ret;
1491
33
}
1492
1493
static long
1494
symtable_lookup(struct symtable *st, PyObject *name)
1495
33
{
1496
33
    return symtable_lookup_entry(st, st->st_cur, name);
1497
33
}
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
68.7k
{
1503
68.7k
    PyObject *o;
1504
68.7k
    PyObject *dict;
1505
68.7k
    long val;
1506
68.7k
    PyObject *mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1507
1508
68.7k
    if (!mangled)
1509
0
        return 0;
1510
68.7k
    dict = ste->ste_symbols;
1511
68.7k
    if ((o = PyDict_GetItemWithError(dict, mangled))) {
1512
37.1k
        val = PyLong_AsLong(o);
1513
37.1k
        if (val == -1 && PyErr_Occurred()) {
1514
0
            goto error;
1515
0
        }
1516
37.1k
        if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
1517
            /* Is it better to use 'mangled' or 'name' here? */
1518
0
            PyErr_Format(PyExc_SyntaxError, DUPLICATE_PARAMETER, name);
1519
0
            SET_ERROR_LOCATION(st->st_filename, loc);
1520
0
            goto error;
1521
0
        }
1522
37.1k
        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
37.1k
        val |= flag;
1528
37.1k
    }
1529
31.5k
    else if (PyErr_Occurred()) {
1530
0
        goto error;
1531
0
    }
1532
31.5k
    else {
1533
31.5k
        val = flag;
1534
31.5k
    }
1535
68.7k
    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
116
        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
116
        val |= DEF_COMP_ITER;
1548
116
    }
1549
68.7k
    o = PyLong_FromLong(val);
1550
68.7k
    if (o == NULL)
1551
0
        goto error;
1552
68.7k
    if (PyDict_SetItem(dict, mangled, o) < 0) {
1553
0
        Py_DECREF(o);
1554
0
        goto error;
1555
0
    }
1556
68.7k
    Py_DECREF(o);
1557
1558
68.7k
    if (flag & DEF_PARAM) {
1559
13.9k
        if (PyList_Append(ste->ste_varnames, mangled) < 0)
1560
0
            goto error;
1561
54.7k
    } else if (flag & DEF_GLOBAL) {
1562
        /* XXX need to update DEF_GLOBAL for other flags too;
1563
           perhaps only DEF_FREE_GLOBAL */
1564
11
        val = 0;
1565
11
        if ((o = PyDict_GetItemWithError(st->st_global, mangled))) {
1566
6
            val = PyLong_AsLong(o);
1567
6
            if (val == -1 && PyErr_Occurred()) {
1568
0
                goto error;
1569
0
            }
1570
6
        }
1571
5
        else if (PyErr_Occurred()) {
1572
0
            goto error;
1573
0
        }
1574
11
        val |= flag;
1575
11
        o = PyLong_FromLong(val);
1576
11
        if (o == NULL)
1577
0
            goto error;
1578
11
        if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
1579
0
            Py_DECREF(o);
1580
0
            goto error;
1581
0
        }
1582
11
        Py_DECREF(o);
1583
11
    }
1584
68.7k
    Py_DECREF(mangled);
1585
68.7k
    return 1;
1586
1587
0
error:
1588
0
    Py_DECREF(mangled);
1589
0
    return 0;
1590
68.7k
}
1591
1592
static int
1593
check_name(struct symtable *st, PyObject *name, _Py_SourceLocation loc,
1594
           expr_context_ty ctx)
1595
42.7k
{
1596
42.7k
    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
42.7k
    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
42.7k
    return 1;
1607
42.7k
}
1608
1609
static int
1610
check_keywords(struct symtable *st, asdl_keyword_seq *keywords)
1611
11.0k
{
1612
12.8k
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(keywords); i++) {
1613
1.81k
        keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
1614
1.81k
        if (key->arg  && !check_name(st, key->arg, LOCATION(key), Store)) {
1615
0
            return 0;
1616
0
        }
1617
1.81k
    }
1618
11.0k
    return 1;
1619
11.0k
}
1620
1621
static int
1622
check_kwd_patterns(struct symtable *st, pattern_ty p)
1623
0
{
1624
0
    assert(p->kind == MatchClass_kind);
1625
0
    asdl_identifier_seq *kwd_attrs = p->v.MatchClass.kwd_attrs;
1626
0
    asdl_pattern_seq *kwd_patterns = p->v.MatchClass.kwd_patterns;
1627
0
    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
0
    return 1;
1634
0
}
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
68.7k
{
1640
68.7k
    int write_mask = DEF_PARAM | DEF_LOCAL | DEF_IMPORT;
1641
68.7k
    if ((flag & write_mask) && !check_name(st, name, loc, ctx)) {
1642
0
        return 0;
1643
0
    }
1644
68.7k
    if ((flag & DEF_TYPE_PARAM) && st->st_cur->ste_mangled_names != NULL) {
1645
0
        if(PySet_Add(st->st_cur->ste_mangled_names, name) < 0) {
1646
0
            return 0;
1647
0
        }
1648
0
    }
1649
68.7k
    return symtable_add_def_helper(st, name, flag, st->st_cur, loc);
1650
68.7k
}
1651
1652
static int
1653
symtable_add_def(struct symtable *st, PyObject *name, int flag,
1654
                 _Py_SourceLocation loc)
1655
24.8k
{
1656
24.8k
    return symtable_add_def_ctx(st, name, flag, loc,
1657
24.8k
                                flag == USE ? Load : Store);
1658
24.8k
}
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
0
{
1665
0
    _Py_block_ty current_type = st->st_cur->ste_type;
1666
0
    if(!symtable_enter_block(st, name, TypeParametersBlock, ast, loc)) {
1667
0
        return 0;
1668
0
    }
1669
0
    if (current_type == ClassBlock) {
1670
0
        st->st_cur->ste_can_see_class_scope = 1;
1671
0
        if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, loc)) {
1672
0
            return 0;
1673
0
        }
1674
0
    }
1675
0
    if (kind == ClassDef_kind) {
1676
0
        _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
0
        if (!symtable_add_def(st, &_Py_STR(type_params), DEF_LOCAL, loc)) {
1680
0
            return 0;
1681
0
        }
1682
0
        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
0
        _Py_DECLARE_STR(generic_base, ".generic_base");
1687
0
        if (!symtable_add_def(st, &_Py_STR(generic_base), DEF_LOCAL, loc)) {
1688
0
            return 0;
1689
0
        }
1690
0
        if (!symtable_add_def(st, &_Py_STR(generic_base), USE, loc)) {
1691
0
            return 0;
1692
0
        }
1693
0
    }
1694
0
    if (has_defaults) {
1695
0
        _Py_DECLARE_STR(defaults, ".defaults");
1696
0
        if (!symtable_add_def(st, &_Py_STR(defaults), DEF_PARAM, loc)) {
1697
0
            return 0;
1698
0
        }
1699
0
    }
1700
0
    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
0
    return 1;
1707
0
}
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
61.8k
    do { \
1725
61.8k
        if (!symtable_visit_ ## TYPE((ST), (V))) { \
1726
0
            return 0; \
1727
0
        } \
1728
61.8k
    } while(0)
1729
1730
#define VISIT_SEQ(ST, TYPE, SEQ) \
1731
39.2k
    do { \
1732
39.2k
        Py_ssize_t i; \
1733
39.2k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1734
104k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1735
64.8k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1736
64.8k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1737
64.8k
                return 0;                 \
1738
64.8k
        } \
1739
39.2k
    } while(0)
1740
1741
#define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) \
1742
94
    do { \
1743
94
        Py_ssize_t i; \
1744
94
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1745
95
        for (i = (START); i < asdl_seq_LEN(seq); i++) { \
1746
1
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1747
1
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1748
1
                return 0;                 \
1749
1
        } \
1750
94
    } while(0)
1751
1752
#define VISIT_SEQ_WITH_NULL(ST, TYPE, SEQ) \
1753
14.2k
    do { \
1754
14.2k
        int i = 0; \
1755
14.2k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1756
23.8k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1757
9.62k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1758
9.62k
            if (!elt) continue; /* can be NULL */ \
1759
9.62k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1760
9.61k
                return 0;             \
1761
9.61k
        } \
1762
14.2k
    } while(0)
1763
1764
#define ENTER_CONDITIONAL_BLOCK(ST) \
1765
4.07k
    int in_conditional_block = (ST)->st_cur->ste_in_conditional_block; \
1766
4.07k
    (ST)->st_cur->ste_in_conditional_block = 1;
1767
1768
#define LEAVE_CONDITIONAL_BLOCK(ST) \
1769
4.07k
    (ST)->st_cur->ste_in_conditional_block = in_conditional_block;
1770
1771
#define ENTER_TRY_BLOCK(ST) \
1772
395
    int in_try_block = (ST)->st_cur->ste_in_try_block; \
1773
395
    (ST)->st_cur->ste_in_try_block = 1;
1774
1775
#define LEAVE_TRY_BLOCK(ST) \
1776
395
    (ST)->st_cur->ste_in_try_block = in_try_block;
1777
1778
132k
#define ENTER_RECURSIVE() \
1779
132k
if (Py_EnterRecursiveCall(" during compilation")) { \
1780
0
    return 0; \
1781
0
}
1782
1783
132k
#define LEAVE_RECURSIVE() Py_LeaveRecursiveCall();
1784
1785
1786
static int
1787
symtable_record_directive(struct symtable *st, identifier name, _Py_SourceLocation loc)
1788
17
{
1789
17
    PyObject *data, *mangled;
1790
17
    int res;
1791
17
    if (!st->st_cur->ste_directives) {
1792
13
        st->st_cur->ste_directives = PyList_New(0);
1793
13
        if (!st->st_cur->ste_directives)
1794
0
            return 0;
1795
13
    }
1796
17
    mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1797
17
    if (!mangled)
1798
0
        return 0;
1799
17
    data = Py_BuildValue("(Niiii)", mangled, loc.lineno, loc.col_offset,
1800
17
                                    loc.end_lineno, loc.end_col_offset);
1801
17
    if (!data)
1802
0
        return 0;
1803
17
    res = PyList_Append(st->st_cur->ste_directives, data);
1804
17
    Py_DECREF(data);
1805
17
    return res == 0;
1806
17
}
1807
1808
static int
1809
has_kwonlydefaults(asdl_arg_seq *kwonlyargs, asdl_expr_seq *kw_defaults)
1810
0
{
1811
0
    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
0
    return 0;
1818
0
}
1819
1820
static int
1821
check_import_from(struct symtable *st, stmt_ty s)
1822
387
{
1823
387
    assert(s->kind == ImportFrom_kind);
1824
387
    _Py_SourceLocation fut = st->st_future->ff_location;
1825
387
    if (s->v.ImportFrom.module && s->v.ImportFrom.level == 0 &&
1826
242
        _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__") &&
1827
0
        ((s->lineno > fut.lineno) ||
1828
0
         ((s->lineno == fut.end_lineno) && (s->col_offset > fut.end_col_offset))))
1829
0
    {
1830
0
        PyErr_SetString(PyExc_SyntaxError,
1831
0
                        "from __future__ imports must occur "
1832
0
                        "at the beginning of the file");
1833
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
1834
0
        return 0;
1835
0
    }
1836
387
    return 1;
1837
387
}
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
128
{
1874
128
    return (st->st_future->ff_features & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
1875
0
            st->st_cur->ste_type == ModuleBlock;
1876
128
}
1877
1878
1879
static void
1880
maybe_set_ste_coroutine_for_module(struct symtable *st, stmt_ty s)
1881
5
{
1882
5
    if (allows_top_level_await(st)) {
1883
0
        st->st_cur->ste_coroutine = 1;
1884
0
    }
1885
5
}
1886
1887
static int
1888
symtable_visit_stmt(struct symtable *st, stmt_ty s)
1889
23.1k
{
1890
23.1k
    ENTER_RECURSIVE();
1891
23.1k
    switch (s->kind) {
1892
3.38k
    case FunctionDef_kind: {
1893
3.38k
        if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL, LOCATION(s)))
1894
0
            return 0;
1895
3.38k
        if (s->v.FunctionDef.args->defaults)
1896
3.38k
            VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
1897
3.38k
        if (s->v.FunctionDef.args->kw_defaults)
1898
3.38k
            VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults);
1899
3.38k
        if (s->v.FunctionDef.decorator_list)
1900
194
            VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
1901
3.38k
        if (asdl_seq_LEN(s->v.FunctionDef.type_params) > 0) {
1902
0
            if (!symtable_enter_type_param_block(
1903
0
                    st, s->v.FunctionDef.name,
1904
0
                    (void *)s->v.FunctionDef.type_params,
1905
0
                    s->v.FunctionDef.args->defaults != NULL,
1906
0
                    has_kwonlydefaults(s->v.FunctionDef.args->kwonlyargs,
1907
0
                                       s->v.FunctionDef.args->kw_defaults),
1908
0
                    s->kind,
1909
0
                    LOCATION(s))) {
1910
0
                return 0;
1911
0
            }
1912
0
            VISIT_SEQ(st, type_param, s->v.FunctionDef.type_params);
1913
0
        }
1914
3.38k
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
1915
3.38k
                                           LOCATION(s));
1916
3.38k
        if (!new_ste) {
1917
0
            return 0;
1918
0
        }
1919
1920
3.38k
        if (_PyAST_GetDocString(s->v.FunctionDef.body)) {
1921
525
            new_ste->ste_has_docstring = 1;
1922
525
        }
1923
1924
3.38k
        if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args,
1925
3.38k
                                        s->v.FunctionDef.returns, new_ste)) {
1926
0
            Py_DECREF(new_ste);
1927
0
            return 0;
1928
0
        }
1929
3.38k
        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.38k
        Py_DECREF(new_ste);
1934
3.38k
        VISIT(st, arguments, s->v.FunctionDef.args);
1935
3.38k
        VISIT_SEQ(st, stmt, s->v.FunctionDef.body);
1936
3.38k
        if (!symtable_exit_block(st))
1937
0
            return 0;
1938
3.38k
        if (asdl_seq_LEN(s->v.FunctionDef.type_params) > 0) {
1939
0
            if (!symtable_exit_block(st))
1940
0
                return 0;
1941
0
        }
1942
3.38k
        break;
1943
3.38k
    }
1944
3.38k
    case ClassDef_kind: {
1945
720
        PyObject *tmp;
1946
720
        if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL, LOCATION(s)))
1947
0
            return 0;
1948
720
        if (s->v.ClassDef.decorator_list)
1949
3
            VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
1950
720
        tmp = st->st_private;
1951
720
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
1952
0
            if (!symtable_enter_type_param_block(st, s->v.ClassDef.name,
1953
0
                                                (void *)s->v.ClassDef.type_params,
1954
0
                                                false, false, s->kind,
1955
0
                                                LOCATION(s))) {
1956
0
                return 0;
1957
0
            }
1958
0
            st->st_private = s->v.ClassDef.name;
1959
0
            st->st_cur->ste_mangled_names = PySet_New(NULL);
1960
0
            if (!st->st_cur->ste_mangled_names) {
1961
0
                return 0;
1962
0
            }
1963
0
            VISIT_SEQ(st, type_param, s->v.ClassDef.type_params);
1964
0
        }
1965
720
        VISIT_SEQ(st, expr, s->v.ClassDef.bases);
1966
720
        if (!check_keywords(st, s->v.ClassDef.keywords)) {
1967
0
            return 0;
1968
0
        }
1969
720
        VISIT_SEQ(st, keyword, s->v.ClassDef.keywords);
1970
720
        if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
1971
720
                                  (void *)s, LOCATION(s))) {
1972
0
            return 0;
1973
0
        }
1974
720
        st->st_private = s->v.ClassDef.name;
1975
720
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
1976
0
            if (!symtable_add_def(st, &_Py_ID(__type_params__),
1977
0
                                  DEF_LOCAL, LOCATION(s))) {
1978
0
                return 0;
1979
0
            }
1980
0
            _Py_DECLARE_STR(type_params, ".type_params");
1981
0
            if (!symtable_add_def(st, &_Py_STR(type_params),
1982
0
                                  USE, LOCATION(s))) {
1983
0
                return 0;
1984
0
            }
1985
0
        }
1986
1987
720
        if (_PyAST_GetDocString(s->v.ClassDef.body)) {
1988
119
            st->st_cur->ste_has_docstring = 1;
1989
119
        }
1990
1991
720
        VISIT_SEQ(st, stmt, s->v.ClassDef.body);
1992
720
        if (!symtable_exit_block(st))
1993
0
            return 0;
1994
720
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
1995
0
            if (!symtable_exit_block(st))
1996
0
                return 0;
1997
0
        }
1998
720
        st->st_private = tmp;
1999
720
        break;
2000
720
    }
2001
0
    case TypeAlias_kind: {
2002
0
        VISIT(st, expr, s->v.TypeAlias.name);
2003
0
        assert(s->v.TypeAlias.name->kind == Name_kind);
2004
0
        PyObject *name = s->v.TypeAlias.name->v.Name.id;
2005
0
        int is_in_class = st->st_cur->ste_type == ClassBlock;
2006
0
        int is_generic = asdl_seq_LEN(s->v.TypeAlias.type_params) > 0;
2007
0
        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
0
        if (!symtable_enter_block(st, name, TypeAliasBlock,
2018
0
                                  (void *)s, LOCATION(s))) {
2019
0
            return 0;
2020
0
        }
2021
0
        st->st_cur->ste_can_see_class_scope = is_in_class;
2022
0
        if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(s->v.TypeAlias.value))) {
2023
0
            return 0;
2024
0
        }
2025
0
        VISIT(st, expr, s->v.TypeAlias.value);
2026
0
        if (!symtable_exit_block(st))
2027
0
            return 0;
2028
0
        if (is_generic) {
2029
0
            if (!symtable_exit_block(st))
2030
0
                return 0;
2031
0
        }
2032
0
        break;
2033
0
    }
2034
2.91k
    case Return_kind:
2035
2.91k
        if (s->v.Return.value) {
2036
2.66k
            VISIT(st, expr, s->v.Return.value);
2037
2.66k
            st->st_cur->ste_returns_value = 1;
2038
2.66k
        }
2039
2.91k
        break;
2040
2.91k
    case Delete_kind:
2041
47
        VISIT_SEQ(st, expr, s->v.Delete.targets);
2042
47
        break;
2043
4.93k
    case Assign_kind:
2044
4.93k
        VISIT_SEQ(st, expr, s->v.Assign.targets);
2045
4.93k
        VISIT(st, expr, s->v.Assign.value);
2046
4.93k
        break;
2047
4.93k
    case AnnAssign_kind:
2048
18
        st->st_cur->ste_annotations_used = 1;
2049
18
        if (s->v.AnnAssign.target->kind == Name_kind) {
2050
16
            expr_ty e_name = s->v.AnnAssign.target;
2051
16
            long cur = symtable_lookup(st, e_name->v.Name.id);
2052
16
            if (cur < 0) {
2053
0
                return 0;
2054
0
            }
2055
16
            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
16
            if (s->v.AnnAssign.simple &&
2065
16
                !symtable_add_def(st, e_name->v.Name.id,
2066
16
                                  DEF_ANNOT | DEF_LOCAL, LOCATION(e_name))) {
2067
0
                return 0;
2068
0
            }
2069
16
            else {
2070
16
                if (s->v.AnnAssign.value
2071
12
                    && !symtable_add_def(st, e_name->v.Name.id, DEF_LOCAL, LOCATION(e_name))) {
2072
0
                    return 0;
2073
0
                }
2074
16
            }
2075
16
        }
2076
2
        else {
2077
2
            VISIT(st, expr, s->v.AnnAssign.target);
2078
2
        }
2079
18
        if (!symtable_visit_annotation(st, s->v.AnnAssign.annotation,
2080
18
                                       (void *)((uintptr_t)st->st_cur->ste_id + 1))) {
2081
0
            return 0;
2082
0
        }
2083
2084
18
        if (s->v.AnnAssign.value) {
2085
14
            VISIT(st, expr, s->v.AnnAssign.value);
2086
14
        }
2087
18
        break;
2088
185
    case AugAssign_kind: {
2089
185
        VISIT(st, expr, s->v.AugAssign.target);
2090
185
        VISIT(st, expr, s->v.AugAssign.value);
2091
185
        break;
2092
185
    }
2093
317
    case For_kind: {
2094
317
        VISIT(st, expr, s->v.For.target);
2095
317
        VISIT(st, expr, s->v.For.iter);
2096
317
        ENTER_CONDITIONAL_BLOCK(st);
2097
317
        VISIT_SEQ(st, stmt, s->v.For.body);
2098
317
        if (s->v.For.orelse)
2099
4
            VISIT_SEQ(st, stmt, s->v.For.orelse);
2100
317
        LEAVE_CONDITIONAL_BLOCK(st);
2101
317
        break;
2102
317
    }
2103
88
    case While_kind: {
2104
88
        VISIT(st, expr, s->v.While.test);
2105
88
        ENTER_CONDITIONAL_BLOCK(st);
2106
88
        VISIT_SEQ(st, stmt, s->v.While.body);
2107
88
        if (s->v.While.orelse)
2108
1
            VISIT_SEQ(st, stmt, s->v.While.orelse);
2109
88
        LEAVE_CONDITIONAL_BLOCK(st);
2110
88
        break;
2111
88
    }
2112
3.15k
    case If_kind: {
2113
        /* XXX if 0: and lookup_yield() hacks */
2114
3.15k
        VISIT(st, expr, s->v.If.test);
2115
3.15k
        ENTER_CONDITIONAL_BLOCK(st);
2116
3.15k
        VISIT_SEQ(st, stmt, s->v.If.body);
2117
3.15k
        if (s->v.If.orelse)
2118
695
            VISIT_SEQ(st, stmt, s->v.If.orelse);
2119
3.15k
        LEAVE_CONDITIONAL_BLOCK(st);
2120
3.15k
        break;
2121
3.15k
    }
2122
1
    case Match_kind: {
2123
1
        VISIT(st, expr, s->v.Match.subject);
2124
1
        ENTER_CONDITIONAL_BLOCK(st);
2125
1
        VISIT_SEQ(st, match_case, s->v.Match.cases);
2126
1
        LEAVE_CONDITIONAL_BLOCK(st);
2127
1
        break;
2128
1
    }
2129
853
    case Raise_kind:
2130
853
        if (s->v.Raise.exc) {
2131
754
            VISIT(st, expr, s->v.Raise.exc);
2132
754
            if (s->v.Raise.cause) {
2133
27
                VISIT(st, expr, s->v.Raise.cause);
2134
27
            }
2135
754
        }
2136
853
        break;
2137
853
    case Try_kind: {
2138
395
        ENTER_CONDITIONAL_BLOCK(st);
2139
395
        ENTER_TRY_BLOCK(st);
2140
395
        VISIT_SEQ(st, stmt, s->v.Try.body);
2141
395
        VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
2142
395
        VISIT_SEQ(st, stmt, s->v.Try.orelse);
2143
395
        VISIT_SEQ(st, stmt, s->v.Try.finalbody);
2144
395
        LEAVE_TRY_BLOCK(st);
2145
395
        LEAVE_CONDITIONAL_BLOCK(st);
2146
395
        break;
2147
395
    }
2148
0
    case TryStar_kind: {
2149
0
        ENTER_CONDITIONAL_BLOCK(st);
2150
0
        ENTER_TRY_BLOCK(st);
2151
0
        VISIT_SEQ(st, stmt, s->v.TryStar.body);
2152
0
        VISIT_SEQ(st, excepthandler, s->v.TryStar.handlers);
2153
0
        VISIT_SEQ(st, stmt, s->v.TryStar.orelse);
2154
0
        VISIT_SEQ(st, stmt, s->v.TryStar.finalbody);
2155
0
        LEAVE_TRY_BLOCK(st);
2156
0
        LEAVE_CONDITIONAL_BLOCK(st);
2157
0
        break;
2158
0
    }
2159
88
    case Assert_kind:
2160
88
        VISIT(st, expr, s->v.Assert.test);
2161
88
        if (s->v.Assert.msg)
2162
31
            VISIT(st, expr, s->v.Assert.msg);
2163
88
        break;
2164
486
    case Import_kind:
2165
486
        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
486
        VISIT_SEQ(st, alias, s->v.Import.names);
2171
486
        break;
2172
486
    case ImportFrom_kind:
2173
387
        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
387
        VISIT_SEQ(st, alias, s->v.ImportFrom.names);
2193
387
        if (!check_import_from(st, s)) {
2194
0
            return 0;
2195
0
        }
2196
387
        break;
2197
387
    case Global_kind: {
2198
9
        Py_ssize_t i;
2199
9
        asdl_identifier_seq *seq = s->v.Global.names;
2200
20
        for (i = 0; i < asdl_seq_LEN(seq); i++) {
2201
11
            identifier name = (identifier)asdl_seq_GET(seq, i);
2202
11
            long cur = symtable_lookup(st, name);
2203
11
            if (cur < 0)
2204
0
                return 0;
2205
11
            if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) {
2206
0
                const char* msg;
2207
0
                if (cur & DEF_PARAM) {
2208
0
                    msg = GLOBAL_PARAM;
2209
0
                } else if (cur & USE) {
2210
0
                    msg = GLOBAL_AFTER_USE;
2211
0
                } else if (cur & DEF_ANNOT) {
2212
0
                    msg = GLOBAL_ANNOT;
2213
0
                } else {  /* DEF_LOCAL */
2214
0
                    msg = GLOBAL_AFTER_ASSIGN;
2215
0
                }
2216
0
                PyErr_Format(PyExc_SyntaxError,
2217
0
                             msg, name);
2218
0
                SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
2219
0
                return 0;
2220
0
            }
2221
11
            if (!symtable_add_def(st, name, DEF_GLOBAL, LOCATION(s))) {
2222
0
                return 0;
2223
0
            }
2224
11
            if (!symtable_record_directive(st, name, LOCATION(s))) {
2225
0
                return 0;
2226
0
            }
2227
11
        }
2228
9
        break;
2229
9
    }
2230
9
    case Nonlocal_kind: {
2231
5
        Py_ssize_t i;
2232
5
        asdl_identifier_seq *seq = s->v.Nonlocal.names;
2233
11
        for (i = 0; i < asdl_seq_LEN(seq); i++) {
2234
6
            identifier name = (identifier)asdl_seq_GET(seq, i);
2235
6
            long cur = symtable_lookup(st, name);
2236
6
            if (cur < 0)
2237
0
                return 0;
2238
6
            if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) {
2239
0
                const char* msg;
2240
0
                if (cur & DEF_PARAM) {
2241
0
                    msg = NONLOCAL_PARAM;
2242
0
                } else if (cur & USE) {
2243
0
                    msg = NONLOCAL_AFTER_USE;
2244
0
                } else if (cur & DEF_ANNOT) {
2245
0
                    msg = NONLOCAL_ANNOT;
2246
0
                } else {  /* DEF_LOCAL */
2247
0
                    msg = NONLOCAL_AFTER_ASSIGN;
2248
0
                }
2249
0
                PyErr_Format(PyExc_SyntaxError, msg, name);
2250
0
                SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
2251
0
                return 0;
2252
0
            }
2253
6
            if (!symtable_add_def(st, name, DEF_NONLOCAL, LOCATION(s)))
2254
0
                return 0;
2255
6
            if (!symtable_record_directive(st, name, LOCATION(s))) {
2256
0
                return 0;
2257
0
            }
2258
6
        }
2259
5
        break;
2260
5
    }
2261
4.60k
    case Expr_kind:
2262
4.60k
        VISIT(st, expr, s->v.Expr.value);
2263
4.60k
        break;
2264
4.60k
    case Pass_kind:
2265
287
    case Break_kind:
2266
337
    case Continue_kind:
2267
        /* nothing to do here */
2268
337
        break;
2269
114
    case With_kind: {
2270
114
        ENTER_CONDITIONAL_BLOCK(st);
2271
114
        VISIT_SEQ(st, withitem, s->v.With.items);
2272
114
        VISIT_SEQ(st, stmt, s->v.With.body);
2273
114
        LEAVE_CONDITIONAL_BLOCK(st);
2274
114
        break;
2275
114
    }
2276
135
    case AsyncFunctionDef_kind: {
2277
135
        if (!symtable_add_def(st, s->v.AsyncFunctionDef.name, DEF_LOCAL, LOCATION(s)))
2278
0
            return 0;
2279
135
        if (s->v.AsyncFunctionDef.args->defaults)
2280
135
            VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.args->defaults);
2281
135
        if (s->v.AsyncFunctionDef.args->kw_defaults)
2282
135
            VISIT_SEQ_WITH_NULL(st, expr,
2283
135
                                s->v.AsyncFunctionDef.args->kw_defaults);
2284
135
        if (s->v.AsyncFunctionDef.decorator_list)
2285
2
            VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.decorator_list);
2286
135
        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
135
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
2300
135
                                           LOCATION(s));
2301
135
        if (!new_ste) {
2302
0
            return 0;
2303
0
        }
2304
2305
135
        if (_PyAST_GetDocString(s->v.AsyncFunctionDef.body)) {
2306
62
            new_ste->ste_has_docstring = 1;
2307
62
        }
2308
2309
135
        if (!symtable_visit_annotations(st, s, s->v.AsyncFunctionDef.args,
2310
135
                                        s->v.AsyncFunctionDef.returns, new_ste)) {
2311
0
            Py_DECREF(new_ste);
2312
0
            return 0;
2313
0
        }
2314
135
        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
135
        Py_DECREF(new_ste);
2319
2320
135
        st->st_cur->ste_coroutine = 1;
2321
135
        VISIT(st, arguments, s->v.AsyncFunctionDef.args);
2322
135
        VISIT_SEQ(st, stmt, s->v.AsyncFunctionDef.body);
2323
135
        if (!symtable_exit_block(st))
2324
0
            return 0;
2325
135
        if (asdl_seq_LEN(s->v.AsyncFunctionDef.type_params) > 0) {
2326
0
            if (!symtable_exit_block(st))
2327
0
                return 0;
2328
0
        }
2329
135
        break;
2330
135
    }
2331
135
    case AsyncWith_kind: {
2332
5
        maybe_set_ste_coroutine_for_module(st, s);
2333
5
        if (!symtable_raise_if_not_coroutine(st, ASYNC_WITH_OUTSIDE_ASYNC_FUNC, LOCATION(s))) {
2334
0
            return 0;
2335
0
        }
2336
5
        ENTER_CONDITIONAL_BLOCK(st);
2337
5
        VISIT_SEQ(st, withitem, s->v.AsyncWith.items);
2338
5
        VISIT_SEQ(st, stmt, s->v.AsyncWith.body);
2339
5
        LEAVE_CONDITIONAL_BLOCK(st);
2340
5
        break;
2341
5
    }
2342
0
    case AsyncFor_kind: {
2343
0
        maybe_set_ste_coroutine_for_module(st, s);
2344
0
        if (!symtable_raise_if_not_coroutine(st, ASYNC_FOR_OUTSIDE_ASYNC_FUNC, LOCATION(s))) {
2345
0
            return 0;
2346
0
        }
2347
0
        VISIT(st, expr, s->v.AsyncFor.target);
2348
0
        VISIT(st, expr, s->v.AsyncFor.iter);
2349
0
        ENTER_CONDITIONAL_BLOCK(st);
2350
0
        VISIT_SEQ(st, stmt, s->v.AsyncFor.body);
2351
0
        if (s->v.AsyncFor.orelse)
2352
0
            VISIT_SEQ(st, stmt, s->v.AsyncFor.orelse);
2353
0
        LEAVE_CONDITIONAL_BLOCK(st);
2354
0
        break;
2355
0
    }
2356
23.1k
    }
2357
23.1k
    LEAVE_RECURSIVE();
2358
23.1k
    return 1;
2359
23.1k
}
2360
2361
static int
2362
symtable_extend_namedexpr_scope(struct symtable *st, expr_ty e)
2363
0
{
2364
0
    assert(st->st_stack);
2365
0
    assert(e->kind == Name_kind);
2366
2367
0
    PyObject *target_name = e->v.Name.id;
2368
0
    Py_ssize_t i, size;
2369
0
    struct _symtable_entry *ste;
2370
0
    size = PyList_GET_SIZE(st->st_stack);
2371
0
    assert(size);
2372
2373
    /* Iterate over the stack in reverse and add to the nearest adequate scope */
2374
0
    for (i = size - 1; i >= 0; i--) {
2375
0
        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
0
        if (ste->ste_comprehension) {
2381
0
            long target_in_scope = symtable_lookup_entry(st, ste, target_name);
2382
0
            if (target_in_scope < 0) {
2383
0
                return 0;
2384
0
            }
2385
0
            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
0
            continue;
2392
0
        }
2393
2394
        /* If we find a FunctionBlock entry, add as GLOBAL/LOCAL or NONLOCAL/LOCAL */
2395
0
        if (ste->ste_type == FunctionBlock) {
2396
0
            long target_in_scope = symtable_lookup_entry(st, ste, target_name);
2397
0
            if (target_in_scope < 0) {
2398
0
                return 0;
2399
0
            }
2400
0
            if (target_in_scope & DEF_GLOBAL) {
2401
0
                if (!symtable_add_def(st, target_name, DEF_GLOBAL, LOCATION(e)))
2402
0
                    return 0;
2403
0
            } else {
2404
0
                if (!symtable_add_def(st, target_name, DEF_NONLOCAL, LOCATION(e))) {
2405
0
                    return 0;
2406
0
                }
2407
0
            }
2408
0
            if (!symtable_record_directive(st, target_name, LOCATION(e))) {
2409
0
                return 0;
2410
0
            }
2411
2412
0
            return symtable_add_def_helper(st, target_name, DEF_LOCAL, ste, LOCATION(e));
2413
0
        }
2414
        /* If we find a ModuleBlock entry, add as GLOBAL */
2415
0
        if (ste->ste_type == ModuleBlock) {
2416
0
            if (!symtable_add_def(st, target_name, DEF_GLOBAL, LOCATION(e))) {
2417
0
                return 0;
2418
0
            }
2419
0
            if (!symtable_record_directive(st, target_name, LOCATION(e))) {
2420
0
                return 0;
2421
0
            }
2422
2423
0
            return symtable_add_def_helper(st, target_name, DEF_GLOBAL, ste, LOCATION(e));
2424
0
        }
2425
        /* Disallow usage in ClassBlock and type scopes */
2426
0
        if (ste->ste_type == ClassBlock ||
2427
0
            ste->ste_type == TypeParametersBlock ||
2428
0
            ste->ste_type == TypeAliasBlock ||
2429
0
            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
0
    }
2450
2451
    /* We should always find either a function-like block, ModuleBlock or ClassBlock
2452
       and should never fall to this case
2453
    */
2454
0
    Py_UNREACHABLE();
2455
0
    return 0;
2456
0
}
2457
2458
static int
2459
symtable_handle_namedexpr(struct symtable *st, expr_ty e)
2460
9
{
2461
9
    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
9
    if (st->st_cur->ste_comprehension) {
2468
        /* Inside a comprehension body, so find the right target scope */
2469
0
        if (!symtable_extend_namedexpr_scope(st, e->v.NamedExpr.target))
2470
0
            return 0;
2471
0
    }
2472
9
    VISIT(st, expr, e->v.NamedExpr.value);
2473
9
    VISIT(st, expr, e->v.NamedExpr.target);
2474
9
    return 1;
2475
9
}
2476
2477
static int
2478
symtable_visit_expr(struct symtable *st, expr_ty e)
2479
109k
{
2480
109k
    ENTER_RECURSIVE();
2481
109k
    switch (e->kind) {
2482
9
    case NamedExpr_kind:
2483
9
        if (!symtable_raise_if_annotation_block(st, "named expression", e)) {
2484
0
            return 0;
2485
0
        }
2486
9
        if(!symtable_handle_namedexpr(st, e))
2487
0
            return 0;
2488
9
        break;
2489
766
    case BoolOp_kind:
2490
766
        VISIT_SEQ(st, expr, e->v.BoolOp.values);
2491
766
        break;
2492
766
    case BinOp_kind:
2493
696
        VISIT(st, expr, e->v.BinOp.left);
2494
696
        VISIT(st, expr, e->v.BinOp.right);
2495
696
        break;
2496
696
    case UnaryOp_kind:
2497
589
        VISIT(st, expr, e->v.UnaryOp.operand);
2498
589
        break;
2499
589
    case Lambda_kind: {
2500
262
        if (e->v.Lambda.args->defaults)
2501
262
            VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
2502
262
        if (e->v.Lambda.args->kw_defaults)
2503
262
            VISIT_SEQ_WITH_NULL(st, expr, e->v.Lambda.args->kw_defaults);
2504
262
        if (!symtable_enter_block(st, &_Py_STR(anon_lambda),
2505
262
                                  FunctionBlock, (void *)e, LOCATION(e))) {
2506
0
            return 0;
2507
0
        }
2508
262
        VISIT(st, arguments, e->v.Lambda.args);
2509
262
        VISIT(st, expr, e->v.Lambda.body);
2510
262
        if (!symtable_exit_block(st))
2511
0
            return 0;
2512
262
        break;
2513
262
    }
2514
262
    case IfExp_kind:
2515
120
        VISIT(st, expr, e->v.IfExp.test);
2516
120
        VISIT(st, expr, e->v.IfExp.body);
2517
120
        VISIT(st, expr, e->v.IfExp.orelse);
2518
120
        break;
2519
145
    case Dict_kind:
2520
145
        VISIT_SEQ_WITH_NULL(st, expr, e->v.Dict.keys);
2521
145
        VISIT_SEQ(st, expr, e->v.Dict.values);
2522
145
        break;
2523
201
    case Set_kind:
2524
201
        VISIT_SEQ(st, expr, e->v.Set.elts);
2525
201
        break;
2526
201
    case GeneratorExp_kind:
2527
38
        if (!symtable_visit_genexp(st, e))
2528
0
            return 0;
2529
38
        break;
2530
44
    case ListComp_kind:
2531
44
        if (!symtable_visit_listcomp(st, e))
2532
0
            return 0;
2533
44
        break;
2534
44
    case SetComp_kind:
2535
7
        if (!symtable_visit_setcomp(st, e))
2536
0
            return 0;
2537
7
        break;
2538
7
    case DictComp_kind:
2539
5
        if (!symtable_visit_dictcomp(st, e))
2540
0
            return 0;
2541
5
        break;
2542
88
    case Yield_kind:
2543
88
        if (!symtable_raise_if_annotation_block(st, "yield expression", e)) {
2544
0
            return 0;
2545
0
        }
2546
88
        if (e->v.Yield.value)
2547
82
            VISIT(st, expr, e->v.Yield.value);
2548
88
        st->st_cur->ste_generator = 1;
2549
88
        if (st->st_cur->ste_comprehension) {
2550
0
            return symtable_raise_if_comprehension_block(st, e);
2551
0
        }
2552
88
        break;
2553
88
    case YieldFrom_kind:
2554
19
        if (!symtable_raise_if_annotation_block(st, "yield expression", e)) {
2555
0
            return 0;
2556
0
        }
2557
19
        VISIT(st, expr, e->v.YieldFrom.value);
2558
19
        st->st_cur->ste_generator = 1;
2559
19
        if (st->st_cur->ste_comprehension) {
2560
0
            return symtable_raise_if_comprehension_block(st, e);
2561
0
        }
2562
19
        break;
2563
123
    case Await_kind:
2564
123
        if (!symtable_raise_if_annotation_block(st, "await expression", e)) {
2565
0
            return 0;
2566
0
        }
2567
123
        if (!allows_top_level_await(st)) {
2568
123
            if (!_PyST_IsFunctionLike(st->st_cur)) {
2569
0
                PyErr_SetString(PyExc_SyntaxError,
2570
0
                                "'await' outside function");
2571
0
                SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
2572
0
                return 0;
2573
0
            }
2574
123
            if (!IS_ASYNC_DEF(st) && st->st_cur->ste_comprehension == NoComprehension) {
2575
0
                PyErr_SetString(PyExc_SyntaxError,
2576
0
                                "'await' outside async function");
2577
0
                SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
2578
0
                return 0;
2579
0
            }
2580
123
        }
2581
123
        VISIT(st, expr, e->v.Await.value);
2582
123
        st->st_cur->ste_coroutine = 1;
2583
123
        break;
2584
3.38k
    case Compare_kind:
2585
3.38k
        VISIT(st, expr, e->v.Compare.left);
2586
3.38k
        VISIT_SEQ(st, expr, e->v.Compare.comparators);
2587
3.38k
        break;
2588
10.3k
    case Call_kind:
2589
10.3k
        VISIT(st, expr, e->v.Call.func);
2590
10.3k
        VISIT_SEQ(st, expr, e->v.Call.args);
2591
10.3k
        if (!check_keywords(st, e->v.Call.keywords)) {
2592
0
            return 0;
2593
0
        }
2594
10.3k
        VISIT_SEQ_WITH_NULL(st, keyword, e->v.Call.keywords);
2595
10.3k
        break;
2596
10.3k
    case FormattedValue_kind:
2597
1.91k
        VISIT(st, expr, e->v.FormattedValue.value);
2598
1.91k
        if (e->v.FormattedValue.format_spec)
2599
7
            VISIT(st, expr, e->v.FormattedValue.format_spec);
2600
1.91k
        break;
2601
1.91k
    case Interpolation_kind:
2602
0
        VISIT(st, expr, e->v.Interpolation.value);
2603
0
        if (e->v.Interpolation.format_spec)
2604
0
            VISIT(st, expr, e->v.Interpolation.format_spec);
2605
0
        break;
2606
732
    case JoinedStr_kind:
2607
732
        VISIT_SEQ(st, expr, e->v.JoinedStr.values);
2608
732
        break;
2609
732
    case TemplateStr_kind:
2610
0
        VISIT_SEQ(st, expr, e->v.TemplateStr.values);
2611
0
        break;
2612
25.8k
    case Constant_kind:
2613
        /* Nothing to do here. */
2614
25.8k
        break;
2615
    /* The following exprs can be assignment targets. */
2616
17.3k
    case Attribute_kind:
2617
17.3k
        if (!check_name(st, e->v.Attribute.attr, LOCATION(e), e->v.Attribute.ctx)) {
2618
0
            return 0;
2619
0
        }
2620
17.3k
        VISIT(st, expr, e->v.Attribute.value);
2621
17.3k
        break;
2622
17.3k
    case Subscript_kind:
2623
914
        VISIT(st, expr, e->v.Subscript.value);
2624
914
        VISIT(st, expr, e->v.Subscript.slice);
2625
914
        break;
2626
914
    case Starred_kind:
2627
115
        VISIT(st, expr, e->v.Starred.value);
2628
115
        break;
2629
130
    case Slice_kind:
2630
130
        if (e->v.Slice.lower)
2631
70
            VISIT(st, expr, e->v.Slice.lower);
2632
130
        if (e->v.Slice.upper)
2633
78
            VISIT(st, expr, e->v.Slice.upper);
2634
130
        if (e->v.Slice.step)
2635
0
            VISIT(st, expr, e->v.Slice.step);
2636
130
        break;
2637
43.8k
    case Name_kind:
2638
43.8k
        if (!st->st_cur->ste_in_unevaluated_annotation) {
2639
43.8k
            if (!symtable_add_def_ctx(st, e->v.Name.id,
2640
43.8k
                                    e->v.Name.ctx == Load ? USE : DEF_LOCAL,
2641
43.8k
                                    LOCATION(e), e->v.Name.ctx)) {
2642
0
                return 0;
2643
0
            }
2644
            /* Special-case super: it counts as a use of __class__ */
2645
43.8k
            if (e->v.Name.ctx == Load &&
2646
39.4k
                _PyST_IsFunctionLike(st->st_cur) &&
2647
37.4k
                _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
2648
256
                if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
2649
0
                    return 0;
2650
256
            }
2651
43.8k
        }
2652
43.8k
        break;
2653
    /* child nodes of List and Tuple will have expr_context set */
2654
43.8k
    case List_kind:
2655
227
        VISIT_SEQ(st, expr, e->v.List.elts);
2656
227
        break;
2657
1.31k
    case Tuple_kind:
2658
1.31k
        VISIT_SEQ(st, expr, e->v.Tuple.elts);
2659
1.31k
        break;
2660
109k
    }
2661
109k
    LEAVE_RECURSIVE();
2662
109k
    return 1;
2663
109k
}
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
0
{
2670
0
    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
0
    if (e) {
2681
0
        int is_in_class = st->st_cur->ste_can_see_class_scope;
2682
0
        if (!symtable_enter_block(st, name, TypeVariableBlock, (void *)tp, LOCATION(e))) {
2683
0
            return 0;
2684
0
        }
2685
2686
0
        st->st_cur->ste_can_see_class_scope = is_in_class;
2687
0
        if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(e))) {
2688
0
            return 0;
2689
0
        }
2690
2691
0
        assert(ste_scope_info != NULL);
2692
0
        st->st_cur->ste_scope_info = ste_scope_info;
2693
0
        VISIT(st, expr, e);
2694
2695
0
        if (!symtable_exit_block(st)) {
2696
0
            return 0;
2697
0
        }
2698
0
    }
2699
0
    return 1;
2700
0
}
2701
2702
static int
2703
symtable_visit_type_param(struct symtable *st, type_param_ty tp)
2704
0
{
2705
0
    ENTER_RECURSIVE();
2706
0
    switch(tp->kind) {
2707
0
    case TypeVar_kind:
2708
0
        if (!symtable_add_def(st, tp->v.TypeVar.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp)))
2709
0
            return 0;
2710
2711
0
        const char *ste_scope_info = NULL;
2712
0
        const expr_ty bound = tp->v.TypeVar.bound;
2713
0
        if (bound != NULL) {
2714
0
            ste_scope_info = bound->kind == Tuple_kind ? "a TypeVar constraint" : "a TypeVar bound";
2715
0
        }
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
0
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVar.bound, tp->v.TypeVar.name,
2724
0
                                                        tp, ste_scope_info)) {
2725
0
            return 0;
2726
0
        }
2727
2728
0
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVar.default_value, tp->v.TypeVar.name,
2729
0
                                                        (type_param_ty)((uintptr_t)tp + 1), "a TypeVar default")) {
2730
0
            return 0;
2731
0
        }
2732
0
        break;
2733
0
    case TypeVarTuple_kind:
2734
0
        if (!symtable_add_def(st, tp->v.TypeVarTuple.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) {
2735
0
            return 0;
2736
0
        }
2737
2738
0
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVarTuple.default_value, tp->v.TypeVarTuple.name,
2739
0
                                                        tp, "a TypeVarTuple default")) {
2740
0
            return 0;
2741
0
        }
2742
0
        break;
2743
0
    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
0
    }
2754
0
    LEAVE_RECURSIVE();
2755
0
    return 1;
2756
0
}
2757
2758
static int
2759
symtable_visit_pattern(struct symtable *st, pattern_ty p)
2760
4
{
2761
4
    ENTER_RECURSIVE();
2762
4
    switch (p->kind) {
2763
4
    case MatchValue_kind:
2764
4
        VISIT(st, expr, p->v.MatchValue.value);
2765
4
        break;
2766
4
    case MatchSingleton_kind:
2767
        /* Nothing to do here. */
2768
0
        break;
2769
0
    case MatchSequence_kind:
2770
0
        VISIT_SEQ(st, pattern, p->v.MatchSequence.patterns);
2771
0
        break;
2772
0
    case MatchStar_kind:
2773
0
        if (p->v.MatchStar.name) {
2774
0
            if (!symtable_add_def(st, p->v.MatchStar.name, DEF_LOCAL, LOCATION(p))) {
2775
0
                return 0;
2776
0
            }
2777
0
        }
2778
0
        break;
2779
0
    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
0
    case MatchClass_kind:
2789
0
        VISIT(st, expr, p->v.MatchClass.cls);
2790
0
        VISIT_SEQ(st, pattern, p->v.MatchClass.patterns);
2791
0
        if (!check_kwd_patterns(st, p)) {
2792
0
            return 0;
2793
0
        }
2794
0
        VISIT_SEQ(st, pattern, p->v.MatchClass.kwd_patterns);
2795
0
        break;
2796
0
    case MatchAs_kind:
2797
0
        if (p->v.MatchAs.pattern) {
2798
0
            VISIT(st, pattern, p->v.MatchAs.pattern);
2799
0
        }
2800
0
        if (p->v.MatchAs.name) {
2801
0
            if (!symtable_add_def(st, p->v.MatchAs.name, DEF_LOCAL, LOCATION(p))) {
2802
0
                return 0;
2803
0
            }
2804
0
        }
2805
0
        break;
2806
0
    case MatchOr_kind:
2807
0
        VISIT_SEQ(st, pattern, p->v.MatchOr.patterns);
2808
0
        break;
2809
4
    }
2810
4
    LEAVE_RECURSIVE();
2811
4
    return 1;
2812
4
}
2813
2814
static int
2815
symtable_implicit_arg(struct symtable *st, int pos)
2816
94
{
2817
94
    PyObject *id = PyUnicode_FromFormat(".%d", pos);
2818
94
    if (id == NULL)
2819
0
        return 0;
2820
94
    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
94
    Py_DECREF(id);
2825
94
    return 1;
2826
94
}
2827
2828
static int
2829
symtable_visit_params(struct symtable *st, asdl_arg_seq *args)
2830
11.3k
{
2831
11.3k
    Py_ssize_t i;
2832
2833
21.4k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2834
10.1k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2835
10.1k
        if (!symtable_add_def(st, arg->arg, DEF_PARAM, LOCATION(arg)))
2836
0
            return 0;
2837
10.1k
    }
2838
2839
11.3k
    return 1;
2840
11.3k
}
2841
2842
static int
2843
symtable_visit_annotation(struct symtable *st, expr_ty annotation, void *key)
2844
18
{
2845
    // Annotations in local scopes are not executed and should not affect the symtable
2846
18
    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
18
    if ((((st->st_cur->ste_type == ClassBlock && st->st_cur->ste_in_conditional_block)
2851
18
            || st->st_cur->ste_type == ModuleBlock))
2852
0
            && !st->st_cur->ste_has_conditional_annotations)
2853
0
    {
2854
0
        st->st_cur->ste_has_conditional_annotations = 1;
2855
0
        if (!symtable_add_def(st, &_Py_ID(__conditional_annotations__), USE, LOCATION(annotation))) {
2856
0
            return 0;
2857
0
        }
2858
0
    }
2859
18
    struct _symtable_entry *parent_ste = st->st_cur;
2860
18
    if (parent_ste->ste_annotation_block == NULL) {
2861
10
        _Py_block_ty current_type = parent_ste->ste_type;
2862
10
        if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2863
10
                                    key, LOCATION(annotation))) {
2864
0
            return 0;
2865
0
        }
2866
10
        parent_ste->ste_annotation_block =
2867
10
            (struct _symtable_entry *)Py_NewRef(st->st_cur);
2868
10
        int future_annotations = st->st_future->ff_features & CO_FUTURE_ANNOTATIONS;
2869
10
        if (current_type == ClassBlock && !future_annotations) {
2870
6
            st->st_cur->ste_can_see_class_scope = 1;
2871
6
            if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(annotation))) {
2872
0
                return 0;
2873
0
            }
2874
6
        }
2875
10
    }
2876
8
    else {
2877
8
        if (!symtable_enter_existing_block(st, parent_ste->ste_annotation_block,
2878
8
                                           /* add_to_children */false)) {
2879
0
            return 0;
2880
0
        }
2881
8
    }
2882
18
    if (is_unevaluated) {
2883
6
        st->st_cur->ste_in_unevaluated_annotation = 1;
2884
6
    }
2885
18
    int rc = symtable_visit_expr(st, annotation);
2886
18
    if (is_unevaluated) {
2887
6
        st->st_cur->ste_in_unevaluated_annotation = 0;
2888
6
    }
2889
18
    if (!symtable_exit_block(st)) {
2890
0
        return 0;
2891
0
    }
2892
18
    return rc;
2893
18
}
2894
2895
static int
2896
symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args)
2897
10.5k
{
2898
10.5k
    Py_ssize_t i;
2899
2900
19.5k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2901
8.96k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2902
8.96k
        if (arg->annotation) {
2903
49
            st->st_cur->ste_annotations_used = 1;
2904
49
            VISIT(st, expr, arg->annotation);
2905
49
        }
2906
8.96k
    }
2907
2908
10.5k
    return 1;
2909
10.5k
}
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
3.52k
{
2915
3.52k
    int is_in_class = st->st_cur->ste_can_see_class_scope;
2916
3.52k
    _Py_block_ty current_type = st->st_cur->ste_type;
2917
3.52k
    if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2918
3.52k
                              (void *)a, LOCATION(o))) {
2919
0
        return 0;
2920
0
    }
2921
3.52k
    if (is_in_class || current_type == ClassBlock) {
2922
1.78k
        st->st_cur->ste_can_see_class_scope = 1;
2923
1.78k
        if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(o))) {
2924
0
            return 0;
2925
0
        }
2926
1.78k
    }
2927
3.52k
    if (a->posonlyargs && !symtable_visit_argannotations(st, a->posonlyargs))
2928
0
        return 0;
2929
3.52k
    if (a->args && !symtable_visit_argannotations(st, a->args))
2930
0
        return 0;
2931
3.52k
    if (a->vararg && a->vararg->annotation) {
2932
0
        st->st_cur->ste_annotations_used = 1;
2933
0
        VISIT(st, expr, a->vararg->annotation);
2934
0
    }
2935
3.52k
    if (a->kwarg && a->kwarg->annotation) {
2936
0
        st->st_cur->ste_annotations_used = 1;
2937
0
        VISIT(st, expr, a->kwarg->annotation);
2938
0
    }
2939
3.52k
    if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs))
2940
0
        return 0;
2941
3.52k
    if (returns) {
2942
36
        st->st_cur->ste_annotations_used = 1;
2943
36
        VISIT(st, expr, returns);
2944
36
    }
2945
3.52k
    if (!symtable_exit_block(st)) {
2946
0
        return 0;
2947
0
    }
2948
3.52k
    return 1;
2949
3.52k
}
2950
2951
static int
2952
symtable_visit_arguments(struct symtable *st, arguments_ty a)
2953
3.78k
{
2954
    /* skip default arguments inside function block
2955
       XXX should ast be different?
2956
    */
2957
3.78k
    if (a->posonlyargs && !symtable_visit_params(st, a->posonlyargs))
2958
0
        return 0;
2959
3.78k
    if (a->args && !symtable_visit_params(st, a->args))
2960
0
        return 0;
2961
3.78k
    if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs))
2962
0
        return 0;
2963
3.78k
    if (a->vararg) {
2964
117
        if (!symtable_add_def(st, a->vararg->arg, DEF_PARAM, LOCATION(a->vararg)))
2965
0
            return 0;
2966
117
        st->st_cur->ste_varargs = 1;
2967
117
    }
2968
3.78k
    if (a->kwarg) {
2969
106
        if (!symtable_add_def(st, a->kwarg->arg, DEF_PARAM, LOCATION(a->kwarg)))
2970
0
            return 0;
2971
106
        st->st_cur->ste_varkeywords = 1;
2972
106
    }
2973
3.78k
    return 1;
2974
3.78k
}
2975
2976
2977
static int
2978
symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
2979
438
{
2980
438
    if (eh->v.ExceptHandler.type)
2981
410
        VISIT(st, expr, eh->v.ExceptHandler.type);
2982
438
    if (eh->v.ExceptHandler.name)
2983
103
        if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL, LOCATION(eh)))
2984
0
            return 0;
2985
438
    VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
2986
438
    return 1;
2987
438
}
2988
2989
static int
2990
symtable_visit_withitem(struct symtable *st, withitem_ty item)
2991
123
{
2992
123
    VISIT(st, expr, item->context_expr);
2993
123
    if (item->optional_vars) {
2994
31
        VISIT(st, expr, item->optional_vars);
2995
31
    }
2996
123
    return 1;
2997
123
}
2998
2999
static int
3000
symtable_visit_match_case(struct symtable *st, match_case_ty m)
3001
4
{
3002
4
    VISIT(st, pattern, m->pattern);
3003
4
    if (m->guard) {
3004
0
        VISIT(st, expr, m->guard);
3005
0
    }
3006
4
    VISIT_SEQ(st, stmt, m->body);
3007
4
    return 1;
3008
4
}
3009
3010
static int
3011
symtable_visit_alias(struct symtable *st, alias_ty a)
3012
961
{
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
961
    PyObject *store_name;
3018
961
    PyObject *name = (a->asname == NULL) ? a->name : a->asname;
3019
961
    Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
3020
961
                                        PyUnicode_GET_LENGTH(name), 1);
3021
961
    if (dot != -1) {
3022
15
        store_name = PyUnicode_Substring(name, 0, dot);
3023
15
        if (!store_name)
3024
0
            return 0;
3025
15
    }
3026
946
    else {
3027
946
        store_name = Py_NewRef(name);
3028
946
    }
3029
961
    if (!_PyUnicode_EqualToASCIIString(name, "*")) {
3030
940
        int r = symtable_add_def(st, store_name, DEF_IMPORT, LOCATION(a));
3031
940
        Py_DECREF(store_name);
3032
940
        return r;
3033
940
    }
3034
21
    else {
3035
21
        if (st->st_cur->ste_type != ModuleBlock) {
3036
0
            PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING);
3037
0
            SET_ERROR_LOCATION(st->st_filename, LOCATION(a));
3038
0
            Py_DECREF(store_name);
3039
0
            return 0;
3040
0
        }
3041
21
        Py_DECREF(store_name);
3042
21
        return 1;
3043
21
    }
3044
961
}
3045
3046
3047
static int
3048
symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
3049
1
{
3050
1
    st->st_cur->ste_comp_iter_target = 1;
3051
1
    VISIT(st, expr, lc->target);
3052
1
    st->st_cur->ste_comp_iter_target = 0;
3053
1
    st->st_cur->ste_comp_iter_expr++;
3054
1
    VISIT(st, expr, lc->iter);
3055
1
    st->st_cur->ste_comp_iter_expr--;
3056
1
    VISIT_SEQ(st, expr, lc->ifs);
3057
1
    if (lc->is_async) {
3058
0
        st->st_cur->ste_coroutine = 1;
3059
0
    }
3060
1
    return 1;
3061
1
}
3062
3063
3064
static int
3065
symtable_visit_keyword(struct symtable *st, keyword_ty k)
3066
1.81k
{
3067
1.81k
    VISIT(st, expr, k->value);
3068
1.81k
    return 1;
3069
1.81k
}
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
94
{
3077
94
    int is_generator = (e->kind == GeneratorExp_kind);
3078
94
    comprehension_ty outermost = ((comprehension_ty)
3079
94
                                    asdl_seq_GET(generators, 0));
3080
    /* Outermost iterator is evaluated in current scope */
3081
94
    st->st_cur->ste_comp_iter_expr++;
3082
94
    VISIT(st, expr, outermost->iter);
3083
94
    st->st_cur->ste_comp_iter_expr--;
3084
    /* Create comprehension scope for the rest */
3085
94
    if (!scope_name ||
3086
94
        !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, LOCATION(e))) {
3087
0
        return 0;
3088
0
    }
3089
94
    switch(e->kind) {
3090
44
        case ListComp_kind:
3091
44
            st->st_cur->ste_comprehension = ListComprehension;
3092
44
            break;
3093
7
        case SetComp_kind:
3094
7
            st->st_cur->ste_comprehension = SetComprehension;
3095
7
            break;
3096
5
        case DictComp_kind:
3097
5
            st->st_cur->ste_comprehension = DictComprehension;
3098
5
            break;
3099
38
        default:
3100
38
            st->st_cur->ste_comprehension = GeneratorExpression;
3101
38
            break;
3102
94
    }
3103
94
    if (outermost->is_async) {
3104
0
        st->st_cur->ste_coroutine = 1;
3105
0
    }
3106
3107
    /* Outermost iter is received as an argument */
3108
94
    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
94
    st->st_cur->ste_comp_iter_target = 1;
3114
94
    VISIT(st, expr, outermost->target);
3115
94
    st->st_cur->ste_comp_iter_target = 0;
3116
    /* Visit the rest of the comprehension body */
3117
94
    VISIT_SEQ(st, expr, outermost->ifs);
3118
94
    VISIT_SEQ_TAIL(st, comprehension, generators, 1);
3119
94
    if (value)
3120
5
        VISIT(st, expr, value);
3121
94
    VISIT(st, expr, elt);
3122
94
    st->st_cur->ste_generator = is_generator;
3123
94
    int is_async = st->st_cur->ste_coroutine && !is_generator;
3124
94
    if (!symtable_exit_block(st)) {
3125
0
        return 0;
3126
0
    }
3127
94
    if (is_async &&
3128
0
        !IS_ASYNC_DEF(st) &&
3129
0
        st->st_cur->ste_comprehension == NoComprehension &&
3130
0
        !allows_top_level_await(st))
3131
0
    {
3132
0
        PyErr_SetString(PyExc_SyntaxError, "asynchronous comprehension outside of "
3133
0
                                           "an asynchronous function");
3134
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3135
0
        return 0;
3136
0
    }
3137
94
    if (is_async) {
3138
0
        st->st_cur->ste_coroutine = 1;
3139
0
    }
3140
94
    return 1;
3141
94
}
3142
3143
static int
3144
symtable_visit_genexp(struct symtable *st, expr_ty e)
3145
38
{
3146
38
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_genexpr),
3147
38
                                         e->v.GeneratorExp.generators,
3148
38
                                         e->v.GeneratorExp.elt, NULL);
3149
38
}
3150
3151
static int
3152
symtable_visit_listcomp(struct symtable *st, expr_ty e)
3153
44
{
3154
44
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_listcomp),
3155
44
                                         e->v.ListComp.generators,
3156
44
                                         e->v.ListComp.elt, NULL);
3157
44
}
3158
3159
static int
3160
symtable_visit_setcomp(struct symtable *st, expr_ty e)
3161
7
{
3162
7
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_setcomp),
3163
7
                                         e->v.SetComp.generators,
3164
7
                                         e->v.SetComp.elt, NULL);
3165
7
}
3166
3167
static int
3168
symtable_visit_dictcomp(struct symtable *st, expr_ty e)
3169
5
{
3170
5
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_dictcomp),
3171
5
                                         e->v.DictComp.generators,
3172
5
                                         e->v.DictComp.key,
3173
5
                                         e->v.DictComp.value);
3174
5
}
3175
3176
static int
3177
symtable_raise_if_annotation_block(struct symtable *st, const char *name, expr_ty e)
3178
239
{
3179
239
    _Py_block_ty type = st->st_cur->ste_type;
3180
239
    if (type == AnnotationBlock)
3181
0
        PyErr_Format(PyExc_SyntaxError, ANNOTATION_NOT_ALLOWED, name);
3182
239
    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
239
    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
239
    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
239
    else
3198
239
        return 1;
3199
3200
0
    SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3201
0
    return 0;
3202
239
}
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
5
symtable_raise_if_not_coroutine(struct symtable *st, const char *msg, _Py_SourceLocation loc) {
3218
5
    if (!st->st_cur->ste_coroutine) {
3219
0
        PyErr_SetString(PyExc_SyntaxError, msg);
3220
0
        SET_ERROR_LOCATION(st->st_filename, loc);
3221
0
        return 0;
3222
0
    }
3223
5
    return 1;
3224
5
}
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
143k
{
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
143k
    if (ste->ste_mangled_names != NULL) {
3263
0
        int result = PySet_Contains(ste->ste_mangled_names, name);
3264
0
        if (result < 0) {
3265
0
            return NULL;
3266
0
        }
3267
0
        if (result == 0) {
3268
0
            return Py_NewRef(name);
3269
0
        }
3270
0
    }
3271
143k
    return _Py_Mangle(privateobj, name);
3272
143k
}
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
148k
{
3298
    /* Name mangling: __private becomes _classname__private.
3299
       This is independent from how the name is used. */
3300
148k
    if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
3301
74.9k
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3302
140k
        PyUnicode_READ_CHAR(ident, 1) != '_') {
3303
140k
        return Py_NewRef(ident);
3304
140k
    }
3305
7.57k
    size_t nlen = PyUnicode_GET_LENGTH(ident);
3306
7.57k
    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
7.57k
    if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3317
7.48k
         PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
3318
7.48k
        PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
3319
7.48k
        return Py_NewRef(ident); /* Don't mangle __whatever__ */
3320
7.48k
    }
3321
    /* Strip leading underscores from class name */
3322
90
    size_t ipriv = 0;
3323
90
    while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_') {
3324
0
        ipriv++;
3325
0
    }
3326
90
    if (ipriv == plen) {
3327
0
        return Py_NewRef(ident); /* Don't mangle if class is just underscores */
3328
0
    }
3329
3330
90
    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
90
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(1 + nlen + (plen - ipriv));
3337
90
    if (!writer) {
3338
0
        return NULL;
3339
0
    }
3340
    // ident = "_" + priv[ipriv:] + ident
3341
90
    if (PyUnicodeWriter_WriteChar(writer, '_') < 0) {
3342
0
        goto error;
3343
0
    }
3344
90
    if (PyUnicodeWriter_WriteSubstring(writer, privateobj, ipriv, plen) < 0) {
3345
0
        goto error;
3346
0
    }
3347
90
    if (PyUnicodeWriter_WriteStr(writer, ident) < 0) {
3348
0
        goto error;
3349
0
    }
3350
90
    return PyUnicodeWriter_Finish(writer);
3351
3352
0
error:
3353
0
    PyUnicodeWriter_Discard(writer);
3354
    return NULL;
3355
90
}