Coverage Report

Created: 2026-04-12 06:54

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
95.0k
#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
341
#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
9.38k
{
96
9.38k
    PySTEntryObject *ste = NULL;
97
9.38k
    PyObject *k = NULL;
98
99
9.38k
    k = PyLong_FromVoidPtr(key);
100
9.38k
    if (k == NULL)
101
0
        goto fail;
102
9.38k
    ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
103
9.38k
    if (ste == NULL) {
104
0
        Py_DECREF(k);
105
0
        goto fail;
106
0
    }
107
9.38k
    ste->ste_table = st;
108
9.38k
    ste->ste_id = k; /* ste owns reference to k */
109
110
9.38k
    ste->ste_name = Py_NewRef(name);
111
112
9.38k
    ste->ste_symbols = NULL;
113
9.38k
    ste->ste_varnames = NULL;
114
9.38k
    ste->ste_children = NULL;
115
116
9.38k
    ste->ste_directives = NULL;
117
9.38k
    ste->ste_mangled_names = NULL;
118
119
9.38k
    ste->ste_type = block;
120
9.38k
    ste->ste_scope_info = NULL;
121
122
9.38k
    ste->ste_nested = 0;
123
9.38k
    ste->ste_varargs = 0;
124
9.38k
    ste->ste_varkeywords = 0;
125
9.38k
    ste->ste_annotations_used = 0;
126
9.38k
    ste->ste_loc = loc;
127
128
9.38k
    if (st->st_cur != NULL &&
129
8.53k
        (st->st_cur->ste_nested ||
130
8.51k
         _PyST_IsFunctionLike(st->st_cur)))
131
2.28k
        ste->ste_nested = 1;
132
9.38k
    ste->ste_generator = 0;
133
9.38k
    ste->ste_coroutine = 0;
134
9.38k
    ste->ste_comprehension = NoComprehension;
135
9.38k
    ste->ste_returns_value = 0;
136
9.38k
    ste->ste_needs_class_closure = 0;
137
9.38k
    ste->ste_comp_inlined = 0;
138
9.38k
    ste->ste_comp_iter_target = 0;
139
9.38k
    ste->ste_can_see_class_scope = 0;
140
9.38k
    ste->ste_comp_iter_expr = 0;
141
9.38k
    ste->ste_needs_classdict = 0;
142
9.38k
    ste->ste_has_conditional_annotations = 0;
143
9.38k
    ste->ste_in_conditional_block = 0;
144
9.38k
    ste->ste_in_try_block = 0;
145
9.38k
    ste->ste_in_unevaluated_annotation = 0;
146
9.38k
    ste->ste_annotation_block = NULL;
147
148
9.38k
    ste->ste_has_docstring = 0;
149
150
9.38k
    ste->ste_method = 0;
151
9.38k
    if (st->st_cur != NULL &&
152
8.53k
        st->st_cur->ste_type == ClassBlock &&
153
3.65k
        block == FunctionBlock) {
154
1.82k
        ste->ste_method = 1;
155
1.82k
    }
156
157
9.38k
    ste->ste_symbols = PyDict_New();
158
9.38k
    ste->ste_varnames = PyList_New(0);
159
9.38k
    ste->ste_children = PyList_New(0);
160
9.38k
    if (ste->ste_symbols == NULL
161
9.38k
        || ste->ste_varnames == NULL
162
9.38k
        || ste->ste_children == NULL)
163
0
        goto fail;
164
165
9.38k
    if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
166
0
        goto fail;
167
168
9.38k
    return ste;
169
0
 fail:
170
0
    Py_XDECREF(ste);
171
0
    return NULL;
172
9.38k
}
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
9.38k
{
185
9.38k
    PySTEntryObject *ste = (PySTEntryObject *)op;
186
9.38k
    ste->ste_table = NULL;
187
9.38k
    Py_XDECREF(ste->ste_id);
188
9.38k
    Py_XDECREF(ste->ste_name);
189
9.38k
    Py_XDECREF(ste->ste_symbols);
190
9.38k
    Py_XDECREF(ste->ste_varnames);
191
9.38k
    Py_XDECREF(ste->ste_children);
192
9.38k
    Py_XDECREF(ste->ste_directives);
193
9.38k
    Py_XDECREF(ste->ste_annotation_block);
194
9.38k
    Py_XDECREF(ste->ste_mangled_names);
195
9.38k
    PyObject_Free(ste);
196
9.38k
}
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
859
{
390
859
    struct symtable *st;
391
392
859
    st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
393
859
    if (st == NULL) {
394
0
        PyErr_NoMemory();
395
0
        return NULL;
396
0
    }
397
398
859
    st->st_filename = NULL;
399
859
    st->st_blocks = NULL;
400
401
859
    if ((st->st_stack = PyList_New(0)) == NULL)
402
0
        goto fail;
403
859
    if ((st->st_blocks = PyDict_New()) == NULL)
404
0
        goto fail;
405
859
    st->st_cur = NULL;
406
859
    st->st_private = NULL;
407
859
    return st;
408
0
 fail:
409
0
    _PySymtable_Free(st);
410
0
    return NULL;
411
859
}
412
413
struct symtable *
414
_PySymtable_Build(mod_ty mod, PyObject *filename, _PyFutureFeatures *future)
415
859
{
416
859
    struct symtable *st = symtable_new();
417
859
    asdl_stmt_seq *seq;
418
859
    Py_ssize_t i;
419
859
    PyThreadState *tstate;
420
421
859
    if (st == NULL)
422
0
        return NULL;
423
859
    if (filename == NULL) {
424
0
        _PySymtable_Free(st);
425
0
        return NULL;
426
0
    }
427
859
    st->st_filename = Py_NewRef(filename);
428
859
    st->st_future = future;
429
430
    /* Setup recursion depth check counters */
431
859
    tstate = _PyThreadState_GET();
432
859
    if (!tstate) {
433
0
        _PySymtable_Free(st);
434
0
        return NULL;
435
0
    }
436
437
    /* Make the initial symbol information gathering pass */
438
439
859
    _Py_SourceLocation loc0 = {0, 0, 0, 0};
440
859
    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
859
    st->st_top = st->st_cur;
446
859
    switch (mod->kind) {
447
608
    case Module_kind:
448
608
        seq = mod->v.Module.body;
449
608
        if (_PyAST_GetDocString(seq)) {
450
122
            st->st_cur->ste_has_docstring = 1;
451
122
        }
452
3.65k
        for (i = 0; i < asdl_seq_LEN(seq); i++)
453
3.04k
            if (!symtable_visit_stmt(st,
454
3.04k
                        (stmt_ty)asdl_seq_GET(seq, i)))
455
0
                goto error;
456
608
        break;
457
608
    case Expression_kind:
458
251
        if (!symtable_visit_expr(st, mod->v.Expression.body))
459
0
            goto error;
460
251
        break;
461
251
    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
859
    }
473
859
    if (!symtable_exit_block(st)) {
474
0
        _PySymtable_Free(st);
475
0
        return NULL;
476
0
    }
477
    /* Make the second symbol analysis pass */
478
859
    if (symtable_analyze(st)) {
479
#if _PY_DUMP_SYMTABLE
480
        dump_symtable(st->st_top);
481
#endif
482
859
        return st;
483
859
    }
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
859
}
491
492
493
void
494
_PySymtable_Free(struct symtable *st)
495
859
{
496
859
    Py_XDECREF(st->st_filename);
497
859
    Py_XDECREF(st->st_blocks);
498
859
    Py_XDECREF(st->st_stack);
499
859
    PyMem_Free((void *)st);
500
859
}
501
502
PySTEntryObject *
503
_PySymtable_Lookup(struct symtable *st, void *key)
504
5.79k
{
505
5.79k
    PyObject *k, *v;
506
507
5.79k
    k = PyLong_FromVoidPtr(key);
508
5.79k
    if (k == NULL)
509
0
        return NULL;
510
5.79k
    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.79k
    Py_DECREF(k);
515
516
5.79k
    assert(v == NULL || PySTEntry_Check(v));
517
5.79k
    return (PySTEntryObject *)v;
518
5.79k
}
519
520
int
521
_PySymtable_LookupOptional(struct symtable *st, void *key,
522
                           PySTEntryObject **out)
523
3.70k
{
524
3.70k
    PyObject *k = PyLong_FromVoidPtr(key);
525
3.70k
    if (k == NULL) {
526
0
        *out = NULL;
527
0
        return -1;
528
0
    }
529
3.70k
    int result = PyDict_GetItemRef(st->st_blocks, k, (PyObject **)out);
530
3.70k
    Py_DECREF(k);
531
3.70k
    assert(*out == NULL || PySTEntry_Check(*out));
532
3.70k
    return result;
533
3.70k
}
534
535
long
536
_PyST_GetSymbol(PySTEntryObject *ste, PyObject *name)
537
69.9k
{
538
69.9k
    PyObject *v;
539
69.9k
    if (PyDict_GetItemRef(ste->ste_symbols, name, &v) < 0) {
540
0
        return -1;
541
0
    }
542
69.9k
    if (!v) {
543
10.4k
        return 0;
544
10.4k
    }
545
59.5k
    long symbol = PyLong_AsLong(v);
546
59.5k
    Py_DECREF(v);
547
59.5k
    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
59.5k
    return symbol;
554
59.5k
}
555
556
int
557
_PyST_GetScope(PySTEntryObject *ste, PyObject *name)
558
62.6k
{
559
62.6k
    long symbol = _PyST_GetSymbol(ste, name);
560
62.6k
    if (symbol < 0) {
561
0
        return -1;
562
0
    }
563
62.6k
    return SYMBOL_TO_SCOPE(symbol);
564
62.6k
}
565
566
int
567
_PyST_IsFunctionLike(PySTEntryObject *ste)
568
128k
{
569
128k
    return ste->ste_type == FunctionBlock
570
27.4k
        || ste->ste_type == AnnotationBlock
571
19.7k
        || ste->ste_type == TypeVariableBlock
572
19.7k
        || ste->ste_type == TypeAliasBlock
573
19.7k
        || ste->ste_type == TypeParametersBlock;
574
128k
}
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
33.4k
    do { \
649
33.4k
        PyObject *o = PyLong_FromLong(I); \
650
33.4k
        if (!o) \
651
33.4k
            return 0; \
652
33.4k
        if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
653
0
            Py_DECREF(o); \
654
0
            return 0; \
655
0
        } \
656
33.4k
        Py_DECREF(o); \
657
33.4k
    } 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
33.3k
{
671
33.3k
    int contains;
672
33.3k
    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
33.3k
    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
33.3k
    if (flags & DEF_BOUND) {
717
23.6k
        SET_SCOPE(scopes, name, LOCAL);
718
23.6k
        if (PySet_Add(local, name) < 0)
719
0
            return 0;
720
23.6k
        if (PySet_Discard(global, name) < 0)
721
0
            return 0;
722
23.6k
        if (flags & DEF_TYPE_PARAM) {
723
0
            if (PySet_Add(type_params, name) < 0)
724
0
                return 0;
725
0
        }
726
23.6k
        else {
727
23.6k
            if (PySet_Discard(type_params, name) < 0)
728
0
                return 0;
729
23.6k
        }
730
23.6k
        return 1;
731
23.6k
    }
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.66k
    if (class_entry != NULL) {
740
1.87k
        long class_flags = _PyST_GetSymbol(class_entry, name);
741
1.87k
        if (class_flags < 0) {
742
0
            return 0;
743
0
        }
744
1.87k
        if (class_flags & DEF_GLOBAL) {
745
0
            SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
746
0
            return 1;
747
0
        }
748
1.87k
        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.87k
    }
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.66k
    if (bound) {
759
9.50k
        contains = PySet_Contains(bound, name);
760
9.50k
        if (contains < 0) {
761
0
            return 0;
762
0
        }
763
9.50k
        if (contains) {
764
2.97k
            SET_SCOPE(scopes, name, FREE);
765
2.97k
            return PySet_Add(free, name) >= 0;
766
2.97k
        }
767
9.50k
    }
768
    /* If a parent has a global statement, then call it global
769
       explicit?  It could also be global implicit.
770
     */
771
6.69k
    if (global) {
772
6.69k
        contains = PySet_Contains(global, name);
773
6.69k
        if (contains < 0) {
774
0
            return 0;
775
0
        }
776
6.69k
        if (contains) {
777
4
            SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
778
4
            return 1;
779
4
        }
780
6.69k
    }
781
6.68k
    SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
782
6.68k
    return 1;
783
6.68k
}
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
55
{
807
55
    PyObject *k, *v;
808
55
    Py_ssize_t pos = 0;
809
55
    int remove_dunder_class = 0;
810
55
    int remove_dunder_classdict = 0;
811
55
    int remove_dunder_cond_annotations = 0;
812
813
226
    while (PyDict_Next(comp->ste_symbols, &pos, &k, &v)) {
814
        // skip comprehension parameter
815
171
        long comp_flags = PyLong_AsLong(v);
816
171
        if (comp_flags == -1 && PyErr_Occurred()) {
817
0
            return 0;
818
0
        }
819
171
        if (comp_flags & DEF_PARAM) {
820
55
            assert(_PyUnicode_EqualToASCIIString(k, ".0"));
821
55
            continue;
822
55
        }
823
116
        int scope = SYMBOL_TO_SCOPE(comp_flags);
824
116
        int only_flags = comp_flags & ((1 << SCOPE_OFFSET) - 1);
825
116
        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
116
        PyObject *existing = PyDict_GetItemWithError(ste->ste_symbols, k);
831
116
        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
116
        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
116
        if (!existing) {
857
            // name does not exist in scope, copy from comprehension
858
68
            assert(scope != FREE || PySet_Contains(comp_free, k) == 1);
859
68
            PyObject *v_flags = PyLong_FromLong(only_flags);
860
68
            if (v_flags == NULL) {
861
0
                return 0;
862
0
            }
863
68
            int ok = PyDict_SetItem(ste->ste_symbols, k, v_flags);
864
68
            Py_DECREF(v_flags);
865
68
            if (ok < 0) {
866
0
                return 0;
867
0
            }
868
68
            SET_SCOPE(scopes, k, scope);
869
68
        }
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
116
    }
891
55
    if (remove_dunder_class && PyDict_DelItemString(comp->ste_symbols, "__class__") < 0) {
892
0
        return 0;
893
0
    }
894
55
    if (remove_dunder_classdict && PyDict_DelItemString(comp->ste_symbols, "__classdict__") < 0) {
895
0
        return 0;
896
0
    }
897
55
    if (remove_dunder_cond_annotations && PyDict_DelItemString(comp->ste_symbols, "__conditional_annotations__") < 0) {
898
0
        return 0;
899
0
    }
900
55
    return 1;
901
55
}
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.77k
{
916
7.77k
    PyObject *name, *v, *v_cell;
917
7.77k
    int success = 0;
918
7.77k
    Py_ssize_t pos = 0;
919
920
7.77k
    v_cell = PyLong_FromLong(CELL);
921
7.77k
    if (!v_cell)
922
0
        return 0;
923
35.7k
    while (PyDict_Next(scopes, &pos, &name, &v)) {
924
28.0k
        long scope = PyLong_AsLong(v);
925
28.0k
        if (scope == -1 && PyErr_Occurred()) {
926
0
            goto error;
927
0
        }
928
28.0k
        if (scope != LOCAL)
929
9.38k
            continue;
930
18.6k
        int contains = PySet_Contains(free, name);
931
18.6k
        if (contains < 0) {
932
0
            goto error;
933
0
        }
934
18.6k
        if (!contains) {
935
17.8k
            contains = PySet_Contains(inlined_cells, name);
936
17.8k
            if (contains < 0) {
937
0
                goto error;
938
0
            }
939
17.8k
            if (!contains) {
940
17.8k
                continue;
941
17.8k
            }
942
17.8k
        }
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
783
        if (PyDict_SetItem(scopes, name, v_cell) < 0)
948
0
            goto error;
949
783
        if (PySet_Discard(free, name) < 0)
950
0
            goto error;
951
783
    }
952
7.77k
    success = 1;
953
7.77k
 error:
954
7.77k
    Py_DECREF(v_cell);
955
7.77k
    return success;
956
7.77k
}
957
958
static int
959
drop_class_free(PySTEntryObject *ste, PyObject *free)
960
755
{
961
755
    int res;
962
755
    res = PySet_Discard(free, &_Py_ID(__class__));
963
755
    if (res < 0)
964
0
        return 0;
965
755
    if (res)
966
36
        ste->ste_needs_class_closure = 1;
967
755
    res = PySet_Discard(free, &_Py_ID(__classdict__));
968
755
    if (res < 0)
969
0
        return 0;
970
755
    if (res)
971
416
        ste->ste_needs_classdict = 1;
972
755
    res = PySet_Discard(free, &_Py_ID(__conditional_annotations__));
973
755
    if (res < 0)
974
0
        return 0;
975
755
    if (res) {
976
0
        ste->ste_has_conditional_annotations = 1;
977
0
    }
978
755
    return 1;
979
755
}
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
9.38k
{
990
9.38k
    PyObject *name = NULL, *itr = NULL;
991
9.38k
    PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
992
9.38k
    Py_ssize_t pos = 0;
993
994
    /* Update scope information for all symbols in this scope */
995
42.8k
    while (PyDict_Next(symbols, &pos, &name, &v)) {
996
33.4k
        long flags = PyLong_AsLong(v);
997
33.4k
        if (flags == -1 && PyErr_Occurred()) {
998
0
            return 0;
999
0
        }
1000
33.4k
        int contains = PySet_Contains(inlined_cells, name);
1001
33.4k
        if (contains < 0) {
1002
0
            return 0;
1003
0
        }
1004
33.4k
        if (contains) {
1005
0
            flags |= DEF_COMP_CELL;
1006
0
        }
1007
33.4k
        if (PyDict_GetItemRef(scopes, name, &v_scope) < 0) {
1008
0
            return 0;
1009
0
        }
1010
33.4k
        if (!v_scope) {
1011
0
            PyErr_SetObject(PyExc_KeyError, name);
1012
0
            return 0;
1013
0
        }
1014
33.4k
        long scope = PyLong_AsLong(v_scope);
1015
33.4k
        Py_DECREF(v_scope);
1016
33.4k
        if (scope == -1 && PyErr_Occurred()) {
1017
0
            return 0;
1018
0
        }
1019
33.4k
        flags |= (scope << SCOPE_OFFSET);
1020
33.4k
        v_new = PyLong_FromLong(flags);
1021
33.4k
        if (!v_new)
1022
0
            return 0;
1023
33.4k
        if (PyDict_SetItem(symbols, name, v_new) < 0) {
1024
0
            Py_DECREF(v_new);
1025
0
            return 0;
1026
0
        }
1027
33.4k
        Py_DECREF(v_new);
1028
33.4k
    }
1029
1030
    /* Record not yet resolved free variables from children (if any) */
1031
9.38k
    v_free = PyLong_FromLong(FREE << SCOPE_OFFSET);
1032
9.38k
    if (!v_free)
1033
0
        return 0;
1034
1035
9.38k
    itr = PyObject_GetIter(free);
1036
9.38k
    if (itr == NULL) {
1037
0
        Py_DECREF(v_free);
1038
0
        return 0;
1039
0
    }
1040
1041
9.39k
    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
9.38k
    if (PyErr_Occurred()) {
1093
0
        goto error;
1094
0
    }
1095
1096
9.38k
    Py_DECREF(itr);
1097
9.38k
    Py_DECREF(v_free);
1098
9.38k
    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
9.38k
}
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
9.38k
{
1136
9.38k
    PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
1137
9.38k
    PyObject *newglobal = NULL, *newfree = NULL, *inlined_cells = NULL;
1138
9.38k
    PyObject *temp;
1139
9.38k
    int success = 0;
1140
9.38k
    Py_ssize_t i, pos = 0;
1141
1142
9.38k
    local = PySet_New(NULL);  /* collect new names bound in block */
1143
9.38k
    if (!local)
1144
0
        goto error;
1145
9.38k
    scopes = PyDict_New();  /* collect scopes defined for each name */
1146
9.38k
    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
9.38k
    newglobal = PySet_New(NULL);
1161
9.38k
    if (!newglobal)
1162
0
        goto error;
1163
9.38k
    newfree = PySet_New(NULL);
1164
9.38k
    if (!newfree)
1165
0
        goto error;
1166
9.38k
    newbound = PySet_New(NULL);
1167
9.38k
    if (!newbound)
1168
0
        goto error;
1169
9.38k
    inlined_cells = PySet_New(NULL);
1170
9.38k
    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
9.38k
    if (ste->ste_type == ClassBlock) {
1179
        /* Pass down known globals */
1180
755
        temp = PyNumber_InPlaceOr(newglobal, global);
1181
755
        if (!temp)
1182
0
            goto error;
1183
755
        Py_DECREF(temp);
1184
        /* Pass down previously bound symbols */
1185
755
        if (bound) {
1186
755
            temp = PyNumber_InPlaceOr(newbound, bound);
1187
755
            if (!temp)
1188
0
                goto error;
1189
755
            Py_DECREF(temp);
1190
755
        }
1191
755
    }
1192
1193
42.7k
    while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
1194
33.3k
        long flags = PyLong_AsLong(v);
1195
33.3k
        if (flags == -1 && PyErr_Occurred()) {
1196
0
            goto error;
1197
0
        }
1198
33.3k
        if (!analyze_name(ste, scopes, name, flags,
1199
33.3k
                          bound, local, free, global, type_params, class_entry))
1200
0
            goto error;
1201
33.3k
    }
1202
1203
    /* Populate global and bound sets to be passed to children. */
1204
9.38k
    if (ste->ste_type != ClassBlock) {
1205
        /* Add function locals to bound set */
1206
8.63k
        if (_PyST_IsFunctionLike(ste)) {
1207
7.77k
            temp = PyNumber_InPlaceOr(newbound, local);
1208
7.77k
            if (!temp)
1209
0
                goto error;
1210
7.77k
            Py_DECREF(temp);
1211
7.77k
        }
1212
        /* Pass down previously bound symbols */
1213
8.63k
        if (bound) {
1214
7.77k
            temp = PyNumber_InPlaceOr(newbound, bound);
1215
7.77k
            if (!temp)
1216
0
                goto error;
1217
7.77k
            Py_DECREF(temp);
1218
7.77k
        }
1219
        /* Pass down known globals */
1220
8.63k
        temp = PyNumber_InPlaceOr(newglobal, global);
1221
8.63k
        if (!temp)
1222
0
            goto error;
1223
8.63k
        Py_DECREF(temp);
1224
8.63k
    }
1225
755
    else {
1226
        /* Special-case __class__ and __classdict__ */
1227
755
        if (PySet_Add(newbound, &_Py_ID(__class__)) < 0)
1228
0
            goto error;
1229
755
        if (PySet_Add(newbound, &_Py_ID(__classdict__)) < 0)
1230
0
            goto error;
1231
755
        if (PySet_Add(newbound, &_Py_ID(__conditional_annotations__)) < 0)
1232
0
            goto error;
1233
755
    }
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.9k
    for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
1242
8.53k
        PyObject *child_free = NULL;
1243
8.53k
        PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
1244
8.53k
        PySTEntryObject* entry;
1245
8.53k
        assert(c && PySTEntry_Check(c));
1246
8.53k
        entry = (PySTEntryObject*)c;
1247
1248
8.53k
        PySTEntryObject *new_class_entry = NULL;
1249
8.53k
        if (entry->ste_can_see_class_scope) {
1250
1.83k
            if (ste->ste_type == ClassBlock) {
1251
1.83k
                new_class_entry = ste;
1252
1.83k
            }
1253
0
            else if (class_entry) {
1254
0
                new_class_entry = class_entry;
1255
0
            }
1256
1.83k
        }
1257
1258
        // we inline all non-generator-expression comprehensions,
1259
        // except those in annotation scopes that are nested in classes
1260
8.53k
        int inline_comp =
1261
8.53k
            entry->ste_comprehension &&
1262
95
            !entry->ste_generator &&
1263
55
            !ste->ste_can_see_class_scope;
1264
1265
8.53k
        if (!analyze_child_block(entry, newbound, newfree, newglobal,
1266
8.53k
                                 type_params, new_class_entry, &child_free))
1267
0
        {
1268
0
            goto error;
1269
0
        }
1270
8.53k
        if (inline_comp) {
1271
55
            if (!inline_comprehension(ste, entry, scopes, child_free, inlined_cells)) {
1272
0
                Py_DECREF(child_free);
1273
0
                goto error;
1274
0
            }
1275
55
            entry->ste_comp_inlined = 1;
1276
55
        }
1277
8.53k
        temp = PyNumber_InPlaceOr(newfree, child_free);
1278
8.53k
        Py_DECREF(child_free);
1279
8.53k
        if (!temp)
1280
0
            goto error;
1281
8.53k
        Py_DECREF(temp);
1282
8.53k
    }
1283
1284
    /* Splice children of inlined comprehensions into our children list */
1285
17.9k
    for (i = PyList_GET_SIZE(ste->ste_children) - 1; i >= 0; --i) {
1286
8.53k
        PyObject* c = PyList_GET_ITEM(ste->ste_children, i);
1287
8.53k
        PySTEntryObject* entry;
1288
8.53k
        assert(c && PySTEntry_Check(c));
1289
8.53k
        entry = (PySTEntryObject*)c;
1290
8.53k
        if (entry->ste_comp_inlined &&
1291
55
            PyList_SetSlice(ste->ste_children, i, i + 1,
1292
55
                            entry->ste_children) < 0)
1293
0
        {
1294
0
            goto error;
1295
0
        }
1296
8.53k
    }
1297
1298
    /* Check if any local variables must be converted to cell variables */
1299
9.38k
    if (_PyST_IsFunctionLike(ste) && !analyze_cells(scopes, newfree, inlined_cells))
1300
0
        goto error;
1301
9.38k
    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
9.38k
    if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, inlined_cells,
1305
9.38k
                        (ste->ste_type == ClassBlock) || ste->ste_can_see_class_scope))
1306
0
        goto error;
1307
1308
9.38k
    temp = PyNumber_InPlaceOr(free, newfree);
1309
9.38k
    if (!temp)
1310
0
        goto error;
1311
9.38k
    Py_DECREF(temp);
1312
9.38k
    success = 1;
1313
9.38k
 error:
1314
9.38k
    Py_XDECREF(scopes);
1315
9.38k
    Py_XDECREF(local);
1316
9.38k
    Py_XDECREF(newbound);
1317
9.38k
    Py_XDECREF(newglobal);
1318
9.38k
    Py_XDECREF(newfree);
1319
9.38k
    Py_XDECREF(inlined_cells);
1320
9.38k
    if (!success)
1321
9.38k
        assert(PyErr_Occurred());
1322
9.38k
    return success;
1323
9.38k
}
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.53k
{
1330
8.53k
    PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
1331
8.53k
    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.53k
    temp_bound = PySet_New(bound);
1341
8.53k
    if (!temp_bound)
1342
0
        goto error;
1343
8.53k
    temp_free = PySet_New(free);
1344
8.53k
    if (!temp_free)
1345
0
        goto error;
1346
8.53k
    temp_global = PySet_New(global);
1347
8.53k
    if (!temp_global)
1348
0
        goto error;
1349
8.53k
    temp_type_params = PySet_New(type_params);
1350
8.53k
    if (!temp_type_params)
1351
0
        goto error;
1352
1353
8.53k
    if (!analyze_block(entry, temp_bound, temp_free, temp_global,
1354
8.53k
                       temp_type_params, class_entry))
1355
0
        goto error;
1356
8.53k
    *child_free = temp_free;
1357
8.53k
    Py_DECREF(temp_bound);
1358
8.53k
    Py_DECREF(temp_global);
1359
8.53k
    Py_DECREF(temp_type_params);
1360
8.53k
    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.53k
}
1368
1369
static int
1370
symtable_analyze(struct symtable *st)
1371
859
{
1372
859
    PyObject *free, *global, *type_params;
1373
859
    int r;
1374
1375
859
    free = PySet_New(NULL);
1376
859
    if (!free)
1377
0
        return 0;
1378
859
    global = PySet_New(NULL);
1379
859
    if (!global) {
1380
0
        Py_DECREF(free);
1381
0
        return 0;
1382
0
    }
1383
859
    type_params = PySet_New(NULL);
1384
859
    if (!type_params) {
1385
0
        Py_DECREF(free);
1386
0
        Py_DECREF(global);
1387
0
        return 0;
1388
0
    }
1389
859
    r = analyze_block(st->st_top, NULL, free, global, type_params, NULL);
1390
859
    Py_DECREF(free);
1391
859
    Py_DECREF(global);
1392
859
    Py_DECREF(type_params);
1393
859
    return r;
1394
859
}
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
9.39k
{
1404
9.39k
    Py_ssize_t size;
1405
1406
9.39k
    st->st_cur = NULL;
1407
9.39k
    size = PyList_GET_SIZE(st->st_stack);
1408
9.39k
    if (size) {
1409
9.39k
        if (PyList_SetSlice(st->st_stack, size - 1, size, NULL) < 0)
1410
0
            return 0;
1411
9.39k
        if (--size)
1412
8.53k
            st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, size - 1);
1413
9.39k
    }
1414
9.39k
    return 1;
1415
9.39k
}
1416
1417
static int
1418
symtable_enter_existing_block(struct symtable *st, PySTEntryObject* ste, bool add_to_children)
1419
9.39k
{
1420
9.39k
    if (PyList_Append(st->st_stack, (PyObject *)ste) < 0) {
1421
0
        return 0;
1422
0
    }
1423
9.39k
    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
9.39k
    if (prev) {
1429
8.53k
        ste->ste_comp_iter_expr = prev->ste_comp_iter_expr;
1430
8.53k
    }
1431
    /* No need to inherit ste_mangled_names in classes, where all names
1432
     * are mangled. */
1433
9.39k
    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
9.39k
    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
9.39k
    if (st->st_future->ff_features & CO_FUTURE_ANNOTATIONS && ste->ste_type == AnnotationBlock) {
1443
0
        return 1;
1444
0
    }
1445
1446
9.39k
    if (ste->ste_type == ModuleBlock)
1447
859
        st->st_global = st->st_cur->ste_symbols;
1448
1449
9.39k
    if (add_to_children && prev) {
1450
8.53k
        if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) {
1451
0
            return 0;
1452
0
        }
1453
8.53k
    }
1454
9.39k
    return 1;
1455
9.39k
}
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.68k
{
1461
5.68k
    PySTEntryObject *ste = ste_new(st, name, block, ast, loc);
1462
5.68k
    if (ste == NULL)
1463
0
        return 0;
1464
5.68k
    int result = symtable_enter_existing_block(st, ste, /* add_to_children */true);
1465
5.68k
    Py_DECREF(ste);
1466
5.68k
    if (block == AnnotationBlock || block == TypeVariableBlock || block == TypeAliasBlock) {
1467
3.71k
        _Py_DECLARE_STR(format, ".format");
1468
        // We need to insert code that reads this "parameter" to the function.
1469
3.71k
        if (!symtable_add_def(st, &_Py_STR(format), DEF_PARAM, loc)) {
1470
0
            return 0;
1471
0
        }
1472
3.71k
        if (!symtable_add_def(st, &_Py_STR(format), USE, loc)) {
1473
0
            return 0;
1474
0
        }
1475
3.71k
    }
1476
5.68k
    return result;
1477
5.68k
}
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
73.3k
{
1503
73.3k
    PyObject *o;
1504
73.3k
    PyObject *dict;
1505
73.3k
    long val;
1506
73.3k
    PyObject *mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1507
1508
73.3k
    if (!mangled)
1509
0
        return 0;
1510
73.3k
    dict = ste->ste_symbols;
1511
73.3k
    if ((o = PyDict_GetItemWithError(dict, mangled))) {
1512
39.9k
        val = PyLong_AsLong(o);
1513
39.9k
        if (val == -1 && PyErr_Occurred()) {
1514
0
            goto error;
1515
0
        }
1516
39.9k
        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
39.9k
        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
39.9k
        val |= flag;
1528
39.9k
    }
1529
33.3k
    else if (PyErr_Occurred()) {
1530
0
        goto error;
1531
0
    }
1532
33.3k
    else {
1533
33.3k
        val = flag;
1534
33.3k
    }
1535
73.3k
    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
121
        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
121
        val |= DEF_COMP_ITER;
1548
121
    }
1549
73.3k
    o = PyLong_FromLong(val);
1550
73.3k
    if (o == NULL)
1551
0
        goto error;
1552
73.3k
    if (PyDict_SetItem(dict, mangled, o) < 0) {
1553
0
        Py_DECREF(o);
1554
0
        goto error;
1555
0
    }
1556
73.3k
    Py_DECREF(o);
1557
1558
73.3k
    if (flag & DEF_PARAM) {
1559
15.0k
        if (PyList_Append(ste->ste_varnames, mangled) < 0)
1560
0
            goto error;
1561
58.2k
    } 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
73.3k
    Py_DECREF(mangled);
1585
73.3k
    return 1;
1586
1587
0
error:
1588
0
    Py_DECREF(mangled);
1589
0
    return 0;
1590
73.3k
}
1591
1592
static int
1593
check_name(struct symtable *st, PyObject *name, _Py_SourceLocation loc,
1594
           expr_context_ty ctx)
1595
45.6k
{
1596
45.6k
    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
45.6k
    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
45.6k
    return 1;
1607
45.6k
}
1608
1609
static int
1610
check_keywords(struct symtable *st, asdl_keyword_seq *keywords)
1611
11.6k
{
1612
13.4k
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(keywords); i++) {
1613
1.87k
        keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
1614
1.87k
        if (key->arg  && !check_name(st, key->arg, LOCATION(key), Store)) {
1615
0
            return 0;
1616
0
        }
1617
1.87k
    }
1618
11.6k
    return 1;
1619
11.6k
}
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
73.3k
{
1640
73.3k
    int write_mask = DEF_PARAM | DEF_LOCAL | DEF_IMPORT;
1641
73.3k
    if ((flag & write_mask) && !check_name(st, name, loc, ctx)) {
1642
0
        return 0;
1643
0
    }
1644
73.3k
    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
73.3k
    return symtable_add_def_helper(st, name, flag, st->st_cur, loc);
1650
73.3k
}
1651
1652
static int
1653
symtable_add_def(struct symtable *st, PyObject *name, int flag,
1654
                 _Py_SourceLocation loc)
1655
26.4k
{
1656
26.4k
    return symtable_add_def_ctx(st, name, flag, loc,
1657
26.4k
                                flag == USE ? Load : Store);
1658
26.4k
}
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
65.3k
    do { \
1725
65.3k
        if (!symtable_visit_ ## TYPE((ST), (V))) { \
1726
0
            return 0; \
1727
0
        } \
1728
65.3k
    } while(0)
1729
1730
#define VISIT_SEQ(ST, TYPE, SEQ) \
1731
40.9k
    do { \
1732
40.9k
        Py_ssize_t i; \
1733
40.9k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1734
110k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1735
69.3k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1736
69.3k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1737
69.3k
                return 0;                 \
1738
69.3k
        } \
1739
40.9k
    } while(0)
1740
1741
#define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) \
1742
95
    do { \
1743
95
        Py_ssize_t i; \
1744
95
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1745
96
        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
95
    } while(0)
1751
1752
#define VISIT_SEQ_WITH_NULL(ST, TYPE, SEQ) \
1753
14.9k
    do { \
1754
14.9k
        int i = 0; \
1755
14.9k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1756
25.2k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1757
10.2k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1758
10.2k
            if (!elt) continue; /* can be NULL */ \
1759
10.2k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1760
10.2k
                return 0;             \
1761
10.2k
        } \
1762
14.9k
    } while(0)
1763
1764
#define ENTER_CONDITIONAL_BLOCK(ST) \
1765
4.14k
    int in_conditional_block = (ST)->st_cur->ste_in_conditional_block; \
1766
4.14k
    (ST)->st_cur->ste_in_conditional_block = 1;
1767
1768
#define LEAVE_CONDITIONAL_BLOCK(ST) \
1769
4.14k
    (ST)->st_cur->ste_in_conditional_block = in_conditional_block;
1770
1771
#define ENTER_TRY_BLOCK(ST) \
1772
397
    int in_try_block = (ST)->st_cur->ste_in_try_block; \
1773
397
    (ST)->st_cur->ste_in_try_block = 1;
1774
1775
#define LEAVE_TRY_BLOCK(ST) \
1776
397
    (ST)->st_cur->ste_in_try_block = in_try_block;
1777
1778
140k
#define ENTER_RECURSIVE() \
1779
140k
if (Py_EnterRecursiveCall(" during compilation")) { \
1780
0
    return 0; \
1781
0
}
1782
1783
140k
#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
385
{
1823
385
    assert(s->kind == ImportFrom_kind);
1824
385
    _Py_SourceLocation fut = st->st_future->ff_location;
1825
385
    if (s->v.ImportFrom.module && s->v.ImportFrom.level == 0 &&
1826
240
        _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
385
    return 1;
1837
385
}
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.9k
{
1890
23.9k
    ENTER_RECURSIVE();
1891
23.9k
    switch (s->kind) {
1892
3.56k
    case FunctionDef_kind: {
1893
3.56k
        if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL, LOCATION(s)))
1894
0
            return 0;
1895
3.56k
        if (s->v.FunctionDef.args->defaults)
1896
3.56k
            VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
1897
3.56k
        if (s->v.FunctionDef.args->kw_defaults)
1898
3.56k
            VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults);
1899
3.56k
        if (s->v.FunctionDef.decorator_list)
1900
212
            VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
1901
3.56k
        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.56k
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
1915
3.56k
                                           LOCATION(s));
1916
3.56k
        if (!new_ste) {
1917
0
            return 0;
1918
0
        }
1919
1920
3.56k
        if (_PyAST_GetDocString(s->v.FunctionDef.body)) {
1921
517
            new_ste->ste_has_docstring = 1;
1922
517
        }
1923
1924
3.56k
        if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args,
1925
3.56k
                                        s->v.FunctionDef.returns, new_ste)) {
1926
0
            Py_DECREF(new_ste);
1927
0
            return 0;
1928
0
        }
1929
3.56k
        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.56k
        Py_DECREF(new_ste);
1934
3.56k
        VISIT(st, arguments, s->v.FunctionDef.args);
1935
3.56k
        VISIT_SEQ(st, stmt, s->v.FunctionDef.body);
1936
3.56k
        if (!symtable_exit_block(st))
1937
0
            return 0;
1938
3.56k
        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.56k
        break;
1943
3.56k
    }
1944
3.56k
    case ClassDef_kind: {
1945
755
        PyObject *tmp;
1946
755
        if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL, LOCATION(s)))
1947
0
            return 0;
1948
755
        if (s->v.ClassDef.decorator_list)
1949
3
            VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
1950
755
        tmp = st->st_private;
1951
755
        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
755
        VISIT_SEQ(st, expr, s->v.ClassDef.bases);
1966
755
        if (!check_keywords(st, s->v.ClassDef.keywords)) {
1967
0
            return 0;
1968
0
        }
1969
755
        VISIT_SEQ(st, keyword, s->v.ClassDef.keywords);
1970
755
        if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
1971
755
                                  (void *)s, LOCATION(s))) {
1972
0
            return 0;
1973
0
        }
1974
755
        st->st_private = s->v.ClassDef.name;
1975
755
        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
755
        if (_PyAST_GetDocString(s->v.ClassDef.body)) {
1988
116
            st->st_cur->ste_has_docstring = 1;
1989
116
        }
1990
1991
755
        VISIT_SEQ(st, stmt, s->v.ClassDef.body);
1992
755
        if (!symtable_exit_block(st))
1993
0
            return 0;
1994
755
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
1995
0
            if (!symtable_exit_block(st))
1996
0
                return 0;
1997
0
        }
1998
755
        st->st_private = tmp;
1999
755
        break;
2000
755
    }
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
3.06k
    case Return_kind:
2035
3.06k
        if (s->v.Return.value) {
2036
2.80k
            VISIT(st, expr, s->v.Return.value);
2037
2.80k
            st->st_cur->ste_returns_value = 1;
2038
2.80k
        }
2039
3.06k
        break;
2040
3.06k
    case Delete_kind:
2041
50
        VISIT_SEQ(st, expr, s->v.Delete.targets);
2042
50
        break;
2043
4.95k
    case Assign_kind:
2044
4.95k
        VISIT_SEQ(st, expr, s->v.Assign.targets);
2045
4.95k
        VISIT(st, expr, s->v.Assign.value);
2046
4.95k
        break;
2047
4.95k
    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
193
    case AugAssign_kind: {
2089
193
        VISIT(st, expr, s->v.AugAssign.target);
2090
193
        VISIT(st, expr, s->v.AugAssign.value);
2091
193
        break;
2092
193
    }
2093
311
    case For_kind: {
2094
311
        VISIT(st, expr, s->v.For.target);
2095
311
        VISIT(st, expr, s->v.For.iter);
2096
311
        ENTER_CONDITIONAL_BLOCK(st);
2097
311
        VISIT_SEQ(st, stmt, s->v.For.body);
2098
311
        if (s->v.For.orelse)
2099
4
            VISIT_SEQ(st, stmt, s->v.For.orelse);
2100
311
        LEAVE_CONDITIONAL_BLOCK(st);
2101
311
        break;
2102
311
    }
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.22k
    case If_kind: {
2113
        /* XXX if 0: and lookup_yield() hacks */
2114
3.22k
        VISIT(st, expr, s->v.If.test);
2115
3.22k
        ENTER_CONDITIONAL_BLOCK(st);
2116
3.22k
        VISIT_SEQ(st, stmt, s->v.If.body);
2117
3.22k
        if (s->v.If.orelse)
2118
715
            VISIT_SEQ(st, stmt, s->v.If.orelse);
2119
3.22k
        LEAVE_CONDITIONAL_BLOCK(st);
2120
3.22k
        break;
2121
3.22k
    }
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
893
    case Raise_kind:
2130
893
        if (s->v.Raise.exc) {
2131
794
            VISIT(st, expr, s->v.Raise.exc);
2132
794
            if (s->v.Raise.cause) {
2133
27
                VISIT(st, expr, s->v.Raise.cause);
2134
27
            }
2135
794
        }
2136
893
        break;
2137
893
    case Try_kind: {
2138
397
        ENTER_CONDITIONAL_BLOCK(st);
2139
397
        ENTER_TRY_BLOCK(st);
2140
397
        VISIT_SEQ(st, stmt, s->v.Try.body);
2141
397
        VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
2142
397
        VISIT_SEQ(st, stmt, s->v.Try.orelse);
2143
397
        VISIT_SEQ(st, stmt, s->v.Try.finalbody);
2144
397
        LEAVE_TRY_BLOCK(st);
2145
397
        LEAVE_CONDITIONAL_BLOCK(st);
2146
397
        break;
2147
397
    }
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
490
    case Import_kind:
2165
490
        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
490
        VISIT_SEQ(st, alias, s->v.Import.names);
2171
490
        break;
2172
490
    case ImportFrom_kind:
2173
385
        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
385
        VISIT_SEQ(st, alias, s->v.ImportFrom.names);
2193
385
        if (!check_import_from(st, s)) {
2194
0
            return 0;
2195
0
        }
2196
385
        break;
2197
385
    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.89k
    case Expr_kind:
2262
4.89k
        VISIT(st, expr, s->v.Expr.value);
2263
4.89k
        break;
2264
4.89k
    case Pass_kind:
2265
299
    case Break_kind:
2266
348
    case Continue_kind:
2267
        /* nothing to do here */
2268
348
        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.9k
    }
2357
23.9k
    LEAVE_RECURSIVE();
2358
23.9k
    return 1;
2359
23.9k
}
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
116k
{
2480
116k
    ENTER_RECURSIVE();
2481
116k
    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
821
    case BoolOp_kind:
2490
821
        VISIT_SEQ(st, expr, e->v.BoolOp.values);
2491
821
        break;
2492
821
    case BinOp_kind:
2493
699
        VISIT(st, expr, e->v.BinOp.left);
2494
699
        VISIT(st, expr, e->v.BinOp.right);
2495
699
        break;
2496
699
    case UnaryOp_kind:
2497
589
        VISIT(st, expr, e->v.UnaryOp.operand);
2498
589
        break;
2499
589
    case Lambda_kind: {
2500
270
        if (e->v.Lambda.args->defaults)
2501
270
            VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
2502
270
        if (e->v.Lambda.args->kw_defaults)
2503
270
            VISIT_SEQ_WITH_NULL(st, expr, e->v.Lambda.args->kw_defaults);
2504
270
        if (!symtable_enter_block(st, &_Py_STR(anon_lambda),
2505
270
                                  FunctionBlock, (void *)e, LOCATION(e))) {
2506
0
            return 0;
2507
0
        }
2508
270
        VISIT(st, arguments, e->v.Lambda.args);
2509
270
        VISIT(st, expr, e->v.Lambda.body);
2510
270
        if (!symtable_exit_block(st))
2511
0
            return 0;
2512
270
        break;
2513
270
    }
2514
270
    case IfExp_kind:
2515
139
        VISIT(st, expr, e->v.IfExp.test);
2516
139
        VISIT(st, expr, e->v.IfExp.body);
2517
139
        VISIT(st, expr, e->v.IfExp.orelse);
2518
139
        break;
2519
147
    case Dict_kind:
2520
147
        VISIT_SEQ_WITH_NULL(st, expr, e->v.Dict.keys);
2521
147
        VISIT_SEQ(st, expr, e->v.Dict.values);
2522
147
        break;
2523
237
    case Set_kind:
2524
237
        VISIT_SEQ(st, expr, e->v.Set.elts);
2525
237
        break;
2526
237
    case GeneratorExp_kind:
2527
40
        if (!symtable_visit_genexp(st, e))
2528
0
            return 0;
2529
40
        break;
2530
43
    case ListComp_kind:
2531
43
        if (!symtable_visit_listcomp(st, e))
2532
0
            return 0;
2533
43
        break;
2534
43
    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.74k
    case Compare_kind:
2585
3.74k
        VISIT(st, expr, e->v.Compare.left);
2586
3.74k
        VISIT_SEQ(st, expr, e->v.Compare.comparators);
2587
3.74k
        break;
2588
10.8k
    case Call_kind:
2589
10.8k
        VISIT(st, expr, e->v.Call.func);
2590
10.8k
        VISIT_SEQ(st, expr, e->v.Call.args);
2591
10.8k
        if (!check_keywords(st, e->v.Call.keywords)) {
2592
0
            return 0;
2593
0
        }
2594
10.8k
        VISIT_SEQ_WITH_NULL(st, keyword, e->v.Call.keywords);
2595
10.8k
        break;
2596
10.8k
    case FormattedValue_kind:
2597
2.19k
        VISIT(st, expr, e->v.FormattedValue.value);
2598
2.19k
        if (e->v.FormattedValue.format_spec)
2599
7
            VISIT(st, expr, e->v.FormattedValue.format_spec);
2600
2.19k
        break;
2601
2.19k
    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
788
    case JoinedStr_kind:
2607
788
        VISIT_SEQ(st, expr, e->v.JoinedStr.values);
2608
788
        break;
2609
788
    case TemplateStr_kind:
2610
0
        VISIT_SEQ(st, expr, e->v.TemplateStr.values);
2611
0
        break;
2612
27.6k
    case Constant_kind:
2613
        /* Nothing to do here. */
2614
27.6k
        break;
2615
    /* The following exprs can be assignment targets. */
2616
18.8k
    case Attribute_kind:
2617
18.8k
        if (!check_name(st, e->v.Attribute.attr, LOCATION(e), e->v.Attribute.ctx)) {
2618
0
            return 0;
2619
0
        }
2620
18.8k
        VISIT(st, expr, e->v.Attribute.value);
2621
18.8k
        break;
2622
18.8k
    case Subscript_kind:
2623
917
        VISIT(st, expr, e->v.Subscript.value);
2624
917
        VISIT(st, expr, e->v.Subscript.slice);
2625
917
        break;
2626
917
    case Starred_kind:
2627
114
        VISIT(st, expr, e->v.Starred.value);
2628
114
        break;
2629
131
    case Slice_kind:
2630
131
        if (e->v.Slice.lower)
2631
71
            VISIT(st, expr, e->v.Slice.lower);
2632
131
        if (e->v.Slice.upper)
2633
77
            VISIT(st, expr, e->v.Slice.upper);
2634
131
        if (e->v.Slice.step)
2635
0
            VISIT(st, expr, e->v.Slice.step);
2636
131
        break;
2637
46.9k
    case Name_kind:
2638
46.9k
        if (!st->st_cur->ste_in_unevaluated_annotation) {
2639
46.9k
            if (!symtable_add_def_ctx(st, e->v.Name.id,
2640
46.9k
                                    e->v.Name.ctx == Load ? USE : DEF_LOCAL,
2641
46.9k
                                    LOCATION(e), e->v.Name.ctx)) {
2642
0
                return 0;
2643
0
            }
2644
            /* Special-case super: it counts as a use of __class__ */
2645
46.9k
            if (e->v.Name.ctx == Load &&
2646
42.5k
                _PyST_IsFunctionLike(st->st_cur) &&
2647
40.3k
                _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
2648
292
                if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
2649
0
                    return 0;
2650
292
            }
2651
46.9k
        }
2652
46.9k
        break;
2653
    /* child nodes of List and Tuple will have expr_context set */
2654
46.9k
    case List_kind:
2655
220
        VISIT_SEQ(st, expr, e->v.List.elts);
2656
220
        break;
2657
1.38k
    case Tuple_kind:
2658
1.38k
        VISIT_SEQ(st, expr, e->v.Tuple.elts);
2659
1.38k
        break;
2660
116k
    }
2661
116k
    LEAVE_RECURSIVE();
2662
116k
    return 1;
2663
116k
}
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
95
{
2817
95
    PyObject *id = PyUnicode_FromFormat(".%d", pos);
2818
95
    if (id == NULL)
2819
0
        return 0;
2820
95
    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
95
    Py_DECREF(id);
2825
95
    return 1;
2826
95
}
2827
2828
static int
2829
symtable_visit_params(struct symtable *st, asdl_arg_seq *args)
2830
11.9k
{
2831
11.9k
    Py_ssize_t i;
2832
2833
22.9k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2834
11.0k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2835
11.0k
        if (!symtable_add_def(st, arg->arg, DEF_PARAM, LOCATION(arg)))
2836
0
            return 0;
2837
11.0k
    }
2838
2839
11.9k
    return 1;
2840
11.9k
}
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
11.1k
{
2898
11.1k
    Py_ssize_t i;
2899
2900
20.9k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2901
9.82k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2902
9.82k
        if (arg->annotation) {
2903
49
            st->st_cur->ste_annotations_used = 1;
2904
49
            VISIT(st, expr, arg->annotation);
2905
49
        }
2906
9.82k
    }
2907
2908
11.1k
    return 1;
2909
11.1k
}
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.70k
{
2915
3.70k
    int is_in_class = st->st_cur->ste_can_see_class_scope;
2916
3.70k
    _Py_block_ty current_type = st->st_cur->ste_type;
2917
3.70k
    if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2918
3.70k
                              (void *)a, LOCATION(o))) {
2919
0
        return 0;
2920
0
    }
2921
3.70k
    if (is_in_class || current_type == ClassBlock) {
2922
1.82k
        st->st_cur->ste_can_see_class_scope = 1;
2923
1.82k
        if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(o))) {
2924
0
            return 0;
2925
0
        }
2926
1.82k
    }
2927
3.70k
    if (a->posonlyargs && !symtable_visit_argannotations(st, a->posonlyargs))
2928
0
        return 0;
2929
3.70k
    if (a->args && !symtable_visit_argannotations(st, a->args))
2930
0
        return 0;
2931
3.70k
    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.70k
    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.70k
    if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs))
2940
0
        return 0;
2941
3.70k
    if (returns) {
2942
36
        st->st_cur->ste_annotations_used = 1;
2943
36
        VISIT(st, expr, returns);
2944
36
    }
2945
3.70k
    if (!symtable_exit_block(st)) {
2946
0
        return 0;
2947
0
    }
2948
3.70k
    return 1;
2949
3.70k
}
2950
2951
static int
2952
symtable_visit_arguments(struct symtable *st, arguments_ty a)
2953
3.97k
{
2954
    /* skip default arguments inside function block
2955
       XXX should ast be different?
2956
    */
2957
3.97k
    if (a->posonlyargs && !symtable_visit_params(st, a->posonlyargs))
2958
0
        return 0;
2959
3.97k
    if (a->args && !symtable_visit_params(st, a->args))
2960
0
        return 0;
2961
3.97k
    if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs))
2962
0
        return 0;
2963
3.97k
    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.97k
    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.97k
    return 1;
2974
3.97k
}
2975
2976
2977
static int
2978
symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
2979
440
{
2980
440
    if (eh->v.ExceptHandler.type)
2981
414
        VISIT(st, expr, eh->v.ExceptHandler.type);
2982
440
    if (eh->v.ExceptHandler.name)
2983
102
        if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL, LOCATION(eh)))
2984
0
            return 0;
2985
440
    VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
2986
440
    return 1;
2987
440
}
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
960
{
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
960
    PyObject *store_name;
3018
960
    PyObject *name = (a->asname == NULL) ? a->name : a->asname;
3019
960
    Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
3020
960
                                        PyUnicode_GET_LENGTH(name), 1);
3021
960
    if (dot != -1) {
3022
10
        store_name = PyUnicode_Substring(name, 0, dot);
3023
10
        if (!store_name)
3024
0
            return 0;
3025
10
    }
3026
950
    else {
3027
950
        store_name = Py_NewRef(name);
3028
950
    }
3029
960
    if (!_PyUnicode_EqualToASCIIString(name, "*")) {
3030
939
        int r = symtable_add_def(st, store_name, DEF_IMPORT, LOCATION(a));
3031
939
        Py_DECREF(store_name);
3032
939
        return r;
3033
939
    }
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
960
}
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.87k
{
3067
1.87k
    VISIT(st, expr, k->value);
3068
1.87k
    return 1;
3069
1.87k
}
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
95
{
3077
95
    int is_generator = (e->kind == GeneratorExp_kind);
3078
95
    comprehension_ty outermost = ((comprehension_ty)
3079
95
                                    asdl_seq_GET(generators, 0));
3080
    /* Outermost iterator is evaluated in current scope */
3081
95
    st->st_cur->ste_comp_iter_expr++;
3082
95
    VISIT(st, expr, outermost->iter);
3083
95
    st->st_cur->ste_comp_iter_expr--;
3084
    /* Create comprehension scope for the rest */
3085
95
    if (!scope_name ||
3086
95
        !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, LOCATION(e))) {
3087
0
        return 0;
3088
0
    }
3089
95
    switch(e->kind) {
3090
43
        case ListComp_kind:
3091
43
            st->st_cur->ste_comprehension = ListComprehension;
3092
43
            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
40
        default:
3100
40
            st->st_cur->ste_comprehension = GeneratorExpression;
3101
40
            break;
3102
95
    }
3103
95
    if (outermost->is_async) {
3104
0
        st->st_cur->ste_coroutine = 1;
3105
0
    }
3106
3107
    /* Outermost iter is received as an argument */
3108
95
    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
95
    st->st_cur->ste_comp_iter_target = 1;
3114
95
    VISIT(st, expr, outermost->target);
3115
95
    st->st_cur->ste_comp_iter_target = 0;
3116
    /* Visit the rest of the comprehension body */
3117
95
    VISIT_SEQ(st, expr, outermost->ifs);
3118
95
    VISIT_SEQ_TAIL(st, comprehension, generators, 1);
3119
95
    if (value)
3120
5
        VISIT(st, expr, value);
3121
95
    VISIT(st, expr, elt);
3122
95
    st->st_cur->ste_generator = is_generator;
3123
95
    int is_async = st->st_cur->ste_coroutine && !is_generator;
3124
95
    if (!symtable_exit_block(st)) {
3125
0
        return 0;
3126
0
    }
3127
95
    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
95
    if (is_async) {
3138
0
        st->st_cur->ste_coroutine = 1;
3139
0
    }
3140
95
    return 1;
3141
95
}
3142
3143
static int
3144
symtable_visit_genexp(struct symtable *st, expr_ty e)
3145
40
{
3146
40
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_genexpr),
3147
40
                                         e->v.GeneratorExp.generators,
3148
40
                                         e->v.GeneratorExp.elt, NULL);
3149
40
}
3150
3151
static int
3152
symtable_visit_listcomp(struct symtable *st, expr_ty e)
3153
43
{
3154
43
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_listcomp),
3155
43
                                         e->v.ListComp.generators,
3156
43
                                         e->v.ListComp.elt, NULL);
3157
43
}
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
153k
{
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
153k
    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
153k
    return _Py_Mangle(privateobj, name);
3272
153k
}
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
158k
{
3298
    /* Name mangling: __private becomes _classname__private.
3299
       This is independent from how the name is used. */
3300
158k
    if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
3301
76.2k
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3302
150k
        PyUnicode_READ_CHAR(ident, 1) != '_') {
3303
150k
        return Py_NewRef(ident);
3304
150k
    }
3305
7.88k
    size_t nlen = PyUnicode_GET_LENGTH(ident);
3306
7.88k
    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.88k
    if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3317
7.79k
         PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
3318
7.79k
        PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
3319
7.79k
        return Py_NewRef(ident); /* Don't mangle __whatever__ */
3320
7.79k
    }
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
}