Coverage Report

Created: 2026-06-21 06:15

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