Coverage Report

Created: 2026-10-17 06:15

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
64.3k
#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
88
#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
47.5k
{
97
47.5k
    return _PyST_IsFunctionLike(ste) || ste->ste_type == InlinedComprehensionBlock;
98
47.5k
}
99
100
static PySTEntryObject *
101
ste_new(struct symtable *st, identifier name, _Py_block_ty block,
102
        void *key, _Py_SourceLocation loc)
103
6.80k
{
104
6.80k
    PySTEntryObject *ste = NULL;
105
6.80k
    PyObject *k = NULL;
106
107
6.80k
    k = PyLong_FromVoidPtr(key);
108
6.80k
    if (k == NULL)
109
0
        goto fail;
110
6.80k
    ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
111
6.80k
    if (ste == NULL) {
112
0
        Py_DECREF(k);
113
0
        goto fail;
114
0
    }
115
6.80k
    ste->ste_table = st;
116
6.80k
    ste->ste_id = k; /* ste owns reference to k */
117
118
6.80k
    ste->ste_name = Py_NewRef(name);
119
6.80k
    ste->ste_function_name = NULL;
120
121
6.80k
    ste->ste_symbols = NULL;
122
6.80k
    ste->ste_varnames = NULL;
123
6.80k
    ste->ste_children = NULL;
124
125
6.80k
    ste->ste_directives = NULL;
126
6.80k
    ste->ste_mangled_names = NULL;
127
128
6.80k
    ste->ste_type = block;
129
6.80k
    ste->ste_scope_info = NULL;
130
131
6.80k
    ste->ste_nested = 0;
132
6.80k
    ste->ste_varargs = 0;
133
6.80k
    ste->ste_varkeywords = 0;
134
6.80k
    ste->ste_annotations_used = 0;
135
6.80k
    ste->ste_loc = loc;
136
137
6.80k
    if (st->st_cur != NULL &&
138
6.07k
        (st->st_cur->ste_nested ||
139
6.06k
         ste_uses_fast_locals(st->st_cur)))
140
1.63k
        ste->ste_nested = 1;
141
6.80k
    ste->ste_generator = 0;
142
6.80k
    ste->ste_coroutine = 0;
143
6.80k
    ste->ste_comprehension = NoComprehension;
144
6.80k
    ste->ste_returns_value = 0;
145
6.80k
    ste->ste_needs_class_closure = 0;
146
6.80k
    ste->ste_parent = (block == InlinedComprehensionBlock) ? st->st_cur : NULL;
147
6.80k
    ste->ste_comp_iter_target = 0;
148
6.80k
    ste->ste_can_see_class_scope = 0;
149
6.80k
    ste->ste_comp_iter_expr = 0;
150
6.80k
    ste->ste_needs_classdict = 0;
151
6.80k
    ste->ste_has_conditional_annotations = 0;
152
6.80k
    ste->ste_in_conditional_block = 0;
153
6.80k
    ste->ste_in_try_block = 0;
154
6.80k
    ste->ste_in_unevaluated_annotation = 0;
155
6.80k
    ste->ste_annotation_block = NULL;
156
157
6.80k
    ste->ste_has_docstring = 0;
158
159
6.80k
    ste->ste_method = 0;
160
6.80k
    if (st->st_cur != NULL &&
161
6.07k
        st->st_cur->ste_type == ClassBlock &&
162
2.21k
        block == FunctionBlock) {
163
1.09k
        ste->ste_method = 1;
164
1.09k
    }
165
166
6.80k
    ste->ste_symbols = PyDict_New();
167
6.80k
    ste->ste_varnames = PyList_New(0);
168
6.80k
    ste->ste_children = PyList_New(0);
169
6.80k
    if (ste->ste_symbols == NULL
170
6.80k
        || ste->ste_varnames == NULL
171
6.80k
        || ste->ste_children == NULL)
172
0
        goto fail;
173
174
6.80k
    if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
175
0
        goto fail;
176
177
6.80k
    return ste;
178
0
 fail:
179
0
    Py_XDECREF(ste);
180
0
    return NULL;
181
6.80k
}
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.80k
{
194
6.80k
    PySTEntryObject *ste = (PySTEntryObject *)op;
195
6.80k
    ste->ste_table = NULL;
196
6.80k
    Py_XDECREF(ste->ste_id);
197
6.80k
    Py_XDECREF(ste->ste_name);
198
6.80k
    Py_XDECREF(ste->ste_function_name);
199
6.80k
    Py_XDECREF(ste->ste_symbols);
200
6.80k
    Py_XDECREF(ste->ste_varnames);
201
6.80k
    Py_XDECREF(ste->ste_children);
202
6.80k
    Py_XDECREF(ste->ste_directives);
203
6.80k
    Py_XDECREF(ste->ste_annotation_block);
204
6.80k
    Py_XDECREF(ste->ste_mangled_names);
205
6.80k
    PyObject_Free(ste);
206
6.80k
}
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
728
{
399
728
    struct symtable *st;
400
401
728
    st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
402
728
    if (st == NULL) {
403
0
        PyErr_NoMemory();
404
0
        return NULL;
405
0
    }
406
407
728
    st->st_filename = NULL;
408
728
    st->st_blocks = NULL;
409
410
728
    if ((st->st_stack = PyList_New(0)) == NULL)
411
0
        goto fail;
412
728
    if ((st->st_blocks = PyDict_New()) == NULL)
413
0
        goto fail;
414
728
    st->st_cur = NULL;
415
728
    st->st_private = NULL;
416
728
    return st;
417
0
 fail:
418
0
    _PySymtable_Free(st);
419
0
    return NULL;
420
728
}
421
422
struct symtable *
423
_PySymtable_Build(mod_ty mod, PyObject *filename, _PyFutureFeatures *future)
424
728
{
425
728
    struct symtable *st = symtable_new();
426
728
    asdl_stmt_seq *seq;
427
728
    Py_ssize_t i;
428
728
    PyThreadState *tstate;
429
430
728
    if (st == NULL)
431
0
        return NULL;
432
728
    if (filename == NULL) {
433
0
        _PySymtable_Free(st);
434
0
        return NULL;
435
0
    }
436
728
    st->st_filename = Py_NewRef(filename);
437
728
    st->st_future = future;
438
439
    /* Setup recursion depth check counters */
440
728
    tstate = _PyThreadState_GET();
441
728
    if (!tstate) {
442
0
        _PySymtable_Free(st);
443
0
        return NULL;
444
0
    }
445
446
    /* Make the initial symbol information gathering pass */
447
448
728
    _Py_SourceLocation loc0 = {0, 0, 0, 0};
449
728
    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
728
    st->st_top = st->st_cur;
455
728
    switch (mod->kind) {
456
532
    case Module_kind:
457
532
        seq = mod->v.Module.body;
458
532
        if (_PyAST_GetDocString(seq)) {
459
105
            st->st_cur->ste_has_docstring = 1;
460
105
        }
461
3.24k
        for (i = 0; i < asdl_seq_LEN(seq); i++)
462
2.71k
            if (!symtable_visit_stmt(st,
463
2.71k
                        (stmt_ty)asdl_seq_GET(seq, i)))
464
0
                goto error;
465
532
        break;
466
532
    case Expression_kind:
467
196
        if (!symtable_visit_expr(st, mod->v.Expression.body))
468
0
            goto error;
469
196
        break;
470
196
    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
728
    }
482
728
    if (!symtable_exit_block(st)) {
483
0
        _PySymtable_Free(st);
484
0
        return NULL;
485
0
    }
486
    /* Make the second symbol analysis pass */
487
728
    if (symtable_analyze(st)) {
488
#if _PY_DUMP_SYMTABLE
489
        dump_symtable(st->st_top);
490
#endif
491
728
        return st;
492
728
    }
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
728
}
500
501
502
void
503
_PySymtable_Free(struct symtable *st)
504
728
{
505
728
    Py_XDECREF(st->st_filename);
506
728
    Py_XDECREF(st->st_blocks);
507
728
    Py_XDECREF(st->st_stack);
508
728
    PyMem_Free((void *)st);
509
728
}
510
511
PySTEntryObject *
512
_PySymtable_Lookup(struct symtable *st, void *key)
513
4.36k
{
514
4.36k
    PyObject *k, *v;
515
516
4.36k
    k = PyLong_FromVoidPtr(key);
517
4.36k
    if (k == NULL)
518
0
        return NULL;
519
4.36k
    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.36k
    Py_DECREF(k);
524
525
4.36k
    assert(v == NULL || PySTEntry_Check(v));
526
4.36k
    return (PySTEntryObject *)v;
527
4.36k
}
528
529
int
530
_PySymtable_LookupOptional(struct symtable *st, void *key,
531
                           PySTEntryObject **out)
532
2.53k
{
533
2.53k
    PyObject *k = PyLong_FromVoidPtr(key);
534
2.53k
    if (k == NULL) {
535
0
        *out = NULL;
536
0
        return -1;
537
0
    }
538
2.53k
    int result = PyDict_GetItemRef(st->st_blocks, k, (PyObject **)out);
539
2.53k
    Py_DECREF(k);
540
2.53k
    assert(*out == NULL || PySTEntry_Check(*out));
541
2.53k
    return result;
542
2.53k
}
543
544
long
545
_PyST_GetSymbol(PySTEntryObject *ste, PyObject *name)
546
48.3k
{
547
48.3k
    PyObject *v;
548
48.3k
    if (PyDict_GetItemRef(ste->ste_symbols, name, &v) < 0) {
549
0
        return -1;
550
0
    }
551
48.3k
    if (v == NULL) {
552
7.57k
        return 0;
553
7.57k
    }
554
40.8k
    long symbol = PyLong_AsLong(v);
555
40.8k
    Py_DECREF(v);
556
40.8k
    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
40.8k
    return symbol;
563
40.8k
}
564
565
int
566
_PyST_GetScope(PySTEntryObject *ste, PyObject *name)
567
43.8k
{
568
43.8k
    long symbol = _PyST_GetSymbol(ste, name);
569
43.8k
    if (symbol < 0) {
570
0
        return -1;
571
0
    }
572
43.8k
    return SYMBOL_TO_SCOPE(symbol);
573
43.8k
}
574
575
int
576
_PyST_IsFunctionLike(PySTEntryObject *ste)
577
89.4k
{
578
89.4k
    return ste->ste_type == FunctionBlock
579
22.9k
        || ste->ste_type == AnnotationBlock
580
17.1k
        || ste->ste_type == TypeVariableBlock
581
17.1k
        || ste->ste_type == TypeAliasBlock
582
17.1k
        || ste->ste_type == TypeParametersBlock;
583
89.4k
}
584
585
int
586
_PyST_IsClassClosureName(PyObject *name)
587
64
{
588
64
    return _PyUnicode_EqualToASCIIString(name, "__class__")
589
39
        || _PyUnicode_EqualToASCIIString(name, "__classdict__")
590
5
        || _PyUnicode_EqualToASCIIString(name, "__conditional_annotations__");
591
64
}
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
23.6k
    do { \
666
23.6k
        PyObject *o = PyLong_FromLong(I); \
667
23.6k
        if (!o) \
668
23.6k
            return 0; \
669
23.6k
        if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
670
0
            Py_DECREF(o); \
671
0
            return 0; \
672
0
        } \
673
23.6k
        Py_DECREF(o); \
674
23.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
23.6k
{
688
23.6k
    int contains;
689
23.6k
    if (flags & DEF_GLOBAL) {
690
13
        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
13
        SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
697
13
        if (PySet_Add(global, name) < 0)
698
0
            return 0;
699
13
        if (bound && (PySet_Discard(bound, name) < 0))
700
0
            return 0;
701
13
        return 1;
702
13
    }
703
23.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
23.6k
    if (flags & DEF_BOUND) {
734
17.0k
        SET_SCOPE(scopes, name, LOCAL);
735
17.0k
        if (PySet_Add(local, name) < 0)
736
0
            return 0;
737
17.0k
        if (PySet_Discard(global, name) < 0)
738
0
            return 0;
739
17.0k
        if (flags & DEF_TYPE_PARAM) {
740
0
            if (PySet_Add(type_params, name) < 0)
741
0
                return 0;
742
0
        }
743
17.0k
        else {
744
17.0k
            if (PySet_Discard(type_params, name) < 0)
745
0
                return 0;
746
17.0k
        }
747
17.0k
        return 1;
748
17.0k
    }
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
6.63k
    if (class_entry != NULL) {
757
1.20k
        long class_flags = _PyST_GetSymbol(class_entry, name);
758
1.20k
        if (class_flags < 0) {
759
0
            return 0;
760
0
        }
761
1.20k
        if (class_flags & DEF_GLOBAL) {
762
0
            SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
763
0
            return 1;
764
0
        }
765
1.20k
        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.20k
    }
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
6.63k
    if (bound) {
776
6.54k
        contains = PySet_Contains(bound, name);
777
6.54k
        if (contains < 0) {
778
0
            return 0;
779
0
        }
780
6.54k
        if (contains) {
781
1.86k
            SET_SCOPE(scopes, name, FREE);
782
1.86k
            return PySet_Add(free, name) >= 0;
783
1.86k
        }
784
6.54k
    }
785
    /* If a parent has a global statement, then call it global
786
       explicit?  It could also be global implicit.
787
     */
788
4.76k
    if (global) {
789
4.76k
        contains = PySet_Contains(global, name);
790
4.76k
        if (contains < 0) {
791
0
            return 0;
792
0
        }
793
4.76k
        if (contains) {
794
3
            SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
795
3
            return 1;
796
3
        }
797
4.76k
    }
798
4.76k
    SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
799
4.76k
    return 1;
800
4.76k
}
801
802
/* See InternalDocs/inlined_comprehensions.md. */
803
804
static int
805
is_free_in_any_child(PySTEntryObject *entry, PyObject *key)
806
34
{
807
34
    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
34
    return 0;
827
34
}
828
829
static int
830
symtable_add_flag(PyObject *dict, PyObject *name, int flag)
831
50.6k
{
832
50.6k
    PyObject *o = PyDict_GetItemWithError(dict, name);
833
50.6k
    long val;
834
50.6k
    if (o != NULL) {
835
26.9k
        val = PyLong_AsLong(o);
836
26.9k
        if (val == -1 && PyErr_Occurred()) {
837
0
            return 0;
838
0
        }
839
26.9k
        val |= flag;
840
26.9k
    }
841
23.6k
    else if (PyErr_Occurred()) {
842
0
        return 0;
843
0
    }
844
23.6k
    else {
845
23.6k
        val = flag;
846
23.6k
    }
847
50.6k
    o = PyLong_FromLong(val);
848
50.6k
    if (o == NULL) {
849
0
        return 0;
850
0
    }
851
50.6k
    int rc = PyDict_SetItem(dict, name, o);
852
50.6k
    Py_DECREF(o);
853
50.6k
    return rc >= 0;
854
50.6k
}
855
856
static int
857
finalize_inlined_comprehension(PySTEntryObject *ste, PySTEntryObject *comp,
858
                                PyObject *comp_free, PyObject *outer_newfree,
859
                                PyObject *inlined_cells)
860
53
{
861
53
    PyObject *k, *v;
862
53
    Py_ssize_t pos = 0;
863
864
53
    assert(comp->ste_type == InlinedComprehensionBlock);
865
53
    assert(comp->ste_parent != NULL);
866
867
165
    while (PyDict_Next(comp->ste_symbols, &pos, &k, &v)) {
868
112
        long comp_flags = PyLong_AsLong(v);
869
112
        if (comp_flags == -1 && PyErr_Occurred()) {
870
0
            goto error;
871
0
        }
872
112
        int scope = SYMBOL_TO_SCOPE(comp_flags);
873
112
        if (scope == CELL) {
874
0
            if (PySet_Add(inlined_cells, k) < 0) {
875
0
                goto error;
876
0
            }
877
0
        }
878
112
        PyObject *existing = PyDict_GetItemWithError(ste->ste_symbols, k);
879
112
        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
112
        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
112
        int is_def_bound = 0;
899
112
        if (existing) {
900
38
            long flags = PyLong_AsLong(existing);
901
38
            if (flags == -1 && PyErr_Occurred()) {
902
0
                goto error;
903
0
            }
904
38
            is_def_bound = flags & DEF_BOUND;
905
38
        }
906
        // Loads here are in the enclosing compilation unit.
907
112
        if (scope == FREE && (comp_flags & USE) &&
908
27
                !symtable_add_flag(ste->ste_symbols, k, USE)) {
909
0
            goto error;
910
0
        }
911
112
        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
34
            int ok = is_free_in_any_child(comp, k);
917
34
            if (ok < 0) {
918
0
                goto error;
919
0
            }
920
34
            if (!ok) {
921
34
                int in_newfree = PySet_Contains(outer_newfree, k);
922
34
                if (in_newfree < 0) {
923
0
                    goto error;
924
0
                }
925
34
                if (!in_newfree) {
926
34
                    if (PySet_Discard(comp_free, k) < 0) {
927
0
                        goto error;
928
0
                    }
929
34
                }
930
34
            }
931
34
        }
932
78
        else if (!existing) {
933
74
            assert(scope != FREE || PySet_Contains(comp_free, k) == 1);
934
74
        }
935
112
    }
936
53
    return 1;
937
0
error:
938
0
    return 0;
939
53
}
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
5.39k
{
954
5.39k
    PyObject *name, *v, *v_cell;
955
5.39k
    int success = 0;
956
5.39k
    Py_ssize_t pos = 0;
957
958
5.39k
    v_cell = PyLong_FromLong(CELL);
959
5.39k
    if (!v_cell)
960
0
        return 0;
961
24.3k
    while (PyDict_Next(scopes, &pos, &name, &v)) {
962
18.9k
        long scope = PyLong_AsLong(v);
963
18.9k
        if (scope == -1 && PyErr_Occurred()) {
964
0
            goto error;
965
0
        }
966
18.9k
        if (scope != LOCAL)
967
6.39k
            continue;
968
12.5k
        int contains = PySet_Contains(free, name);
969
12.5k
        if (contains < 0) {
970
0
            goto error;
971
0
        }
972
12.5k
        if (!contains) {
973
12.0k
            contains = PySet_Contains(inlined_cells, name);
974
12.0k
            if (contains < 0) {
975
0
                goto error;
976
0
            }
977
12.0k
            if (!contains) {
978
12.0k
                continue;
979
12.0k
            }
980
12.0k
        }
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
533
        if (PyDict_SetItem(scopes, name, v_cell) < 0)
986
0
            goto error;
987
533
        if (PySet_Discard(free, name) < 0)
988
0
            goto error;
989
533
    }
990
5.39k
    success = 1;
991
5.39k
 error:
992
5.39k
    Py_DECREF(v_cell);
993
5.39k
    return success;
994
5.39k
}
995
996
static int
997
drop_class_free(PySTEntryObject *ste, PyObject *free)
998
676
{
999
676
    int res;
1000
676
    res = PySet_Discard(free, &_Py_ID(__class__));
1001
676
    if (res < 0)
1002
0
        return 0;
1003
676
    if (res)
1004
11
        ste->ste_needs_class_closure = 1;
1005
676
    res = PySet_Discard(free, &_Py_ID(__classdict__));
1006
676
    if (res < 0)
1007
0
        return 0;
1008
676
    if (res)
1009
356
        ste->ste_needs_classdict = 1;
1010
676
    res = PySet_Discard(free, &_Py_ID(__conditional_annotations__));
1011
676
    if (res < 0)
1012
0
        return 0;
1013
676
    if (res) {
1014
0
        ste->ste_has_conditional_annotations = 1;
1015
0
    }
1016
676
    return 1;
1017
676
}
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.79k
{
1028
6.79k
    PyObject *name = NULL, *itr = NULL;
1029
6.79k
    PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
1030
6.79k
    Py_ssize_t pos = 0;
1031
1032
    /* Update scope information for all symbols in this scope */
1033
30.4k
    while (PyDict_Next(symbols, &pos, &name, &v)) {
1034
23.6k
        long flags = PyLong_AsLong(v);
1035
23.6k
        if (flags == -1 && PyErr_Occurred()) {
1036
0
            return 0;
1037
0
        }
1038
23.6k
        if (PyDict_GetItemRef(scopes, name, &v_scope) < 0) {
1039
0
            return 0;
1040
0
        }
1041
23.6k
        if (!v_scope) {
1042
0
            PyErr_SetObject(PyExc_KeyError, name);
1043
0
            return 0;
1044
0
        }
1045
23.6k
        long scope = PyLong_AsLong(v_scope);
1046
23.6k
        Py_DECREF(v_scope);
1047
23.6k
        if (scope == -1 && PyErr_Occurred()) {
1048
0
            return 0;
1049
0
        }
1050
23.6k
        flags |= (scope << SCOPE_OFFSET);
1051
23.6k
        v_new = PyLong_FromLong(flags);
1052
23.6k
        if (!v_new)
1053
0
            return 0;
1054
23.6k
        if (PyDict_SetItem(symbols, name, v_new) < 0) {
1055
0
            Py_DECREF(v_new);
1056
0
            return 0;
1057
0
        }
1058
23.6k
        Py_DECREF(v_new);
1059
23.6k
    }
1060
1061
    /* Record not yet resolved free variables from children (if any) */
1062
6.79k
    v_free = PyLong_FromLong(FREE << SCOPE_OFFSET);
1063
6.79k
    if (!v_free)
1064
0
        return 0;
1065
1066
6.79k
    itr = PyObject_GetIter(free);
1067
6.79k
    if (itr == NULL) {
1068
0
        Py_DECREF(v_free);
1069
0
        return 0;
1070
0
    }
1071
1072
6.80k
    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.79k
    if (PyErr_Occurred()) {
1124
0
        goto error;
1125
0
    }
1126
1127
6.79k
    Py_DECREF(itr);
1128
6.79k
    Py_DECREF(v_free);
1129
6.79k
    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.79k
}
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.79k
{
1167
6.79k
    PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
1168
6.79k
    PyObject *newglobal = NULL, *newfree = NULL, *inlined_cells = NULL;
1169
6.79k
    PyObject *temp;
1170
6.79k
    int success = 0;
1171
6.79k
    Py_ssize_t i, pos = 0;
1172
1173
6.79k
    local = PySet_New(NULL);  /* collect new names bound in block */
1174
6.79k
    if (!local)
1175
0
        goto error;
1176
6.79k
    scopes = PyDict_New();  /* collect scopes defined for each name */
1177
6.79k
    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.79k
    newglobal = PySet_New(NULL);
1192
6.79k
    if (!newglobal)
1193
0
        goto error;
1194
6.79k
    newfree = PySet_New(NULL);
1195
6.79k
    if (!newfree)
1196
0
        goto error;
1197
6.79k
    newbound = PySet_New(NULL);
1198
6.79k
    if (!newbound)
1199
0
        goto error;
1200
6.79k
    inlined_cells = PySet_New(NULL);
1201
6.79k
    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.79k
    if (ste->ste_type == ClassBlock) {
1209
        /* Pass down known globals */
1210
676
        temp = PyNumber_InPlaceOr(newglobal, global);
1211
676
        if (!temp)
1212
0
            goto error;
1213
676
        Py_DECREF(temp);
1214
        /* Pass down previously bound symbols */
1215
676
        if (bound) {
1216
676
            temp = PyNumber_InPlaceOr(newbound, bound);
1217
676
            if (!temp)
1218
0
                goto error;
1219
676
            Py_DECREF(temp);
1220
676
        }
1221
676
    }
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
30.4k
    while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
1227
23.6k
        long flags = PyLong_AsLong(v);
1228
23.6k
        if (flags == -1 && PyErr_Occurred()) {
1229
0
            goto error;
1230
0
        }
1231
23.6k
        if (!(flags & (DEF_GLOBAL | DEF_NONLOCAL | DEF_BOUND))) {
1232
6.63k
            continue;
1233
6.63k
        }
1234
17.0k
        if (!analyze_name(ste, scopes, name, flags,
1235
17.0k
                          bound, local, free, global, type_params, class_entry))
1236
0
            goto error;
1237
17.0k
    }
1238
1239
    /* Populate global and bound sets to be passed to children. */
1240
6.79k
    if (ste->ste_type != ClassBlock) {
1241
        /* Add function locals to bound set */
1242
6.12k
        if (ste_uses_fast_locals(ste)) {
1243
5.39k
            temp = PyNumber_InPlaceOr(newbound, local);
1244
5.39k
            if (!temp)
1245
0
                goto error;
1246
5.39k
            Py_DECREF(temp);
1247
5.39k
        }
1248
        /* Pass down previously bound symbols */
1249
6.12k
        if (bound) {
1250
5.39k
            temp = PyNumber_InPlaceOr(newbound, bound);
1251
5.39k
            if (!temp)
1252
0
                goto error;
1253
5.39k
            Py_DECREF(temp);
1254
5.39k
        }
1255
        /* Pass down known globals */
1256
6.12k
        temp = PyNumber_InPlaceOr(newglobal, global);
1257
6.12k
        if (!temp)
1258
0
            goto error;
1259
6.12k
        Py_DECREF(temp);
1260
6.12k
    }
1261
676
    else {
1262
        /* Special-case __class__ and __classdict__ */
1263
676
        if (PySet_Add(newbound, &_Py_ID(__class__)) < 0)
1264
0
            goto error;
1265
676
        if (PySet_Add(newbound, &_Py_ID(__classdict__)) < 0)
1266
0
            goto error;
1267
676
        if (PySet_Add(newbound, &_Py_ID(__conditional_annotations__)) < 0)
1268
0
            goto error;
1269
676
    }
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
12.8k
    for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
1278
6.07k
        PyObject *child_free = NULL;
1279
6.07k
        PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
1280
6.07k
        PySTEntryObject* entry;
1281
6.07k
        assert(c && PySTEntry_Check(c));
1282
6.07k
        entry = (PySTEntryObject*)c;
1283
1284
6.07k
        PySTEntryObject *new_class_entry = NULL;
1285
6.07k
        if (entry->ste_can_see_class_scope) {
1286
1.11k
            if (ste->ste_type == ClassBlock) {
1287
1.11k
                new_class_entry = ste;
1288
1.11k
            }
1289
0
            else if (class_entry) {
1290
0
                new_class_entry = class_entry;
1291
0
            }
1292
1.11k
        }
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
6.07k
        if (!analyze_child_block(entry, newbound, newfree, newglobal,
1298
6.07k
                                 type_params, new_class_entry, &child_free))
1299
0
        {
1300
0
            goto error;
1301
0
        }
1302
6.07k
        if (entry->ste_type == InlinedComprehensionBlock) {
1303
53
            if (!finalize_inlined_comprehension(ste, entry, child_free, newfree,
1304
53
                                                inlined_cells)) {
1305
0
                Py_DECREF(child_free);
1306
0
                goto error;
1307
0
            }
1308
53
        }
1309
6.07k
        temp = PyNumber_InPlaceOr(newfree, child_free);
1310
6.07k
        Py_DECREF(child_free);
1311
6.07k
        if (!temp)
1312
0
            goto error;
1313
6.07k
        Py_DECREF(temp);
1314
6.07k
    }
1315
1316
    /* Complete the classification. */
1317
6.79k
    pos = 0;
1318
30.4k
    while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
1319
23.6k
        long flags = PyLong_AsLong(v);
1320
23.6k
        if (flags == -1 && PyErr_Occurred()) {
1321
0
            goto error;
1322
0
        }
1323
23.6k
        int contains = PyDict_Contains(scopes, name);
1324
23.6k
        if (contains < 0) {
1325
0
            goto error;
1326
0
        }
1327
23.6k
        if (contains) {
1328
17.0k
            continue;
1329
17.0k
        }
1330
6.63k
        if (!analyze_name(ste, scopes, name, flags,
1331
6.63k
                          bound, local, free, global, type_params, class_entry))
1332
0
            goto error;
1333
6.63k
    }
1334
1335
    /* Check if any local variables must be converted to cell variables */
1336
6.79k
    if (ste_uses_fast_locals(ste) && !analyze_cells(scopes, newfree, inlined_cells)) {
1337
0
        goto error;
1338
0
    }
1339
6.79k
    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.79k
    if (!update_symbols(ste->ste_symbols, scopes, bound, newfree,
1344
6.79k
                        (ste->ste_type == ClassBlock) || ste->ste_can_see_class_scope))
1345
0
        goto error;
1346
6.79k
    temp = PyNumber_InPlaceOr(free, newfree);
1347
6.79k
    if (!temp)
1348
0
        goto error;
1349
6.79k
    Py_DECREF(temp);
1350
6.79k
    success = 1;
1351
6.79k
 error:
1352
6.79k
    Py_XDECREF(scopes);
1353
6.79k
    Py_XDECREF(local);
1354
6.79k
    Py_XDECREF(newbound);
1355
6.79k
    Py_XDECREF(newglobal);
1356
6.79k
    Py_XDECREF(newfree);
1357
6.79k
    Py_XDECREF(inlined_cells);
1358
6.79k
    if (!success)
1359
6.79k
        assert(PyErr_Occurred());
1360
6.79k
    return success;
1361
6.79k
}
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
6.07k
{
1368
6.07k
    PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
1369
6.07k
    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
6.07k
    temp_bound = PySet_New(bound);
1379
6.07k
    if (!temp_bound)
1380
0
        goto error;
1381
6.07k
    temp_free = PySet_New(free);
1382
6.07k
    if (!temp_free)
1383
0
        goto error;
1384
6.07k
    temp_global = PySet_New(global);
1385
6.07k
    if (!temp_global)
1386
0
        goto error;
1387
6.07k
    temp_type_params = PySet_New(type_params);
1388
6.07k
    if (!temp_type_params)
1389
0
        goto error;
1390
1391
6.07k
    if (!analyze_block(entry, temp_bound, temp_free, temp_global,
1392
6.07k
                       temp_type_params, class_entry))
1393
0
        goto error;
1394
6.07k
    *child_free = temp_free;
1395
6.07k
    Py_DECREF(temp_bound);
1396
6.07k
    Py_DECREF(temp_global);
1397
6.07k
    Py_DECREF(temp_type_params);
1398
6.07k
    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
6.07k
}
1406
1407
static int
1408
symtable_analyze(struct symtable *st)
1409
728
{
1410
728
    PyObject *free, *global, *type_params;
1411
728
    int r;
1412
1413
728
    free = PySet_New(NULL);
1414
728
    if (!free)
1415
0
        return 0;
1416
728
    global = PySet_New(NULL);
1417
728
    if (!global) {
1418
0
        Py_DECREF(free);
1419
0
        return 0;
1420
0
    }
1421
728
    type_params = PySet_New(NULL);
1422
728
    if (!type_params) {
1423
0
        Py_DECREF(free);
1424
0
        Py_DECREF(global);
1425
0
        return 0;
1426
0
    }
1427
728
    r = analyze_block(st->st_top, NULL, free, global, type_params, NULL);
1428
728
    Py_DECREF(free);
1429
728
    Py_DECREF(global);
1430
728
    Py_DECREF(type_params);
1431
728
    return r;
1432
728
}
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.96k
{
1442
6.96k
    Py_ssize_t size;
1443
1444
6.96k
    st->st_cur = NULL;
1445
6.96k
    size = PyList_GET_SIZE(st->st_stack);
1446
6.96k
    if (size) {
1447
6.96k
        if (PyList_SetSlice(st->st_stack, size - 1, size, NULL) < 0)
1448
0
            return 0;
1449
6.96k
        if (--size)
1450
6.24k
            st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, size - 1);
1451
6.96k
    }
1452
6.96k
    return 1;
1453
6.96k
}
1454
1455
static int
1456
symtable_enter_existing_block(struct symtable *st, PySTEntryObject* ste, bool add_to_children)
1457
6.96k
{
1458
6.96k
    if (PyList_Append(st->st_stack, (PyObject *)ste) < 0) {
1459
0
        return 0;
1460
0
    }
1461
6.96k
    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.96k
    if (prev) {
1467
6.24k
        ste->ste_comp_iter_expr = prev->ste_comp_iter_expr;
1468
6.24k
    }
1469
    /* No need to inherit ste_mangled_names in classes, where all names
1470
     * are mangled. */
1471
6.96k
    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.96k
    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.96k
    if (st->st_future->ff_features & CO_FUTURE_ANNOTATIONS && ste->ste_type == AnnotationBlock) {
1481
9
        return 1;
1482
9
    }
1483
1484
6.95k
    if (ste->ste_type == ModuleBlock)
1485
728
        st->st_global = st->st_cur->ste_symbols;
1486
1487
6.95k
    if (add_to_children && prev) {
1488
6.07k
        if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) {
1489
0
            symtable_exit_block(st);
1490
0
            return 0;
1491
0
        }
1492
6.07k
    }
1493
6.95k
    return 1;
1494
6.95k
}
1495
1496
static int
1497
symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
1498
                     void *ast, _Py_SourceLocation loc)
1499
4.27k
{
1500
4.27k
    PySTEntryObject *ste = ste_new(st, name, block, ast, loc);
1501
4.27k
    if (ste == NULL) {
1502
0
        return 0;
1503
0
    }
1504
4.27k
    int result = symtable_enter_existing_block(st, ste, /* add_to_children */true);
1505
4.27k
    Py_DECREF(ste);
1506
4.27k
    if (result == 0) {
1507
0
        return 0;
1508
0
    }
1509
4.27k
    if (block == AnnotationBlock || block == TypeVariableBlock || block == TypeAliasBlock) {
1510
2.55k
        _Py_DECLARE_STR(format, ".format");
1511
        // We need to insert code that reads this "parameter" to the function.
1512
2.55k
        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.55k
        if (!symtable_add_def(st, &_Py_STR(format), USE, loc)) {
1517
0
            symtable_exit_block(st);
1518
0
            return 0;
1519
0
        }
1520
2.55k
    }
1521
4.27k
    return 1;
1522
4.27k
}
1523
1524
static long
1525
symtable_lookup_entry(struct symtable *st, PySTEntryObject *ste, PyObject *name)
1526
198
{
1527
198
    PyObject *mangled = _Py_MaybeMangle(st->st_private, ste, name);
1528
198
    if (!mangled)
1529
0
        return -1;
1530
198
    long ret = _PyST_GetSymbol(ste, mangled);
1531
198
    Py_DECREF(mangled);
1532
198
    if (ret < 0) {
1533
0
        return -1;
1534
0
    }
1535
198
    return ret;
1536
198
}
1537
1538
static long
1539
symtable_lookup(struct symtable *st, PyObject *name)
1540
198
{
1541
198
    return symtable_lookup_entry(st, st->st_cur, name);
1542
198
}
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
50.5k
{
1548
50.5k
    PyObject *o;
1549
50.5k
    long val = 0;
1550
50.5k
    PyObject *mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1551
1552
50.5k
    if (!mangled)
1553
0
        return 0;
1554
50.5k
    if ((o = PyDict_GetItemWithError(ste->ste_symbols, mangled))) {
1555
26.9k
        val = PyLong_AsLong(o);
1556
26.9k
        if (val == -1 && PyErr_Occurred()) {
1557
0
            goto error;
1558
0
        }
1559
26.9k
        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
26.9k
        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
26.9k
    }
1571
23.6k
    else if (PyErr_Occurred()) {
1572
0
        goto error;
1573
0
    }
1574
1575
50.5k
    int to_add = flag;
1576
50.5k
    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
102
        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
102
        to_add |= DEF_COMP_ITER;
1589
102
    }
1590
50.5k
    if (!symtable_add_flag(ste->ste_symbols, mangled, to_add)) {
1591
0
        goto error;
1592
0
    }
1593
1594
50.5k
    if (flag & DEF_PARAM) {
1595
9.98k
        if (PyList_Append(ste->ste_varnames, mangled) < 0)
1596
0
            goto error;
1597
9.98k
    }
1598
40.6k
    else if (flag & DEF_GLOBAL) {
1599
        /* XXX need to update DEF_GLOBAL for other flags too;
1600
           perhaps only DEF_FREE_GLOBAL */
1601
7
        if (!symtable_add_flag(st->st_global, mangled, flag)) {
1602
0
            goto error;
1603
0
        }
1604
7
    }
1605
50.5k
    Py_DECREF(mangled);
1606
50.5k
    return 1;
1607
1608
0
error:
1609
0
    Py_DECREF(mangled);
1610
0
    return 0;
1611
50.5k
}
1612
1613
static int
1614
check_name(struct symtable *st, PyObject *name, _Py_SourceLocation loc,
1615
           expr_context_ty ctx)
1616
31.0k
{
1617
31.0k
    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
31.0k
    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
31.0k
    return 1;
1628
31.0k
}
1629
1630
static int
1631
check_keywords(struct symtable *st, asdl_keyword_seq *keywords)
1632
7.93k
{
1633
9.67k
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(keywords); i++) {
1634
1.74k
        keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
1635
1.74k
        if (key->arg  && !check_name(st, key->arg, LOCATION(key), Store)) {
1636
0
            return 0;
1637
0
        }
1638
1.74k
    }
1639
7.93k
    return 1;
1640
7.93k
}
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
50.5k
{
1661
50.5k
    int write_mask = DEF_PARAM | DEF_LOCAL | DEF_IMPORT;
1662
50.5k
    if ((flag & write_mask) && !check_name(st, name, loc, ctx)) {
1663
0
        return 0;
1664
0
    }
1665
50.5k
    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
50.5k
    return symtable_add_def_helper(st, name, flag, st->st_cur, loc);
1671
50.5k
}
1672
1673
static int
1674
symtable_add_def(struct symtable *st, PyObject *name, int flag,
1675
                 _Py_SourceLocation loc)
1676
18.5k
{
1677
18.5k
    return symtable_add_def_ctx(st, name, flag, loc,
1678
18.5k
                                flag == USE ? Load : Store);
1679
18.5k
}
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
44.6k
    do { \
1749
44.6k
        if (!symtable_visit_ ## TYPE((ST), (V))) { \
1750
0
            return 0; \
1751
0
        } \
1752
44.6k
    } while(0)
1753
1754
#define VISIT_SEQ(ST, TYPE, SEQ) \
1755
27.9k
    do { \
1756
27.9k
        Py_ssize_t i; \
1757
27.9k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1758
77.7k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1759
49.8k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1760
49.8k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1761
49.8k
                return 0;                 \
1762
49.8k
        } \
1763
27.9k
    } while(0)
1764
1765
#define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) \
1766
80
    do { \
1767
80
        Py_ssize_t i; \
1768
80
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1769
80
        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
80
    } while(0)
1775
1776
#define VISIT_SEQ_WITH_NULL(ST, TYPE, SEQ) \
1777
10.1k
    do { \
1778
10.1k
        int i = 0; \
1779
10.1k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1780
19.1k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1781
9.02k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1782
9.02k
            if (!elt) continue; /* can be NULL */ \
1783
9.02k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1784
9.01k
                return 0;             \
1785
9.01k
        } \
1786
10.1k
    } while(0)
1787
1788
#define ENTER_CONDITIONAL_BLOCK(ST) \
1789
2.57k
    int in_conditional_block = (ST)->st_cur->ste_in_conditional_block; \
1790
2.57k
    (ST)->st_cur->ste_in_conditional_block = 1;
1791
1792
#define LEAVE_CONDITIONAL_BLOCK(ST) \
1793
2.57k
    (ST)->st_cur->ste_in_conditional_block = in_conditional_block;
1794
1795
#define ENTER_TRY_BLOCK(ST) \
1796
212
    int in_try_block = (ST)->st_cur->ste_in_try_block; \
1797
212
    (ST)->st_cur->ste_in_try_block = 1;
1798
1799
#define LEAVE_TRY_BLOCK(ST) \
1800
212
    (ST)->st_cur->ste_in_try_block = in_try_block;
1801
1802
100k
#define ENTER_RECURSIVE() \
1803
100k
if (Py_EnterRecursiveCall(" during compilation")) { \
1804
0
    return 0; \
1805
0
}
1806
1807
100k
#define LEAVE_RECURSIVE() Py_LeaveRecursiveCall();
1808
1809
1810
static int
1811
symtable_record_directive(struct symtable *st, identifier name, _Py_SourceLocation loc)
1812
9
{
1813
9
    PyObject *data, *mangled;
1814
9
    int res;
1815
9
    if (!st->st_cur->ste_directives) {
1816
8
        st->st_cur->ste_directives = PyList_New(0);
1817
8
        if (!st->st_cur->ste_directives)
1818
0
            return 0;
1819
8
    }
1820
9
    mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1821
9
    if (!mangled)
1822
0
        return 0;
1823
9
    data = Py_BuildValue("(Niiii)", mangled, loc.lineno, loc.col_offset,
1824
9
                                    loc.end_lineno, loc.end_col_offset);
1825
9
    if (!data)
1826
0
        return 0;
1827
9
    res = PyList_Append(st->st_cur->ste_directives, data);
1828
9
    Py_DECREF(data);
1829
9
    return res == 0;
1830
9
}
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
445
{
1847
445
    assert(s->kind == ImportFrom_kind);
1848
445
    _Py_SourceLocation fut = st->st_future->ff_location;
1849
445
    if (s->v.ImportFrom.module && s->v.ImportFrom.level == 0 &&
1850
418
        _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
445
    return 1;
1861
445
}
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
4
{
1898
4
    return (st->st_future->ff_features & PyCF_ALLOW_TOP_LEVEL_AWAIT) &&
1899
0
            st->st_cur->ste_type == ModuleBlock;
1900
4
}
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
16.2k
{
1914
16.2k
    ENTER_RECURSIVE();
1915
16.2k
    switch (s->kind) {
1916
2.52k
    case FunctionDef_kind: {
1917
2.52k
        if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL, LOCATION(s)))
1918
0
            return 0;
1919
2.52k
        if (s->v.FunctionDef.args->defaults)
1920
2.52k
            VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
1921
2.52k
        if (s->v.FunctionDef.args->kw_defaults)
1922
2.52k
            VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults);
1923
2.52k
        if (s->v.FunctionDef.decorator_list)
1924
147
            VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
1925
2.52k
        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.52k
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
1939
2.52k
                                           LOCATION(s));
1940
2.52k
        if (!new_ste) {
1941
0
            return 0;
1942
0
        }
1943
1944
2.52k
        if (_PyAST_GetDocString(s->v.FunctionDef.body)) {
1945
297
            new_ste->ste_has_docstring = 1;
1946
297
        }
1947
1948
2.52k
        if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args,
1949
2.52k
                                        s->v.FunctionDef.returns, new_ste)) {
1950
0
            Py_DECREF(new_ste);
1951
0
            return 0;
1952
0
        }
1953
2.52k
        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.52k
        Py_DECREF(new_ste);
1958
2.52k
        VISIT(st, arguments, s->v.FunctionDef.args);
1959
2.52k
        VISIT_SEQ(st, stmt, s->v.FunctionDef.body);
1960
2.52k
        if (!symtable_exit_block(st))
1961
0
            return 0;
1962
2.52k
        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.52k
        break;
1967
2.52k
    }
1968
2.52k
    case ClassDef_kind: {
1969
676
        PyObject *tmp;
1970
676
        if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL, LOCATION(s)))
1971
0
            return 0;
1972
676
        if (s->v.ClassDef.decorator_list)
1973
16
            VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
1974
676
        tmp = st->st_private;
1975
676
        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
676
        VISIT_SEQ(st, expr, s->v.ClassDef.bases);
1990
676
        if (!check_keywords(st, s->v.ClassDef.keywords)) {
1991
0
            return 0;
1992
0
        }
1993
676
        VISIT_SEQ(st, keyword, s->v.ClassDef.keywords);
1994
676
        if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
1995
676
                                  (void *)s, LOCATION(s))) {
1996
0
            return 0;
1997
0
        }
1998
676
        st->st_private = s->v.ClassDef.name;
1999
676
        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
676
        if (_PyAST_GetDocString(s->v.ClassDef.body)) {
2012
58
            st->st_cur->ste_has_docstring = 1;
2013
58
        }
2014
2015
676
        VISIT_SEQ(st, stmt, s->v.ClassDef.body);
2016
676
        if (!symtable_exit_block(st))
2017
0
            return 0;
2018
676
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
2019
0
            if (!symtable_exit_block(st))
2020
0
                return 0;
2021
0
        }
2022
676
        st->st_private = tmp;
2023
676
        break;
2024
676
    }
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.29k
    case Return_kind:
2059
2.29k
        if (s->v.Return.value) {
2060
2.15k
            VISIT(st, expr, s->v.Return.value);
2061
2.15k
            st->st_cur->ste_returns_value = 1;
2062
2.15k
        }
2063
2.29k
        break;
2064
2.29k
    case Delete_kind:
2065
24
        VISIT_SEQ(st, expr, s->v.Delete.targets);
2066
24
        break;
2067
3.58k
    case Assign_kind:
2068
3.58k
        VISIT_SEQ(st, expr, s->v.Assign.targets);
2069
3.58k
        VISIT(st, expr, s->v.Assign.value);
2070
3.58k
        break;
2071
3.58k
    case AnnAssign_kind:
2072
189
        st->st_cur->ste_annotations_used = 1;
2073
189
        if (s->v.AnnAssign.target->kind == Name_kind) {
2074
189
            expr_ty e_name = s->v.AnnAssign.target;
2075
189
            long cur = symtable_lookup(st, e_name->v.Name.id);
2076
189
            if (cur < 0) {
2077
0
                return 0;
2078
0
            }
2079
189
            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
189
            if (s->v.AnnAssign.simple &&
2089
189
                !symtable_add_def(st, e_name->v.Name.id,
2090
189
                                  DEF_ANNOT | DEF_LOCAL, LOCATION(e_name))) {
2091
0
                return 0;
2092
0
            }
2093
189
            else {
2094
189
                if (s->v.AnnAssign.value
2095
186
                    && !symtable_add_def(st, e_name->v.Name.id, DEF_LOCAL, LOCATION(e_name))) {
2096
0
                    return 0;
2097
0
                }
2098
189
            }
2099
189
        }
2100
0
        else {
2101
0
            VISIT(st, expr, s->v.AnnAssign.target);
2102
0
        }
2103
189
        if (!symtable_visit_annotation(st, s->v.AnnAssign.annotation,
2104
189
                                       (void *)((uintptr_t)st->st_cur->ste_id + 1))) {
2105
0
            return 0;
2106
0
        }
2107
2108
189
        if (s->v.AnnAssign.value) {
2109
186
            VISIT(st, expr, s->v.AnnAssign.value);
2110
186
        }
2111
189
        break;
2112
189
    case AugAssign_kind: {
2113
133
        VISIT(st, expr, s->v.AugAssign.target);
2114
133
        VISIT(st, expr, s->v.AugAssign.value);
2115
133
        break;
2116
133
    }
2117
254
    case For_kind: {
2118
254
        VISIT(st, expr, s->v.For.target);
2119
254
        VISIT(st, expr, s->v.For.iter);
2120
254
        ENTER_CONDITIONAL_BLOCK(st);
2121
254
        VISIT_SEQ(st, stmt, s->v.For.body);
2122
254
        if (s->v.For.orelse)
2123
2
            VISIT_SEQ(st, stmt, s->v.For.orelse);
2124
254
        LEAVE_CONDITIONAL_BLOCK(st);
2125
254
        break;
2126
254
    }
2127
55
    case While_kind: {
2128
55
        VISIT(st, expr, s->v.While.test);
2129
55
        ENTER_CONDITIONAL_BLOCK(st);
2130
55
        VISIT_SEQ(st, stmt, s->v.While.body);
2131
55
        if (s->v.While.orelse)
2132
0
            VISIT_SEQ(st, stmt, s->v.While.orelse);
2133
55
        LEAVE_CONDITIONAL_BLOCK(st);
2134
55
        break;
2135
55
    }
2136
1.96k
    case If_kind: {
2137
        /* XXX if 0: and lookup_yield() hacks */
2138
1.96k
        VISIT(st, expr, s->v.If.test);
2139
1.96k
        ENTER_CONDITIONAL_BLOCK(st);
2140
1.96k
        VISIT_SEQ(st, stmt, s->v.If.body);
2141
1.96k
        if (s->v.If.orelse)
2142
496
            VISIT_SEQ(st, stmt, s->v.If.orelse);
2143
1.96k
        LEAVE_CONDITIONAL_BLOCK(st);
2144
1.96k
        break;
2145
1.96k
    }
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
377
    case Raise_kind:
2154
377
        if (s->v.Raise.exc) {
2155
348
            VISIT(st, expr, s->v.Raise.exc);
2156
348
            if (s->v.Raise.cause) {
2157
21
                VISIT(st, expr, s->v.Raise.cause);
2158
21
            }
2159
348
        }
2160
377
        break;
2161
377
    case Try_kind: {
2162
212
        ENTER_CONDITIONAL_BLOCK(st);
2163
212
        ENTER_TRY_BLOCK(st);
2164
212
        VISIT_SEQ(st, stmt, s->v.Try.body);
2165
212
        VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
2166
212
        VISIT_SEQ(st, stmt, s->v.Try.orelse);
2167
212
        VISIT_SEQ(st, stmt, s->v.Try.finalbody);
2168
212
        LEAVE_TRY_BLOCK(st);
2169
212
        LEAVE_CONDITIONAL_BLOCK(st);
2170
212
        break;
2171
212
    }
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
50
    case Assert_kind:
2184
50
        VISIT(st, expr, s->v.Assert.test);
2185
50
        if (s->v.Assert.msg)
2186
20
            VISIT(st, expr, s->v.Assert.msg);
2187
50
        break;
2188
375
    case Import_kind:
2189
375
        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
375
        VISIT_SEQ(st, alias, s->v.Import.names);
2195
375
        break;
2196
445
    case ImportFrom_kind:
2197
445
        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
445
        VISIT_SEQ(st, alias, s->v.ImportFrom.names);
2217
445
        if (!check_import_from(st, s)) {
2218
0
            return 0;
2219
0
        }
2220
445
        break;
2221
445
    case Global_kind: {
2222
7
        Py_ssize_t i;
2223
7
        asdl_identifier_seq *seq = s->v.Global.names;
2224
14
        for (i = 0; i < asdl_seq_LEN(seq); i++) {
2225
7
            identifier name = (identifier)asdl_seq_GET(seq, i);
2226
7
            long cur = symtable_lookup(st, name);
2227
7
            if (cur < 0)
2228
0
                return 0;
2229
7
            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
7
            if (!symtable_add_def(st, name, DEF_GLOBAL, LOCATION(s))) {
2246
0
                return 0;
2247
0
            }
2248
7
            if (!symtable_record_directive(st, name, LOCATION(s))) {
2249
0
                return 0;
2250
0
            }
2251
7
        }
2252
7
        break;
2253
7
    }
2254
7
    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.67k
    case Expr_kind:
2286
2.67k
        VISIT(st, expr, s->v.Expr.value);
2287
2.67k
        break;
2288
2.67k
    case Pass_kind:
2289
230
    case Break_kind:
2290
270
    case Continue_kind:
2291
        /* nothing to do here */
2292
270
        break;
2293
86
    case With_kind: {
2294
86
        ENTER_CONDITIONAL_BLOCK(st);
2295
86
        VISIT_SEQ(st, withitem, s->v.With.items);
2296
86
        VISIT_SEQ(st, stmt, s->v.With.body);
2297
86
        LEAVE_CONDITIONAL_BLOCK(st);
2298
86
        break;
2299
86
    }
2300
4
    case AsyncFunctionDef_kind: {
2301
4
        if (!symtable_add_def(st, s->v.AsyncFunctionDef.name, DEF_LOCAL, LOCATION(s)))
2302
0
            return 0;
2303
4
        if (s->v.AsyncFunctionDef.args->defaults)
2304
4
            VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.args->defaults);
2305
4
        if (s->v.AsyncFunctionDef.args->kw_defaults)
2306
4
            VISIT_SEQ_WITH_NULL(st, expr,
2307
4
                                s->v.AsyncFunctionDef.args->kw_defaults);
2308
4
        if (s->v.AsyncFunctionDef.decorator_list)
2309
2
            VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.decorator_list);
2310
4
        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
4
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
2324
4
                                           LOCATION(s));
2325
4
        if (!new_ste) {
2326
0
            return 0;
2327
0
        }
2328
2329
4
        if (_PyAST_GetDocString(s->v.AsyncFunctionDef.body)) {
2330
0
            new_ste->ste_has_docstring = 1;
2331
0
        }
2332
2333
4
        if (!symtable_visit_annotations(st, s, s->v.AsyncFunctionDef.args,
2334
4
                                        s->v.AsyncFunctionDef.returns, new_ste)) {
2335
0
            Py_DECREF(new_ste);
2336
0
            return 0;
2337
0
        }
2338
4
        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
4
        Py_DECREF(new_ste);
2343
2344
4
        st->st_cur->ste_coroutine = 1;
2345
4
        VISIT(st, arguments, s->v.AsyncFunctionDef.args);
2346
4
        VISIT_SEQ(st, stmt, s->v.AsyncFunctionDef.body);
2347
4
        if (!symtable_exit_block(st))
2348
0
            return 0;
2349
4
        if (asdl_seq_LEN(s->v.AsyncFunctionDef.type_params) > 0) {
2350
0
            if (!symtable_exit_block(st))
2351
0
                return 0;
2352
0
        }
2353
4
        break;
2354
4
    }
2355
4
    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
16.2k
    }
2381
16.2k
    LEAVE_RECURSIVE();
2382
16.2k
    return 1;
2383
16.2k
}
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
84.4k
{
2504
84.4k
    ENTER_RECURSIVE();
2505
84.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
512
    case BoolOp_kind:
2514
512
        VISIT_SEQ(st, expr, e->v.BoolOp.values);
2515
512
        break;
2516
680
    case BinOp_kind:
2517
680
        VISIT(st, expr, e->v.BinOp.left);
2518
680
        VISIT(st, expr, e->v.BinOp.right);
2519
680
        break;
2520
1.99k
    case UnaryOp_kind:
2521
1.99k
        VISIT(st, expr, e->v.UnaryOp.operand);
2522
1.99k
        break;
2523
1.99k
    case Lambda_kind: {
2524
230
        if (e->v.Lambda.args->defaults)
2525
230
            VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
2526
230
        if (e->v.Lambda.args->kw_defaults)
2527
230
            VISIT_SEQ_WITH_NULL(st, expr, e->v.Lambda.args->kw_defaults);
2528
230
        if (!symtable_enter_block(st, &_Py_STR(anon_lambda),
2529
230
                                  FunctionBlock, (void *)e, LOCATION(e))) {
2530
0
            return 0;
2531
0
        }
2532
230
        VISIT(st, arguments, e->v.Lambda.args);
2533
230
        VISIT(st, expr, e->v.Lambda.body);
2534
230
        if (!symtable_exit_block(st))
2535
0
            return 0;
2536
230
        break;
2537
230
    }
2538
230
    case IfExp_kind:
2539
89
        VISIT(st, expr, e->v.IfExp.test);
2540
89
        VISIT(st, expr, e->v.IfExp.body);
2541
89
        VISIT(st, expr, e->v.IfExp.orelse);
2542
89
        break;
2543
127
    case Dict_kind:
2544
127
        VISIT_SEQ_WITH_NULL(st, expr, e->v.Dict.keys);
2545
127
        VISIT_SEQ(st, expr, e->v.Dict.values);
2546
127
        break;
2547
138
    case Set_kind:
2548
138
        VISIT_SEQ(st, expr, e->v.Set.elts);
2549
138
        break;
2550
138
    case GeneratorExp_kind:
2551
27
        if (!symtable_visit_genexp(st, e))
2552
0
            return 0;
2553
27
        break;
2554
44
    case ListComp_kind:
2555
44
        if (!symtable_visit_listcomp(st, e))
2556
0
            return 0;
2557
44
        break;
2558
44
    case SetComp_kind:
2559
4
        if (!symtable_visit_setcomp(st, e))
2560
0
            return 0;
2561
4
        break;
2562
5
    case DictComp_kind:
2563
5
        if (!symtable_visit_dictcomp(st, e))
2564
0
            return 0;
2565
5
        break;
2566
83
    case Yield_kind:
2567
83
        if (!symtable_raise_if_annotation_block(st, "yield expression", e)) {
2568
0
            return 0;
2569
0
        }
2570
83
        if (e->v.Yield.value)
2571
78
            VISIT(st, expr, e->v.Yield.value);
2572
83
        st->st_cur->ste_generator = 1;
2573
83
        if (st->st_cur->ste_comprehension) {
2574
0
            return symtable_raise_if_comprehension_block(st, e);
2575
0
        }
2576
83
        break;
2577
83
    case YieldFrom_kind:
2578
17
        if (!symtable_raise_if_annotation_block(st, "yield expression", e)) {
2579
0
            return 0;
2580
0
        }
2581
17
        VISIT(st, expr, e->v.YieldFrom.value);
2582
17
        st->st_cur->ste_generator = 1;
2583
17
        if (st->st_cur->ste_comprehension) {
2584
0
            return symtable_raise_if_comprehension_block(st, e);
2585
0
        }
2586
17
        break;
2587
17
    case Await_kind:
2588
4
        if (!symtable_raise_if_annotation_block(st, "await expression", e)) {
2589
0
            return 0;
2590
0
        }
2591
4
        if (!allows_top_level_await(st)) {
2592
4
            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
4
            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
4
        }
2605
4
        VISIT(st, expr, e->v.Await.value);
2606
4
        st->st_cur->ste_coroutine = 1;
2607
4
        break;
2608
2.15k
    case Compare_kind:
2609
2.15k
        VISIT(st, expr, e->v.Compare.left);
2610
2.15k
        VISIT_SEQ(st, expr, e->v.Compare.comparators);
2611
2.15k
        break;
2612
7.25k
    case Call_kind:
2613
7.25k
        VISIT(st, expr, e->v.Call.func);
2614
7.25k
        VISIT_SEQ(st, expr, e->v.Call.args);
2615
7.25k
        if (!check_keywords(st, e->v.Call.keywords)) {
2616
0
            return 0;
2617
0
        }
2618
7.25k
        VISIT_SEQ_WITH_NULL(st, keyword, e->v.Call.keywords);
2619
7.25k
        break;
2620
7.25k
    case FormattedValue_kind:
2621
1.23k
        VISIT(st, expr, e->v.FormattedValue.value);
2622
1.23k
        if (e->v.FormattedValue.format_spec)
2623
3
            VISIT(st, expr, e->v.FormattedValue.format_spec);
2624
1.23k
        break;
2625
1.23k
    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
459
    case JoinedStr_kind:
2631
459
        VISIT_SEQ(st, expr, e->v.JoinedStr.values);
2632
459
        break;
2633
459
    case TemplateStr_kind:
2634
1
        VISIT_SEQ(st, expr, e->v.TemplateStr.values);
2635
1
        break;
2636
23.8k
    case Constant_kind:
2637
        /* Nothing to do here. */
2638
23.8k
        break;
2639
    /* The following exprs can be assignment targets. */
2640
11.1k
    case Attribute_kind:
2641
11.1k
        if (!check_name(st, e->v.Attribute.attr, LOCATION(e), e->v.Attribute.ctx)) {
2642
0
            return 0;
2643
0
        }
2644
11.1k
        VISIT(st, expr, e->v.Attribute.value);
2645
11.1k
        break;
2646
11.1k
    case Subscript_kind:
2647
818
        VISIT(st, expr, e->v.Subscript.value);
2648
818
        VISIT(st, expr, e->v.Subscript.slice);
2649
818
        break;
2650
818
    case Starred_kind:
2651
106
        VISIT(st, expr, e->v.Starred.value);
2652
106
        break;
2653
110
    case Slice_kind:
2654
110
        if (e->v.Slice.lower)
2655
64
            VISIT(st, expr, e->v.Slice.lower);
2656
110
        if (e->v.Slice.upper)
2657
70
            VISIT(st, expr, e->v.Slice.upper);
2658
110
        if (e->v.Slice.step)
2659
0
            VISIT(st, expr, e->v.Slice.step);
2660
110
        break;
2661
32.0k
    case Name_kind:
2662
32.0k
        if (!st->st_cur->ste_in_unevaluated_annotation) {
2663
32.0k
            if (!symtable_add_def_ctx(st, e->v.Name.id,
2664
32.0k
                                    e->v.Name.ctx == Load ? USE : DEF_LOCAL,
2665
32.0k
                                    LOCATION(e), e->v.Name.ctx)) {
2666
0
                return 0;
2667
0
            }
2668
            /* Special-case super: it counts as a use of __class__ */
2669
32.0k
            if (e->v.Name.ctx == Load &&
2670
28.5k
                ste_uses_fast_locals(st->st_cur) &&
2671
26.4k
                _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
2672
143
                if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
2673
0
                    return 0;
2674
143
            }
2675
32.0k
        }
2676
32.0k
        break;
2677
    /* child nodes of List and Tuple will have expr_context set */
2678
32.0k
    case List_kind:
2679
167
        VISIT_SEQ(st, expr, e->v.List.elts);
2680
167
        break;
2681
1.12k
    case Tuple_kind:
2682
1.12k
        VISIT_SEQ(st, expr, e->v.Tuple.elts);
2683
1.12k
        break;
2684
84.4k
    }
2685
84.4k
    LEAVE_RECURSIVE();
2686
84.4k
    return 1;
2687
84.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
27
{
2844
27
    PyObject *id = PyUnicode_FromFormat(".%d", pos);
2845
27
    if (id == NULL)
2846
0
        return 0;
2847
27
    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
27
    Py_DECREF(id);
2852
27
    return 1;
2853
27
}
2854
2855
static int
2856
symtable_visit_params(struct symtable *st, asdl_arg_seq *args)
2857
8.28k
{
2858
8.28k
    Py_ssize_t i;
2859
2860
15.5k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2861
7.23k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2862
7.23k
        if (!symtable_add_def(st, arg->arg, DEF_PARAM, LOCATION(arg)))
2863
0
            return 0;
2864
7.23k
    }
2865
2866
8.28k
    return 1;
2867
8.28k
}
2868
2869
static int
2870
symtable_visit_annotation(struct symtable *st, expr_ty annotation, void *key)
2871
189
{
2872
    // Annotations in local scopes are not executed and should not affect the symtable
2873
189
    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
189
    if ((((st->st_cur->ste_type == ClassBlock && st->st_cur->ste_in_conditional_block)
2878
189
            || 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
189
    struct _symtable_entry *parent_ste = st->st_cur;
2887
189
    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
164
    else {
2905
164
        if (!symtable_enter_existing_block(st, parent_ste->ste_annotation_block,
2906
164
                                           /* add_to_children */false)) {
2907
0
            return 0;
2908
0
        }
2909
164
    }
2910
189
    if (is_unevaluated) {
2911
3
        st->st_cur->ste_in_unevaluated_annotation = 1;
2912
3
    }
2913
189
    int rc = symtable_visit_expr(st, annotation);
2914
189
    if (is_unevaluated) {
2915
3
        st->st_cur->ste_in_unevaluated_annotation = 0;
2916
3
    }
2917
189
    if (!symtable_exit_block(st)) {
2918
0
        return 0;
2919
0
    }
2920
189
    return rc;
2921
189
}
2922
2923
static int
2924
symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args)
2925
7.59k
{
2926
7.59k
    Py_ssize_t i;
2927
2928
13.7k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2929
6.19k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2930
6.19k
        if (arg->annotation) {
2931
53
            st->st_cur->ste_annotations_used = 1;
2932
53
            VISIT(st, expr, arg->annotation);
2933
53
        }
2934
6.19k
    }
2935
2936
7.59k
    return 1;
2937
7.59k
}
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.53k
{
2943
2.53k
    int is_in_class = st->st_cur->ste_can_see_class_scope;
2944
2.53k
    _Py_block_ty current_type = st->st_cur->ste_type;
2945
2.53k
    if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2946
2.53k
                              (void *)a, LOCATION(o))) {
2947
0
        return 0;
2948
0
    }
2949
2.53k
    Py_XSETREF(st->st_cur->ste_function_name, Py_NewRef(function_ste->ste_name));
2950
2.53k
    if (is_in_class || current_type == ClassBlock) {
2951
1.09k
        st->st_cur->ste_can_see_class_scope = 1;
2952
1.09k
        if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(o))) {
2953
0
            return 0;
2954
0
        }
2955
1.09k
    }
2956
2.53k
    if (a->posonlyargs && !symtable_visit_argannotations(st, a->posonlyargs))
2957
0
        return 0;
2958
2.53k
    if (a->args && !symtable_visit_argannotations(st, a->args))
2959
0
        return 0;
2960
2.53k
    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.53k
    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.53k
    if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs))
2969
0
        return 0;
2970
2.53k
    if (returns) {
2971
34
        st->st_cur->ste_annotations_used = 1;
2972
34
        VISIT(st, expr, returns);
2973
34
    }
2974
2.53k
    if (!symtable_exit_block(st)) {
2975
0
        return 0;
2976
0
    }
2977
2.53k
    return 1;
2978
2.53k
}
2979
2980
static int
2981
symtable_visit_arguments(struct symtable *st, arguments_ty a)
2982
2.76k
{
2983
    /* skip default arguments inside function block
2984
       XXX should ast be different?
2985
    */
2986
2.76k
    if (a->posonlyargs && !symtable_visit_params(st, a->posonlyargs))
2987
0
        return 0;
2988
2.76k
    if (a->args && !symtable_visit_params(st, a->args))
2989
0
        return 0;
2990
2.76k
    if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs))
2991
0
        return 0;
2992
2.76k
    if (a->vararg) {
2993
81
        if (!symtable_add_def(st, a->vararg->arg, DEF_PARAM, LOCATION(a->vararg)))
2994
0
            return 0;
2995
81
        st->st_cur->ste_varargs = 1;
2996
81
    }
2997
2.76k
    if (a->kwarg) {
2998
84
        if (!symtable_add_def(st, a->kwarg->arg, DEF_PARAM, LOCATION(a->kwarg)))
2999
0
            return 0;
3000
84
        st->st_cur->ste_varkeywords = 1;
3001
84
    }
3002
2.76k
    return 1;
3003
2.76k
}
3004
3005
3006
static int
3007
symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
3008
226
{
3009
226
    if (eh->v.ExceptHandler.type)
3010
213
        VISIT(st, expr, eh->v.ExceptHandler.type);
3011
226
    if (eh->v.ExceptHandler.name)
3012
30
        if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL, LOCATION(eh)))
3013
0
            return 0;
3014
226
    VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
3015
226
    return 1;
3016
226
}
3017
3018
static int
3019
symtable_visit_withitem(struct symtable *st, withitem_ty item)
3020
90
{
3021
90
    VISIT(st, expr, item->context_expr);
3022
90
    if (item->optional_vars) {
3023
30
        VISIT(st, expr, item->optional_vars);
3024
30
    }
3025
90
    return 1;
3026
90
}
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.13k
{
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.13k
    PyObject *store_name;
3047
1.13k
    PyObject *name = (a->asname == NULL) ? a->name : a->asname;
3048
1.13k
    Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
3049
1.13k
                                        PyUnicode_GET_LENGTH(name), 1);
3050
1.13k
    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.13k
    else {
3056
1.13k
        store_name = Py_NewRef(name);
3057
1.13k
    }
3058
1.13k
    if (!_PyUnicode_EqualToASCIIString(name, "*")) {
3059
1.13k
        int r = symtable_add_def(st, store_name, DEF_IMPORT, LOCATION(a));
3060
1.13k
        Py_DECREF(store_name);
3061
1.13k
        return r;
3062
1.13k
    }
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.13k
}
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.74k
{
3096
1.74k
    VISIT(st, expr, k->value);
3097
1.74k
    return 1;
3098
1.74k
}
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
80
{
3106
80
    int is_generator = (e->kind == GeneratorExp_kind);
3107
80
    comprehension_ty outermost = ((comprehension_ty)
3108
80
                                    asdl_seq_GET(generators, 0));
3109
    /* Outermost iterator is evaluated in current scope */
3110
80
    st->st_cur->ste_comp_iter_expr++;
3111
80
    VISIT(st, expr, outermost->iter);
3112
80
    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
80
    int will_inline = !is_generator && !st->st_cur->ste_can_see_class_scope;
3118
80
    _Py_block_ty block = will_inline ? InlinedComprehensionBlock : FunctionBlock;
3119
3120
    /* Create comprehension scope for the rest */
3121
80
    if (!scope_name ||
3122
80
        !symtable_enter_block(st, scope_name, block, (void *)e, LOCATION(e))) {
3123
0
        return 0;
3124
0
    }
3125
80
    switch(e->kind) {
3126
44
        case ListComp_kind:
3127
44
            st->st_cur->ste_comprehension = ListComprehension;
3128
44
            break;
3129
4
        case SetComp_kind:
3130
4
            st->st_cur->ste_comprehension = SetComprehension;
3131
4
            break;
3132
5
        case DictComp_kind:
3133
5
            st->st_cur->ste_comprehension = DictComprehension;
3134
5
            break;
3135
27
        default:
3136
27
            st->st_cur->ste_comprehension = GeneratorExpression;
3137
27
            break;
3138
80
    }
3139
80
    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
80
    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
80
    st->st_cur->ste_comp_iter_target = 1;
3150
80
    VISIT(st, expr, outermost->target);
3151
80
    st->st_cur->ste_comp_iter_target = 0;
3152
    /* Visit the rest of the comprehension body */
3153
80
    VISIT_SEQ(st, expr, outermost->ifs);
3154
80
    VISIT_SEQ_TAIL(st, comprehension, generators, 1);
3155
80
    if (value)
3156
5
        VISIT(st, expr, value);
3157
80
    VISIT(st, expr, elt);
3158
80
    st->st_cur->ste_generator = is_generator;
3159
80
    int is_async = st->st_cur->ste_coroutine && !is_generator;
3160
80
    if (!symtable_exit_block(st)) {
3161
0
        return 0;
3162
0
    }
3163
80
    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
80
    if (is_async) {
3174
0
        st->st_cur->ste_coroutine = 1;
3175
0
    }
3176
80
    return 1;
3177
80
}
3178
3179
static int
3180
symtable_visit_genexp(struct symtable *st, expr_ty e)
3181
27
{
3182
27
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_genexpr),
3183
27
                                         e->v.GeneratorExp.generators,
3184
27
                                         e->v.GeneratorExp.elt, NULL);
3185
27
}
3186
3187
static int
3188
symtable_visit_listcomp(struct symtable *st, expr_ty e)
3189
44
{
3190
44
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_listcomp),
3191
44
                                         e->v.ListComp.generators,
3192
44
                                         e->v.ListComp.elt, NULL);
3193
44
}
3194
3195
static int
3196
symtable_visit_setcomp(struct symtable *st, expr_ty e)
3197
4
{
3198
4
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_setcomp),
3199
4
                                         e->v.SetComp.generators,
3200
4
                                         e->v.SetComp.elt, NULL);
3201
4
}
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
108
{
3215
108
    _Py_block_ty type = st->st_cur->ste_type;
3216
108
    if (type == AnnotationBlock)
3217
0
        PyErr_Format(PyExc_SyntaxError, ANNOTATION_NOT_ALLOWED, name);
3218
108
    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
108
    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
108
    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
108
    else
3234
108
        return 1;
3235
3236
0
    SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3237
0
    return 0;
3238
108
}
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);
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
105k
{
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
105k
    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
105k
    return _Py_Mangle(privateobj, name);
3308
105k
}
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
109k
{
3334
    /* Name mangling: __private becomes _classname__private.
3335
       This is independent from how the name is used. */
3336
109k
    if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
3337
51.7k
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3338
103k
        PyUnicode_READ_CHAR(ident, 1) != '_') {
3339
103k
        return Py_NewRef(ident);
3340
103k
    }
3341
6.02k
    size_t nlen = PyUnicode_GET_LENGTH(ident);
3342
6.02k
    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
6.02k
    if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3353
5.98k
         PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
3354
5.98k
        PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
3355
5.98k
        return Py_NewRef(ident); /* Don't mangle __whatever__ */
3356
5.98k
    }
3357
    /* Strip leading underscores from class name */
3358
41
    size_t ipriv = 0;
3359
41
    while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_') {
3360
0
        ipriv++;
3361
0
    }
3362
41
    if (ipriv == plen) {
3363
0
        return Py_NewRef(ident); /* Don't mangle if class is just underscores */
3364
0
    }
3365
3366
41
    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
41
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(1 + nlen + (plen - ipriv));
3373
41
    if (!writer) {
3374
0
        return NULL;
3375
0
    }
3376
    // ident = "_" + priv[ipriv:] + ident
3377
41
    if (PyUnicodeWriter_WriteChar(writer, '_') < 0) {
3378
0
        goto error;
3379
0
    }
3380
41
    if (PyUnicodeWriter_WriteSubstring(writer, privateobj, ipriv, plen) < 0) {
3381
0
        goto error;
3382
0
    }
3383
41
    if (PyUnicodeWriter_WriteStr(writer, ident) < 0) {
3384
0
        goto error;
3385
0
    }
3386
41
    return PyUnicodeWriter_Finish(writer);
3387
3388
0
error:
3389
0
    PyUnicodeWriter_Discard(writer);
3390
    return NULL;
3391
41
}