Coverage Report

Created: 2026-10-31 06:21

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