Coverage Report

Created: 2026-12-01 06:09

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