Coverage Report

Created: 2026-07-14 06:16

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.7k
#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.72k
{
96
6.72k
    PySTEntryObject *ste = NULL;
97
6.72k
    PyObject *k = NULL;
98
99
6.72k
    k = PyLong_FromVoidPtr(key);
100
6.72k
    if (k == NULL)
101
0
        goto fail;
102
6.72k
    ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
103
6.72k
    if (ste == NULL) {
104
0
        Py_DECREF(k);
105
0
        goto fail;
106
0
    }
107
6.72k
    ste->ste_table = st;
108
6.72k
    ste->ste_id = k; /* ste owns reference to k */
109
110
6.72k
    ste->ste_name = Py_NewRef(name);
111
6.72k
    ste->ste_function_name = NULL;
112
113
6.72k
    ste->ste_symbols = NULL;
114
6.72k
    ste->ste_varnames = NULL;
115
6.72k
    ste->ste_children = NULL;
116
117
6.72k
    ste->ste_directives = NULL;
118
6.72k
    ste->ste_mangled_names = NULL;
119
120
6.72k
    ste->ste_type = block;
121
6.72k
    ste->ste_scope_info = NULL;
122
123
6.72k
    ste->ste_nested = 0;
124
6.72k
    ste->ste_varargs = 0;
125
6.72k
    ste->ste_varkeywords = 0;
126
6.72k
    ste->ste_annotations_used = 0;
127
6.72k
    ste->ste_loc = loc;
128
129
6.72k
    if (st->st_cur != NULL &&
130
5.97k
        (st->st_cur->ste_nested ||
131
5.96k
         _PyST_IsFunctionLike(st->st_cur)))
132
1.57k
        ste->ste_nested = 1;
133
6.72k
    ste->ste_generator = 0;
134
6.72k
    ste->ste_coroutine = 0;
135
6.72k
    ste->ste_comprehension = NoComprehension;
136
6.72k
    ste->ste_returns_value = 0;
137
6.72k
    ste->ste_needs_class_closure = 0;
138
6.72k
    ste->ste_comp_inlined = 0;
139
6.72k
    ste->ste_comp_iter_target = 0;
140
6.72k
    ste->ste_can_see_class_scope = 0;
141
6.72k
    ste->ste_comp_iter_expr = 0;
142
6.72k
    ste->ste_needs_classdict = 0;
143
6.72k
    ste->ste_has_conditional_annotations = 0;
144
6.72k
    ste->ste_in_conditional_block = 0;
145
6.72k
    ste->ste_in_try_block = 0;
146
6.72k
    ste->ste_in_unevaluated_annotation = 0;
147
6.72k
    ste->ste_annotation_block = NULL;
148
149
6.72k
    ste->ste_has_docstring = 0;
150
151
6.72k
    ste->ste_method = 0;
152
6.72k
    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.72k
    ste->ste_symbols = PyDict_New();
159
6.72k
    ste->ste_varnames = PyList_New(0);
160
6.72k
    ste->ste_children = PyList_New(0);
161
6.72k
    if (ste->ste_symbols == NULL
162
6.72k
        || ste->ste_varnames == NULL
163
6.72k
        || ste->ste_children == NULL)
164
0
        goto fail;
165
166
6.72k
    if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
167
0
        goto fail;
168
169
6.72k
    return ste;
170
0
 fail:
171
0
    Py_XDECREF(ste);
172
0
    return NULL;
173
6.72k
}
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.72k
{
186
6.72k
    PySTEntryObject *ste = (PySTEntryObject *)op;
187
6.72k
    ste->ste_table = NULL;
188
6.72k
    Py_XDECREF(ste->ste_id);
189
6.72k
    Py_XDECREF(ste->ste_name);
190
6.72k
    Py_XDECREF(ste->ste_function_name);
191
6.72k
    Py_XDECREF(ste->ste_symbols);
192
6.72k
    Py_XDECREF(ste->ste_varnames);
193
6.72k
    Py_XDECREF(ste->ste_children);
194
6.72k
    Py_XDECREF(ste->ste_directives);
195
6.72k
    Py_XDECREF(ste->ste_annotation_block);
196
6.72k
    Py_XDECREF(ste->ste_mangled_names);
197
6.72k
    PyObject_Free(ste);
198
6.72k
}
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
745
{
392
745
    struct symtable *st;
393
394
745
    st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
395
745
    if (st == NULL) {
396
0
        PyErr_NoMemory();
397
0
        return NULL;
398
0
    }
399
400
745
    st->st_filename = NULL;
401
745
    st->st_blocks = NULL;
402
403
745
    if ((st->st_stack = PyList_New(0)) == NULL)
404
0
        goto fail;
405
745
    if ((st->st_blocks = PyDict_New()) == NULL)
406
0
        goto fail;
407
745
    st->st_cur = NULL;
408
745
    st->st_private = NULL;
409
745
    return st;
410
0
 fail:
411
0
    _PySymtable_Free(st);
412
0
    return NULL;
413
745
}
414
415
struct symtable *
416
_PySymtable_Build(mod_ty mod, PyObject *filename, _PyFutureFeatures *future)
417
745
{
418
745
    struct symtable *st = symtable_new();
419
745
    asdl_stmt_seq *seq;
420
745
    Py_ssize_t i;
421
745
    PyThreadState *tstate;
422
423
745
    if (st == NULL)
424
0
        return NULL;
425
745
    if (filename == NULL) {
426
0
        _PySymtable_Free(st);
427
0
        return NULL;
428
0
    }
429
745
    st->st_filename = Py_NewRef(filename);
430
745
    st->st_future = future;
431
432
    /* Setup recursion depth check counters */
433
745
    tstate = _PyThreadState_GET();
434
745
    if (!tstate) {
435
0
        _PySymtable_Free(st);
436
0
        return NULL;
437
0
    }
438
439
    /* Make the initial symbol information gathering pass */
440
441
745
    _Py_SourceLocation loc0 = {0, 0, 0, 0};
442
745
    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
745
    st->st_top = st->st_cur;
448
745
    switch (mod->kind) {
449
522
    case Module_kind:
450
522
        seq = mod->v.Module.body;
451
522
        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
522
        break;
459
522
    case Expression_kind:
460
223
        if (!symtable_visit_expr(st, mod->v.Expression.body))
461
0
            goto error;
462
223
        break;
463
223
    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
745
    }
475
745
    if (!symtable_exit_block(st)) {
476
0
        _PySymtable_Free(st);
477
0
        return NULL;
478
0
    }
479
    /* Make the second symbol analysis pass */
480
745
    if (symtable_analyze(st)) {
481
#if _PY_DUMP_SYMTABLE
482
        dump_symtable(st->st_top);
483
#endif
484
745
        return st;
485
745
    }
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
745
}
493
494
495
void
496
_PySymtable_Free(struct symtable *st)
497
745
{
498
745
    Py_XDECREF(st->st_filename);
499
745
    Py_XDECREF(st->st_blocks);
500
745
    Py_XDECREF(st->st_stack);
501
745
    PyMem_Free((void *)st);
502
745
}
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.3k
{
540
47.3k
    PyObject *v;
541
47.3k
    if (PyDict_GetItemRef(ste->ste_symbols, name, &v) < 0) {
542
0
        return -1;
543
0
    }
544
47.3k
    if (!v) {
545
7.52k
        return 0;
546
7.52k
    }
547
39.7k
    long symbol = PyLong_AsLong(v);
548
39.7k
    Py_DECREF(v);
549
39.7k
    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.7k
    return symbol;
556
39.7k
}
557
558
int
559
_PyST_GetScope(PySTEntryObject *ste, PyObject *name)
560
42.5k
{
561
42.5k
    long symbol = _PyST_GetSymbol(ste, name);
562
42.5k
    if (symbol < 0) {
563
0
        return -1;
564
0
    }
565
42.5k
    return SYMBOL_TO_SCOPE(symbol);
566
42.5k
}
567
568
int
569
_PyST_IsFunctionLike(PySTEntryObject *ste)
570
87.4k
{
571
87.4k
    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.4k
}
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.53k
    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.53k
    if (bound) {
761
6.42k
        contains = PySet_Contains(bound, name);
762
6.42k
        if (contains < 0) {
763
0
            return 0;
764
0
        }
765
6.42k
        if (contains) {
766
1.83k
            SET_SCOPE(scopes, name, FREE);
767
1.83k
            return PySet_Add(free, name) >= 0;
768
1.83k
        }
769
6.42k
    }
770
    /* If a parent has a global statement, then call it global
771
       explicit?  It could also be global implicit.
772
     */
773
4.69k
    if (global) {
774
4.69k
        contains = PySet_Contains(global, name);
775
4.69k
        if (contains < 0) {
776
0
            return 0;
777
0
        }
778
4.69k
        if (contains) {
779
3
            SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
780
3
            return 1;
781
3
        }
782
4.69k
    }
783
4.69k
    SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
784
4.69k
    return 1;
785
4.69k
}
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.30k
{
923
5.30k
    PyObject *name, *v, *v_cell;
924
5.30k
    int success = 0;
925
5.30k
    Py_ssize_t pos = 0;
926
927
5.30k
    v_cell = PyLong_FromLong(CELL);
928
5.30k
    if (!v_cell)
929
0
        return 0;
930
24.0k
    while (PyDict_Next(scopes, &pos, &name, &v)) {
931
18.7k
        long scope = PyLong_AsLong(v);
932
18.7k
        if (scope == -1 && PyErr_Occurred()) {
933
0
            goto error;
934
0
        }
935
18.7k
        if (scope != LOCAL)
936
6.29k
            continue;
937
12.4k
        int contains = PySet_Contains(free, name);
938
12.4k
        if (contains < 0) {
939
0
            goto error;
940
0
        }
941
12.4k
        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
516
        if (PyDict_SetItem(scopes, name, v_cell) < 0)
955
0
            goto error;
956
516
        if (PySet_Discard(free, name) < 0)
957
0
            goto error;
958
516
    }
959
5.30k
    success = 1;
960
5.30k
 error:
961
5.30k
    Py_DECREF(v_cell);
962
5.30k
    return success;
963
5.30k
}
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.72k
{
997
6.72k
    PyObject *name = NULL, *itr = NULL;
998
6.72k
    PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
999
6.72k
    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.72k
    v_free = PyLong_FromLong(FREE << SCOPE_OFFSET);
1039
6.72k
    if (!v_free)
1040
0
        return 0;
1041
1042
6.72k
    itr = PyObject_GetIter(free);
1043
6.72k
    if (itr == NULL) {
1044
0
        Py_DECREF(v_free);
1045
0
        return 0;
1046
0
    }
1047
1048
6.72k
    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.72k
    if (PyErr_Occurred()) {
1100
0
        goto error;
1101
0
    }
1102
1103
6.72k
    Py_DECREF(itr);
1104
6.72k
    Py_DECREF(v_free);
1105
6.72k
    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.72k
}
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.72k
{
1143
6.72k
    PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
1144
6.72k
    PyObject *newglobal = NULL, *newfree = NULL, *inlined_cells = NULL;
1145
6.72k
    PyObject *temp;
1146
6.72k
    int success = 0;
1147
6.72k
    Py_ssize_t i, pos = 0;
1148
1149
6.72k
    local = PySet_New(NULL);  /* collect new names bound in block */
1150
6.72k
    if (!local)
1151
0
        goto error;
1152
6.72k
    scopes = PyDict_New();  /* collect scopes defined for each name */
1153
6.72k
    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.72k
    newglobal = PySet_New(NULL);
1168
6.72k
    if (!newglobal)
1169
0
        goto error;
1170
6.72k
    newfree = PySet_New(NULL);
1171
6.72k
    if (!newfree)
1172
0
        goto error;
1173
6.72k
    newbound = PySet_New(NULL);
1174
6.72k
    if (!newbound)
1175
0
        goto error;
1176
6.72k
    inlined_cells = PySet_New(NULL);
1177
6.72k
    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.72k
    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.72k
    if (ste->ste_type != ClassBlock) {
1212
        /* Add function locals to bound set */
1213
6.05k
        if (_PyST_IsFunctionLike(ste)) {
1214
5.30k
            temp = PyNumber_InPlaceOr(newbound, local);
1215
5.30k
            if (!temp)
1216
0
                goto error;
1217
5.30k
            Py_DECREF(temp);
1218
5.30k
        }
1219
        /* Pass down previously bound symbols */
1220
6.05k
        if (bound) {
1221
5.30k
            temp = PyNumber_InPlaceOr(newbound, bound);
1222
5.30k
            if (!temp)
1223
0
                goto error;
1224
5.30k
            Py_DECREF(temp);
1225
5.30k
        }
1226
        /* Pass down known globals */
1227
6.05k
        temp = PyNumber_InPlaceOr(newglobal, global);
1228
6.05k
        if (!temp)
1229
0
            goto error;
1230
6.05k
        Py_DECREF(temp);
1231
6.05k
    }
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.97k
        PyObject *child_free = NULL;
1250
5.97k
        PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
1251
5.97k
        PySTEntryObject* entry;
1252
5.97k
        assert(c && PySTEntry_Check(c));
1253
5.97k
        entry = (PySTEntryObject*)c;
1254
1255
5.97k
        PySTEntryObject *new_class_entry = NULL;
1256
5.97k
        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.97k
        int inline_comp =
1268
5.97k
            entry->ste_comprehension &&
1269
76
            !entry->ste_generator &&
1270
50
            !ste->ste_can_see_class_scope;
1271
1272
5.97k
        if (!analyze_child_block(entry, newbound, newfree, newglobal,
1273
5.97k
                                 type_params, new_class_entry, &child_free))
1274
0
        {
1275
0
            goto error;
1276
0
        }
1277
5.97k
        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.97k
        temp = PyNumber_InPlaceOr(newfree, child_free);
1285
5.97k
        Py_DECREF(child_free);
1286
5.97k
        if (!temp)
1287
0
            goto error;
1288
5.97k
        Py_DECREF(temp);
1289
5.97k
    }
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.97k
        PyObject* c = PyList_GET_ITEM(ste->ste_children, i);
1294
5.97k
        PySTEntryObject* entry;
1295
5.97k
        assert(c && PySTEntry_Check(c));
1296
5.97k
        entry = (PySTEntryObject*)c;
1297
5.97k
        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.97k
    }
1304
1305
    /* Check if any local variables must be converted to cell variables */
1306
6.72k
    if (_PyST_IsFunctionLike(ste) && !analyze_cells(scopes, newfree, inlined_cells))
1307
0
        goto error;
1308
6.72k
    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.72k
    if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, inlined_cells,
1312
6.72k
                        (ste->ste_type == ClassBlock) || ste->ste_can_see_class_scope))
1313
0
        goto error;
1314
1315
6.72k
    temp = PyNumber_InPlaceOr(free, newfree);
1316
6.72k
    if (!temp)
1317
0
        goto error;
1318
6.72k
    Py_DECREF(temp);
1319
6.72k
    success = 1;
1320
6.72k
 error:
1321
6.72k
    Py_XDECREF(scopes);
1322
6.72k
    Py_XDECREF(local);
1323
6.72k
    Py_XDECREF(newbound);
1324
6.72k
    Py_XDECREF(newglobal);
1325
6.72k
    Py_XDECREF(newfree);
1326
6.72k
    Py_XDECREF(inlined_cells);
1327
6.72k
    if (!success)
1328
6.72k
        assert(PyErr_Occurred());
1329
6.72k
    return success;
1330
6.72k
}
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.97k
{
1337
5.97k
    PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
1338
5.97k
    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.97k
    temp_bound = PySet_New(bound);
1348
5.97k
    if (!temp_bound)
1349
0
        goto error;
1350
5.97k
    temp_free = PySet_New(free);
1351
5.97k
    if (!temp_free)
1352
0
        goto error;
1353
5.97k
    temp_global = PySet_New(global);
1354
5.97k
    if (!temp_global)
1355
0
        goto error;
1356
5.97k
    temp_type_params = PySet_New(type_params);
1357
5.97k
    if (!temp_type_params)
1358
0
        goto error;
1359
1360
5.97k
    if (!analyze_block(entry, temp_bound, temp_free, temp_global,
1361
5.97k
                       temp_type_params, class_entry))
1362
0
        goto error;
1363
5.97k
    *child_free = temp_free;
1364
5.97k
    Py_DECREF(temp_bound);
1365
5.97k
    Py_DECREF(temp_global);
1366
5.97k
    Py_DECREF(temp_type_params);
1367
5.97k
    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.97k
}
1375
1376
static int
1377
symtable_analyze(struct symtable *st)
1378
745
{
1379
745
    PyObject *free, *global, *type_params;
1380
745
    int r;
1381
1382
745
    free = PySet_New(NULL);
1383
745
    if (!free)
1384
0
        return 0;
1385
745
    global = PySet_New(NULL);
1386
745
    if (!global) {
1387
0
        Py_DECREF(free);
1388
0
        return 0;
1389
0
    }
1390
745
    type_params = PySet_New(NULL);
1391
745
    if (!type_params) {
1392
0
        Py_DECREF(free);
1393
0
        Py_DECREF(global);
1394
0
        return 0;
1395
0
    }
1396
745
    r = analyze_block(st->st_top, NULL, free, global, type_params, NULL);
1397
745
    Py_DECREF(free);
1398
745
    Py_DECREF(global);
1399
745
    Py_DECREF(type_params);
1400
745
    return r;
1401
745
}
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
0
        return 1;
1451
0
    }
1452
1453
6.88k
    if (ste->ste_type == ModuleBlock)
1454
745
        st->st_global = st->st_cur->ste_symbols;
1455
1456
6.88k
    if (add_to_children && prev) {
1457
5.97k
        if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) {
1458
0
            return 0;
1459
0
        }
1460
5.97k
    }
1461
6.88k
    return 1;
1462
6.88k
}
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.51k
        _Py_DECLARE_STR(format, ".format");
1475
        // We need to insert code that reads this "parameter" to the function.
1476
2.51k
        if (!symtable_add_def(st, &_Py_STR(format), DEF_PARAM, loc)) {
1477
0
            return 0;
1478
0
        }
1479
2.51k
        if (!symtable_add_def(st, &_Py_STR(format), USE, loc)) {
1480
0
            return 0;
1481
0
        }
1482
2.51k
    }
1483
4.23k
    return result;
1484
4.23k
}
1485
1486
static long
1487
symtable_lookup_entry(struct symtable *st, PySTEntryObject *ste, PyObject *name)
1488
192
{
1489
192
    PyObject *mangled = _Py_MaybeMangle(st->st_private, ste, name);
1490
192
    if (!mangled)
1491
0
        return -1;
1492
192
    long ret = _PyST_GetSymbol(ste, mangled);
1493
192
    Py_DECREF(mangled);
1494
192
    if (ret < 0) {
1495
0
        return -1;
1496
0
    }
1497
192
    return ret;
1498
192
}
1499
1500
static long
1501
symtable_lookup(struct symtable *st, PyObject *name)
1502
192
{
1503
192
    return symtable_lookup_entry(st, st->st_cur, name);
1504
192
}
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.1k
{
1510
49.1k
    PyObject *o;
1511
49.1k
    PyObject *dict;
1512
49.1k
    long val;
1513
49.1k
    PyObject *mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1514
1515
49.1k
    if (!mangled)
1516
0
        return 0;
1517
49.1k
    dict = ste->ste_symbols;
1518
49.1k
    if ((o = PyDict_GetItemWithError(dict, mangled))) {
1519
26.3k
        val = PyLong_AsLong(o);
1520
26.3k
        if (val == -1 && PyErr_Occurred()) {
1521
0
            goto error;
1522
0
        }
1523
26.3k
        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.3k
        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.3k
        val |= flag;
1535
26.3k
    }
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.1k
    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.1k
    o = PyLong_FromLong(val);
1557
49.1k
    if (o == NULL)
1558
0
        goto error;
1559
49.1k
    if (PyDict_SetItem(dict, mangled, o) < 0) {
1560
0
        Py_DECREF(o);
1561
0
        goto error;
1562
0
    }
1563
49.1k
    Py_DECREF(o);
1564
1565
49.1k
    if (flag & DEF_PARAM) {
1566
9.86k
        if (PyList_Append(ste->ste_varnames, mangled) < 0)
1567
0
            goto error;
1568
39.3k
    } 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.1k
    Py_DECREF(mangled);
1592
49.1k
    return 1;
1593
1594
0
error:
1595
0
    Py_DECREF(mangled);
1596
0
    return 0;
1597
49.1k
}
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.78k
{
1619
9.50k
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(keywords); i++) {
1620
1.72k
        keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
1621
1.72k
        if (key->arg  && !check_name(st, key->arg, LOCATION(key), Store)) {
1622
0
            return 0;
1623
0
        }
1624
1.72k
    }
1625
7.78k
    return 1;
1626
7.78k
}
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.1k
{
1647
49.1k
    int write_mask = DEF_PARAM | DEF_LOCAL | DEF_IMPORT;
1648
49.1k
    if ((flag & write_mask) && !check_name(st, name, loc, ctx)) {
1649
0
        return 0;
1650
0
    }
1651
49.1k
    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.1k
    return symtable_add_def_helper(st, name, flag, st->st_cur, loc);
1657
49.1k
}
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.8k
    do { \
1732
43.8k
        if (!symtable_visit_ ## TYPE((ST), (V))) { \
1733
0
            return 0; \
1734
0
        } \
1735
43.8k
    } while(0)
1736
1737
#define VISIT_SEQ(ST, TYPE, SEQ) \
1738
27.1k
    do { \
1739
27.1k
        Py_ssize_t i; \
1740
27.1k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1741
75.4k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1742
48.2k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1743
48.2k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1744
48.2k
                return 0;                 \
1745
48.2k
        } \
1746
27.1k
    } 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.95k
    do { \
1761
9.95k
        int i = 0; \
1762
9.95k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1763
18.8k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1764
8.92k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1765
8.92k
            if (!elt) continue; /* can be NULL */ \
1766
8.92k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1767
8.91k
                return 0;             \
1768
8.91k
        } \
1769
9.95k
    } while(0)
1770
1771
#define ENTER_CONDITIONAL_BLOCK(ST) \
1772
2.52k
    int in_conditional_block = (ST)->st_cur->ste_in_conditional_block; \
1773
2.52k
    (ST)->st_cur->ste_in_conditional_block = 1;
1774
1775
#define LEAVE_CONDITIONAL_BLOCK(ST) \
1776
2.52k
    (ST)->st_cur->ste_in_conditional_block = in_conditional_block;
1777
1778
#define ENTER_TRY_BLOCK(ST) \
1779
209
    int in_try_block = (ST)->st_cur->ste_in_try_block; \
1780
209
    (ST)->st_cur->ste_in_try_block = 1;
1781
1782
#define LEAVE_TRY_BLOCK(ST) \
1783
209
    (ST)->st_cur->ste_in_try_block = in_try_block;
1784
1785
98.5k
#define ENTER_RECURSIVE() \
1786
98.5k
if (Py_EnterRecursiveCall(" during compilation")) { \
1787
0
    return 0; \
1788
0
}
1789
1790
98.5k
#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
262
{
1830
262
    assert(s->kind == ImportFrom_kind);
1831
262
    _Py_SourceLocation fut = st->st_future->ff_location;
1832
262
    if (s->v.ImportFrom.module && s->v.ImportFrom.level == 0 &&
1833
237
        _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__") &&
1834
0
        ((s->lineno > fut.lineno) ||
1835
0
         ((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
262
    return 1;
1844
262
}
1845
1846
static int
1847
check_lazy_import_context(struct symtable *st, stmt_ty s,
1848
                          const char* import_type)
1849
3
{
1850
    // Check if inside try/except block.
1851
3
    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
3
    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
3
    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
3
    return 1;
1876
3
}
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.7k
{
1897
15.7k
    ENTER_RECURSIVE();
1898
15.7k
    switch (s->kind) {
1899
2.48k
    case FunctionDef_kind: {
1900
2.48k
        if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL, LOCATION(s)))
1901
0
            return 0;
1902
2.48k
        if (s->v.FunctionDef.args->defaults)
1903
2.48k
            VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
1904
2.48k
        if (s->v.FunctionDef.args->kw_defaults)
1905
2.48k
            VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults);
1906
2.48k
        if (s->v.FunctionDef.decorator_list)
1907
142
            VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
1908
2.48k
        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.48k
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
1922
2.48k
                                           LOCATION(s));
1923
2.48k
        if (!new_ste) {
1924
0
            return 0;
1925
0
        }
1926
1927
2.48k
        if (_PyAST_GetDocString(s->v.FunctionDef.body)) {
1928
294
            new_ste->ste_has_docstring = 1;
1929
294
        }
1930
1931
2.48k
        if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args,
1932
2.48k
                                        s->v.FunctionDef.returns, new_ste)) {
1933
0
            Py_DECREF(new_ste);
1934
0
            return 0;
1935
0
        }
1936
2.48k
        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.48k
        Py_DECREF(new_ste);
1941
2.48k
        VISIT(st, arguments, s->v.FunctionDef.args);
1942
2.48k
        VISIT_SEQ(st, stmt, s->v.FunctionDef.body);
1943
2.48k
        if (!symtable_exit_block(st))
1944
0
            return 0;
1945
2.48k
        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.48k
        break;
1950
2.48k
    }
1951
2.48k
    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
1
    case TypeAlias_kind: {
2009
1
        VISIT(st, expr, s->v.TypeAlias.name);
2010
1
        assert(s->v.TypeAlias.name->kind == Name_kind);
2011
1
        PyObject *name = s->v.TypeAlias.name->v.Name.id;
2012
1
        int is_in_class = st->st_cur->ste_type == ClassBlock;
2013
1
        int is_generic = asdl_seq_LEN(s->v.TypeAlias.type_params) > 0;
2014
1
        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
1
        if (!symtable_enter_block(st, name, TypeAliasBlock,
2025
1
                                  (void *)s, LOCATION(s))) {
2026
0
            return 0;
2027
0
        }
2028
1
        st->st_cur->ste_can_see_class_scope = is_in_class;
2029
1
        if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(s->v.TypeAlias.value))) {
2030
0
            return 0;
2031
0
        }
2032
1
        VISIT(st, expr, s->v.TypeAlias.value);
2033
1
        if (!symtable_exit_block(st))
2034
0
            return 0;
2035
1
        if (is_generic) {
2036
0
            if (!symtable_exit_block(st))
2037
0
                return 0;
2038
0
        }
2039
1
        break;
2040
1
    }
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.52k
    case Assign_kind:
2051
3.52k
        VISIT_SEQ(st, expr, s->v.Assign.targets);
2052
3.52k
        VISIT(st, expr, s->v.Assign.value);
2053
3.52k
        break;
2054
3.52k
    case AnnAssign_kind:
2055
183
        st->st_cur->ste_annotations_used = 1;
2056
183
        if (s->v.AnnAssign.target->kind == Name_kind) {
2057
183
            expr_ty e_name = s->v.AnnAssign.target;
2058
183
            long cur = symtable_lookup(st, e_name->v.Name.id);
2059
183
            if (cur < 0) {
2060
0
                return 0;
2061
0
            }
2062
183
            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
183
            if (s->v.AnnAssign.simple &&
2072
183
                !symtable_add_def(st, e_name->v.Name.id,
2073
183
                                  DEF_ANNOT | DEF_LOCAL, LOCATION(e_name))) {
2074
0
                return 0;
2075
0
            }
2076
183
            else {
2077
183
                if (s->v.AnnAssign.value
2078
180
                    && !symtable_add_def(st, e_name->v.Name.id, DEF_LOCAL, LOCATION(e_name))) {
2079
0
                    return 0;
2080
0
                }
2081
183
            }
2082
183
        }
2083
0
        else {
2084
0
            VISIT(st, expr, s->v.AnnAssign.target);
2085
0
        }
2086
183
        if (!symtable_visit_annotation(st, s->v.AnnAssign.annotation,
2087
183
                                       (void *)((uintptr_t)st->st_cur->ste_id + 1))) {
2088
0
            return 0;
2089
0
        }
2090
2091
183
        if (s->v.AnnAssign.value) {
2092
180
            VISIT(st, expr, s->v.AnnAssign.value);
2093
180
        }
2094
183
        break;
2095
183
    case AugAssign_kind: {
2096
131
        VISIT(st, expr, s->v.AugAssign.target);
2097
131
        VISIT(st, expr, s->v.AugAssign.value);
2098
131
        break;
2099
131
    }
2100
253
    case For_kind: {
2101
253
        VISIT(st, expr, s->v.For.target);
2102
253
        VISIT(st, expr, s->v.For.iter);
2103
253
        ENTER_CONDITIONAL_BLOCK(st);
2104
253
        VISIT_SEQ(st, stmt, s->v.For.body);
2105
253
        if (s->v.For.orelse)
2106
2
            VISIT_SEQ(st, stmt, s->v.For.orelse);
2107
253
        LEAVE_CONDITIONAL_BLOCK(st);
2108
253
        break;
2109
253
    }
2110
55
    case While_kind: {
2111
55
        VISIT(st, expr, s->v.While.test);
2112
55
        ENTER_CONDITIONAL_BLOCK(st);
2113
55
        VISIT_SEQ(st, stmt, s->v.While.body);
2114
55
        if (s->v.While.orelse)
2115
0
            VISIT_SEQ(st, stmt, s->v.While.orelse);
2116
55
        LEAVE_CONDITIONAL_BLOCK(st);
2117
55
        break;
2118
55
    }
2119
1.92k
    case If_kind: {
2120
        /* XXX if 0: and lookup_yield() hacks */
2121
1.92k
        VISIT(st, expr, s->v.If.test);
2122
1.92k
        ENTER_CONDITIONAL_BLOCK(st);
2123
1.92k
        VISIT_SEQ(st, stmt, s->v.If.body);
2124
1.92k
        if (s->v.If.orelse)
2125
495
            VISIT_SEQ(st, stmt, s->v.If.orelse);
2126
1.92k
        LEAVE_CONDITIONAL_BLOCK(st);
2127
1.92k
        break;
2128
1.92k
    }
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
366
    case Raise_kind:
2137
366
        if (s->v.Raise.exc) {
2138
336
            VISIT(st, expr, s->v.Raise.exc);
2139
336
            if (s->v.Raise.cause) {
2140
21
                VISIT(st, expr, s->v.Raise.cause);
2141
21
            }
2142
336
        }
2143
366
        break;
2144
366
    case Try_kind: {
2145
209
        ENTER_CONDITIONAL_BLOCK(st);
2146
209
        ENTER_TRY_BLOCK(st);
2147
209
        VISIT_SEQ(st, stmt, s->v.Try.body);
2148
209
        VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
2149
209
        VISIT_SEQ(st, stmt, s->v.Try.orelse);
2150
209
        VISIT_SEQ(st, stmt, s->v.Try.finalbody);
2151
209
        LEAVE_TRY_BLOCK(st);
2152
209
        LEAVE_CONDITIONAL_BLOCK(st);
2153
209
        break;
2154
209
    }
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
262
        if (s->v.ImportFrom.is_lazy) {
2181
3
            if (!check_lazy_import_context(st, s, "from ... import")) {
2182
0
                return 0;
2183
0
            }
2184
2185
            // Check for import *
2186
10
            for (Py_ssize_t i = 0; i < asdl_seq_LEN(s->v.ImportFrom.names);
2187
7
                 i++) {
2188
7
                alias_ty alias = (alias_ty)asdl_seq_GET(
2189
7
                    s->v.ImportFrom.names, i);
2190
7
                if (alias->name &&
2191
7
                        _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
7
            }
2198
3
        }
2199
262
        VISIT_SEQ(st, alias, s->v.ImportFrom.names);
2200
262
        if (!check_import_from(st, s)) {
2201
0
            return 0;
2202
0
        }
2203
262
        break;
2204
262
    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.64k
    case Expr_kind:
2269
2.64k
        VISIT(st, expr, s->v.Expr.value);
2270
2.64k
        break;
2271
2.64k
    case Pass_kind:
2272
233
    case Break_kind:
2273
272
    case Continue_kind:
2274
        /* nothing to do here */
2275
272
        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.7k
    }
2364
15.7k
    LEAVE_RECURSIVE();
2365
15.7k
    return 1;
2366
15.7k
}
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
82.7k
{
2487
82.7k
    ENTER_RECURSIVE();
2488
82.7k
    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
500
    case BoolOp_kind:
2497
500
        VISIT_SEQ(st, expr, e->v.BoolOp.values);
2498
500
        break;
2499
670
    case BinOp_kind:
2500
670
        VISIT(st, expr, e->v.BinOp.left);
2501
670
        VISIT(st, expr, e->v.BinOp.right);
2502
670
        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
231
        if (e->v.Lambda.args->defaults)
2508
231
            VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
2509
231
        if (e->v.Lambda.args->kw_defaults)
2510
231
            VISIT_SEQ_WITH_NULL(st, expr, e->v.Lambda.args->kw_defaults);
2511
231
        if (!symtable_enter_block(st, &_Py_STR(anon_lambda),
2512
231
                                  FunctionBlock, (void *)e, LOCATION(e))) {
2513
0
            return 0;
2514
0
        }
2515
231
        VISIT(st, arguments, e->v.Lambda.args);
2516
231
        VISIT(st, expr, e->v.Lambda.body);
2517
231
        if (!symtable_exit_block(st))
2518
0
            return 0;
2519
231
        break;
2520
231
    }
2521
231
    case IfExp_kind:
2522
76
        VISIT(st, expr, e->v.IfExp.test);
2523
76
        VISIT(st, expr, e->v.IfExp.body);
2524
76
        VISIT(st, expr, e->v.IfExp.orelse);
2525
76
        break;
2526
119
    case Dict_kind:
2527
119
        VISIT_SEQ_WITH_NULL(st, expr, e->v.Dict.keys);
2528
119
        VISIT_SEQ(st, expr, e->v.Dict.values);
2529
119
        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.10k
    case Compare_kind:
2592
2.10k
        VISIT(st, expr, e->v.Compare.left);
2593
2.10k
        VISIT_SEQ(st, expr, e->v.Compare.comparators);
2594
2.10k
        break;
2595
7.11k
    case Call_kind:
2596
7.11k
        VISIT(st, expr, e->v.Call.func);
2597
7.11k
        VISIT_SEQ(st, expr, e->v.Call.args);
2598
7.11k
        if (!check_keywords(st, e->v.Call.keywords)) {
2599
0
            return 0;
2600
0
        }
2601
7.11k
        VISIT_SEQ_WITH_NULL(st, keyword, e->v.Call.keywords);
2602
7.11k
        break;
2603
7.11k
    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
444
    case JoinedStr_kind:
2614
444
        VISIT_SEQ(st, expr, e->v.JoinedStr.values);
2615
444
        break;
2616
444
    case TemplateStr_kind:
2617
1
        VISIT_SEQ(st, expr, e->v.TemplateStr.values);
2618
1
        break;
2619
23.4k
    case Constant_kind:
2620
        /* Nothing to do here. */
2621
23.4k
        break;
2622
    /* The following exprs can be assignment targets. */
2623
11.0k
    case Attribute_kind:
2624
11.0k
        if (!check_name(st, e->v.Attribute.attr, LOCATION(e), e->v.Attribute.ctx)) {
2625
0
            return 0;
2626
0
        }
2627
11.0k
        VISIT(st, expr, e->v.Attribute.value);
2628
11.0k
        break;
2629
11.0k
    case Subscript_kind:
2630
804
        VISIT(st, expr, e->v.Subscript.value);
2631
804
        VISIT(st, expr, e->v.Subscript.slice);
2632
804
        break;
2633
804
    case Starred_kind:
2634
102
        VISIT(st, expr, e->v.Starred.value);
2635
102
        break;
2636
113
    case Slice_kind:
2637
113
        if (e->v.Slice.lower)
2638
66
            VISIT(st, expr, e->v.Slice.lower);
2639
113
        if (e->v.Slice.upper)
2640
73
            VISIT(st, expr, e->v.Slice.upper);
2641
113
        if (e->v.Slice.step)
2642
0
            VISIT(st, expr, e->v.Slice.step);
2643
113
        break;
2644
31.3k
    case Name_kind:
2645
31.3k
        if (!st->st_cur->ste_in_unevaluated_annotation) {
2646
31.2k
            if (!symtable_add_def_ctx(st, e->v.Name.id,
2647
31.2k
                                    e->v.Name.ctx == Load ? USE : DEF_LOCAL,
2648
31.2k
                                    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.2k
            if (e->v.Name.ctx == Load &&
2653
27.9k
                _PyST_IsFunctionLike(st->st_cur) &&
2654
25.8k
                _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.2k
        }
2659
31.3k
        break;
2660
    /* child nodes of List and Tuple will have expr_context set */
2661
31.3k
    case List_kind:
2662
153
        VISIT_SEQ(st, expr, e->v.List.elts);
2663
153
        break;
2664
1.00k
    case Tuple_kind:
2665
1.00k
        VISIT_SEQ(st, expr, e->v.Tuple.elts);
2666
1.00k
        break;
2667
82.7k
    }
2668
82.7k
    LEAVE_RECURSIVE();
2669
82.7k
    return 1;
2670
82.7k
}
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
        if (error_msg == NULL) {
2682
0
            return 0;
2683
0
        }
2684
0
        PyErr_SetObject(PyExc_SyntaxError, error_msg);
2685
0
        Py_DECREF(error_msg);
2686
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(tp));
2687
0
        return 0;
2688
0
    }
2689
2690
0
    if (e) {
2691
0
        int is_in_class = st->st_cur->ste_can_see_class_scope;
2692
0
        if (!symtable_enter_block(st, name, TypeVariableBlock, (void *)tp, LOCATION(e))) {
2693
0
            return 0;
2694
0
        }
2695
2696
0
        st->st_cur->ste_can_see_class_scope = is_in_class;
2697
0
        if (is_in_class && !symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(e))) {
2698
0
            return 0;
2699
0
        }
2700
2701
0
        assert(ste_scope_info != NULL);
2702
0
        st->st_cur->ste_scope_info = ste_scope_info;
2703
0
        VISIT(st, expr, e);
2704
2705
0
        if (!symtable_exit_block(st)) {
2706
0
            return 0;
2707
0
        }
2708
0
    }
2709
0
    return 1;
2710
0
}
2711
2712
static int
2713
symtable_visit_type_param(struct symtable *st, type_param_ty tp)
2714
0
{
2715
0
    ENTER_RECURSIVE();
2716
0
    switch(tp->kind) {
2717
0
    case TypeVar_kind:
2718
0
        if (!symtable_add_def(st, tp->v.TypeVar.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp)))
2719
0
            return 0;
2720
2721
0
        const char *ste_scope_info = NULL;
2722
0
        const expr_ty bound = tp->v.TypeVar.bound;
2723
0
        if (bound != NULL) {
2724
0
            ste_scope_info = bound->kind == Tuple_kind ? "a TypeVar constraint" : "a TypeVar bound";
2725
0
        }
2726
2727
        // We must use a different key for the bound and default. The obvious choice would be to
2728
        // use the .bound and .default_value pointers, but that fails when the expression immediately
2729
        // inside the bound or default is a comprehension: we would reuse the same key for
2730
        // the comprehension scope. Therefore, use the address + 1 as the second key.
2731
        // The only requirement for the key is that it is unique and it matches the logic in
2732
        // compile.c where the scope is retrieved.
2733
0
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVar.bound, tp->v.TypeVar.name,
2734
0
                                                        tp, ste_scope_info)) {
2735
0
            return 0;
2736
0
        }
2737
2738
0
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVar.default_value, tp->v.TypeVar.name,
2739
0
                                                        (type_param_ty)((uintptr_t)tp + 1), "a TypeVar default")) {
2740
0
            return 0;
2741
0
        }
2742
0
        break;
2743
0
    case TypeVarTuple_kind:
2744
0
        if (!symtable_add_def(st, tp->v.TypeVarTuple.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) {
2745
0
            return 0;
2746
0
        }
2747
2748
0
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.TypeVarTuple.default_value, tp->v.TypeVarTuple.name,
2749
0
                                                        tp, "a TypeVarTuple default")) {
2750
0
            return 0;
2751
0
        }
2752
0
        break;
2753
0
    case ParamSpec_kind:
2754
0
        if (!symtable_add_def(st, tp->v.ParamSpec.name, DEF_TYPE_PARAM | DEF_LOCAL, LOCATION(tp))) {
2755
0
            return 0;
2756
0
        }
2757
2758
0
        if (!symtable_visit_type_param_bound_or_default(st, tp->v.ParamSpec.default_value, tp->v.ParamSpec.name,
2759
0
                                                        tp, "a ParamSpec default")) {
2760
0
            return 0;
2761
0
        }
2762
0
        break;
2763
0
    }
2764
0
    LEAVE_RECURSIVE();
2765
0
    return 1;
2766
0
}
2767
2768
static int
2769
symtable_visit_pattern(struct symtable *st, pattern_ty p)
2770
0
{
2771
0
    ENTER_RECURSIVE();
2772
0
    switch (p->kind) {
2773
0
    case MatchValue_kind:
2774
0
        VISIT(st, expr, p->v.MatchValue.value);
2775
0
        break;
2776
0
    case MatchSingleton_kind:
2777
        /* Nothing to do here. */
2778
0
        break;
2779
0
    case MatchSequence_kind:
2780
0
        VISIT_SEQ(st, pattern, p->v.MatchSequence.patterns);
2781
0
        break;
2782
0
    case MatchStar_kind:
2783
0
        if (p->v.MatchStar.name) {
2784
0
            if (!symtable_add_def(st, p->v.MatchStar.name, DEF_LOCAL, LOCATION(p))) {
2785
0
                return 0;
2786
0
            }
2787
0
        }
2788
0
        break;
2789
0
    case MatchMapping_kind:
2790
0
        VISIT_SEQ(st, expr, p->v.MatchMapping.keys);
2791
0
        VISIT_SEQ(st, pattern, p->v.MatchMapping.patterns);
2792
0
        if (p->v.MatchMapping.rest) {
2793
0
            if (!symtable_add_def(st, p->v.MatchMapping.rest, DEF_LOCAL, LOCATION(p))) {
2794
0
                return 0;
2795
0
            }
2796
0
        }
2797
0
        break;
2798
0
    case MatchClass_kind:
2799
0
        VISIT(st, expr, p->v.MatchClass.cls);
2800
0
        VISIT_SEQ(st, pattern, p->v.MatchClass.patterns);
2801
0
        if (!check_kwd_patterns(st, p)) {
2802
0
            return 0;
2803
0
        }
2804
0
        VISIT_SEQ(st, pattern, p->v.MatchClass.kwd_patterns);
2805
0
        break;
2806
0
    case MatchAs_kind:
2807
0
        if (p->v.MatchAs.pattern) {
2808
0
            VISIT(st, pattern, p->v.MatchAs.pattern);
2809
0
        }
2810
0
        if (p->v.MatchAs.name) {
2811
0
            if (!symtable_add_def(st, p->v.MatchAs.name, DEF_LOCAL, LOCATION(p))) {
2812
0
                return 0;
2813
0
            }
2814
0
        }
2815
0
        break;
2816
0
    case MatchOr_kind:
2817
0
        VISIT_SEQ(st, pattern, p->v.MatchOr.patterns);
2818
0
        break;
2819
0
    }
2820
0
    LEAVE_RECURSIVE();
2821
0
    return 1;
2822
0
}
2823
2824
static int
2825
symtable_implicit_arg(struct symtable *st, int pos)
2826
76
{
2827
76
    PyObject *id = PyUnicode_FromFormat(".%d", pos);
2828
76
    if (id == NULL)
2829
0
        return 0;
2830
76
    if (!symtable_add_def(st, id, DEF_PARAM, st->st_cur->ste_loc)) {
2831
0
        Py_DECREF(id);
2832
0
        return 0;
2833
0
    }
2834
76
    Py_DECREF(id);
2835
76
    return 1;
2836
76
}
2837
2838
static int
2839
symtable_visit_params(struct symtable *st, asdl_arg_seq *args)
2840
8.15k
{
2841
8.15k
    Py_ssize_t i;
2842
2843
15.2k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2844
7.10k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2845
7.10k
        if (!symtable_add_def(st, arg->arg, DEF_PARAM, LOCATION(arg)))
2846
0
            return 0;
2847
7.10k
    }
2848
2849
8.15k
    return 1;
2850
8.15k
}
2851
2852
static int
2853
symtable_visit_annotation(struct symtable *st, expr_ty annotation, void *key)
2854
183
{
2855
    // Annotations in local scopes are not executed and should not affect the symtable
2856
183
    bool is_unevaluated = st->st_cur->ste_type == FunctionBlock;
2857
2858
    // Module-level annotations are always considered conditional because the module
2859
    // may be partially executed.
2860
183
    if ((((st->st_cur->ste_type == ClassBlock && st->st_cur->ste_in_conditional_block)
2861
183
            || st->st_cur->ste_type == ModuleBlock))
2862
1
            && !st->st_cur->ste_has_conditional_annotations)
2863
1
    {
2864
1
        st->st_cur->ste_has_conditional_annotations = 1;
2865
1
        if (!symtable_add_def(st, &_Py_ID(__conditional_annotations__), USE, LOCATION(annotation))) {
2866
0
            return 0;
2867
0
        }
2868
1
    }
2869
183
    struct _symtable_entry *parent_ste = st->st_cur;
2870
183
    if (parent_ste->ste_annotation_block == NULL) {
2871
23
        _Py_block_ty current_type = parent_ste->ste_type;
2872
23
        if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2873
23
                                    key, LOCATION(annotation))) {
2874
0
            return 0;
2875
0
        }
2876
23
        parent_ste->ste_annotation_block =
2877
23
            (struct _symtable_entry *)Py_NewRef(st->st_cur);
2878
23
        int future_annotations = st->st_future->ff_features & CO_FUTURE_ANNOTATIONS;
2879
23
        if (current_type == ClassBlock && !future_annotations) {
2880
20
            st->st_cur->ste_can_see_class_scope = 1;
2881
20
            parent_ste->ste_needs_classdict = 1;
2882
20
            if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(annotation))) {
2883
0
                return 0;
2884
0
            }
2885
20
        }
2886
23
    }
2887
160
    else {
2888
160
        if (!symtable_enter_existing_block(st, parent_ste->ste_annotation_block,
2889
160
                                           /* add_to_children */false)) {
2890
0
            return 0;
2891
0
        }
2892
160
    }
2893
183
    if (is_unevaluated) {
2894
2
        st->st_cur->ste_in_unevaluated_annotation = 1;
2895
2
    }
2896
183
    int rc = symtable_visit_expr(st, annotation);
2897
183
    if (is_unevaluated) {
2898
2
        st->st_cur->ste_in_unevaluated_annotation = 0;
2899
2
    }
2900
183
    if (!symtable_exit_block(st)) {
2901
0
        return 0;
2902
0
    }
2903
183
    return rc;
2904
183
}
2905
2906
static int
2907
symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args)
2908
7.46k
{
2909
7.46k
    Py_ssize_t i;
2910
2911
13.5k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2912
6.06k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2913
6.06k
        if (arg->annotation) {
2914
46
            st->st_cur->ste_annotations_used = 1;
2915
46
            VISIT(st, expr, arg->annotation);
2916
46
        }
2917
6.06k
    }
2918
2919
7.46k
    return 1;
2920
7.46k
}
2921
2922
static int
2923
symtable_visit_annotations(struct symtable *st, stmt_ty o, arguments_ty a, expr_ty returns,
2924
                           struct _symtable_entry *function_ste)
2925
2.48k
{
2926
2.48k
    int is_in_class = st->st_cur->ste_can_see_class_scope;
2927
2.48k
    _Py_block_ty current_type = st->st_cur->ste_type;
2928
2.48k
    if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2929
2.48k
                              (void *)a, LOCATION(o))) {
2930
0
        return 0;
2931
0
    }
2932
2.48k
    Py_XSETREF(st->st_cur->ste_function_name, Py_NewRef(function_ste->ste_name));
2933
2.48k
    if (is_in_class || current_type == ClassBlock) {
2934
1.09k
        st->st_cur->ste_can_see_class_scope = 1;
2935
1.09k
        if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(o))) {
2936
0
            return 0;
2937
0
        }
2938
1.09k
    }
2939
2.48k
    if (a->posonlyargs && !symtable_visit_argannotations(st, a->posonlyargs))
2940
0
        return 0;
2941
2.48k
    if (a->args && !symtable_visit_argannotations(st, a->args))
2942
0
        return 0;
2943
2.48k
    if (a->vararg && a->vararg->annotation) {
2944
0
        st->st_cur->ste_annotations_used = 1;
2945
0
        VISIT(st, expr, a->vararg->annotation);
2946
0
    }
2947
2.48k
    if (a->kwarg && a->kwarg->annotation) {
2948
1
        st->st_cur->ste_annotations_used = 1;
2949
1
        VISIT(st, expr, a->kwarg->annotation);
2950
1
    }
2951
2.48k
    if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs))
2952
0
        return 0;
2953
2.48k
    if (returns) {
2954
30
        st->st_cur->ste_annotations_used = 1;
2955
30
        VISIT(st, expr, returns);
2956
30
    }
2957
2.48k
    if (!symtable_exit_block(st)) {
2958
0
        return 0;
2959
0
    }
2960
2.48k
    return 1;
2961
2.48k
}
2962
2963
static int
2964
symtable_visit_arguments(struct symtable *st, arguments_ty a)
2965
2.71k
{
2966
    /* skip default arguments inside function block
2967
       XXX should ast be different?
2968
    */
2969
2.71k
    if (a->posonlyargs && !symtable_visit_params(st, a->posonlyargs))
2970
0
        return 0;
2971
2.71k
    if (a->args && !symtable_visit_params(st, a->args))
2972
0
        return 0;
2973
2.71k
    if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs))
2974
0
        return 0;
2975
2.71k
    if (a->vararg) {
2976
81
        if (!symtable_add_def(st, a->vararg->arg, DEF_PARAM, LOCATION(a->vararg)))
2977
0
            return 0;
2978
81
        st->st_cur->ste_varargs = 1;
2979
81
    }
2980
2.71k
    if (a->kwarg) {
2981
84
        if (!symtable_add_def(st, a->kwarg->arg, DEF_PARAM, LOCATION(a->kwarg)))
2982
0
            return 0;
2983
84
        st->st_cur->ste_varkeywords = 1;
2984
84
    }
2985
2.71k
    return 1;
2986
2.71k
}
2987
2988
2989
static int
2990
symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
2991
225
{
2992
225
    if (eh->v.ExceptHandler.type)
2993
211
        VISIT(st, expr, eh->v.ExceptHandler.type);
2994
225
    if (eh->v.ExceptHandler.name)
2995
30
        if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL, LOCATION(eh)))
2996
0
            return 0;
2997
225
    VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
2998
225
    return 1;
2999
225
}
3000
3001
static int
3002
symtable_visit_withitem(struct symtable *st, withitem_ty item)
3003
90
{
3004
90
    VISIT(st, expr, item->context_expr);
3005
90
    if (item->optional_vars) {
3006
30
        VISIT(st, expr, item->optional_vars);
3007
30
    }
3008
90
    return 1;
3009
90
}
3010
3011
static int
3012
symtable_visit_match_case(struct symtable *st, match_case_ty m)
3013
0
{
3014
0
    VISIT(st, pattern, m->pattern);
3015
0
    if (m->guard) {
3016
0
        VISIT(st, expr, m->guard);
3017
0
    }
3018
0
    VISIT_SEQ(st, stmt, m->body);
3019
0
    return 1;
3020
0
}
3021
3022
static int
3023
symtable_visit_alias(struct symtable *st, alias_ty a)
3024
701
{
3025
    /* Compute store_name, the name actually bound by the import
3026
       operation.  It is different than a->name when a->name is a
3027
       dotted package name (e.g. spam.eggs)
3028
    */
3029
701
    PyObject *store_name;
3030
701
    PyObject *name = (a->asname == NULL) ? a->name : a->asname;
3031
701
    Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
3032
701
                                        PyUnicode_GET_LENGTH(name), 1);
3033
701
    if (dot != -1) {
3034
5
        store_name = PyUnicode_Substring(name, 0, dot);
3035
5
        if (!store_name)
3036
0
            return 0;
3037
5
    }
3038
696
    else {
3039
696
        store_name = Py_NewRef(name);
3040
696
    }
3041
701
    if (!_PyUnicode_EqualToASCIIString(name, "*")) {
3042
699
        int r = symtable_add_def(st, store_name, DEF_IMPORT, LOCATION(a));
3043
699
        Py_DECREF(store_name);
3044
699
        return r;
3045
699
    }
3046
2
    else {
3047
2
        if (st->st_cur->ste_type != ModuleBlock) {
3048
0
            PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING);
3049
0
            SET_ERROR_LOCATION(st->st_filename, LOCATION(a));
3050
0
            Py_DECREF(store_name);
3051
0
            return 0;
3052
0
        }
3053
2
        Py_DECREF(store_name);
3054
2
        return 1;
3055
2
    }
3056
701
}
3057
3058
3059
static int
3060
symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
3061
0
{
3062
0
    st->st_cur->ste_comp_iter_target = 1;
3063
0
    VISIT(st, expr, lc->target);
3064
0
    st->st_cur->ste_comp_iter_target = 0;
3065
0
    st->st_cur->ste_comp_iter_expr++;
3066
0
    VISIT(st, expr, lc->iter);
3067
0
    st->st_cur->ste_comp_iter_expr--;
3068
0
    VISIT_SEQ(st, expr, lc->ifs);
3069
0
    if (lc->is_async) {
3070
0
        st->st_cur->ste_coroutine = 1;
3071
0
    }
3072
0
    return 1;
3073
0
}
3074
3075
3076
static int
3077
symtable_visit_keyword(struct symtable *st, keyword_ty k)
3078
1.72k
{
3079
1.72k
    VISIT(st, expr, k->value);
3080
1.72k
    return 1;
3081
1.72k
}
3082
3083
3084
static int
3085
symtable_handle_comprehension(struct symtable *st, expr_ty e,
3086
                              identifier scope_name, asdl_comprehension_seq *generators,
3087
                              expr_ty elt, expr_ty value)
3088
76
{
3089
76
    int is_generator = (e->kind == GeneratorExp_kind);
3090
76
    comprehension_ty outermost = ((comprehension_ty)
3091
76
                                    asdl_seq_GET(generators, 0));
3092
    /* Outermost iterator is evaluated in current scope */
3093
76
    st->st_cur->ste_comp_iter_expr++;
3094
76
    VISIT(st, expr, outermost->iter);
3095
76
    st->st_cur->ste_comp_iter_expr--;
3096
    /* Create comprehension scope for the rest */
3097
76
    if (!scope_name ||
3098
76
        !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, LOCATION(e))) {
3099
0
        return 0;
3100
0
    }
3101
76
    switch(e->kind) {
3102
41
        case ListComp_kind:
3103
41
            st->st_cur->ste_comprehension = ListComprehension;
3104
41
            break;
3105
4
        case SetComp_kind:
3106
4
            st->st_cur->ste_comprehension = SetComprehension;
3107
4
            break;
3108
5
        case DictComp_kind:
3109
5
            st->st_cur->ste_comprehension = DictComprehension;
3110
5
            break;
3111
26
        default:
3112
26
            st->st_cur->ste_comprehension = GeneratorExpression;
3113
26
            break;
3114
76
    }
3115
76
    if (outermost->is_async) {
3116
0
        st->st_cur->ste_coroutine = 1;
3117
0
    }
3118
3119
    /* Outermost iter is received as an argument */
3120
76
    if (!symtable_implicit_arg(st, 0)) {
3121
0
        symtable_exit_block(st);
3122
0
        return 0;
3123
0
    }
3124
    /* Visit iteration variable target, and mark them as such */
3125
76
    st->st_cur->ste_comp_iter_target = 1;
3126
76
    VISIT(st, expr, outermost->target);
3127
76
    st->st_cur->ste_comp_iter_target = 0;
3128
    /* Visit the rest of the comprehension body */
3129
76
    VISIT_SEQ(st, expr, outermost->ifs);
3130
76
    VISIT_SEQ_TAIL(st, comprehension, generators, 1);
3131
76
    if (value)
3132
5
        VISIT(st, expr, value);
3133
76
    VISIT(st, expr, elt);
3134
76
    st->st_cur->ste_generator = is_generator;
3135
76
    int is_async = st->st_cur->ste_coroutine && !is_generator;
3136
76
    if (!symtable_exit_block(st)) {
3137
0
        return 0;
3138
0
    }
3139
76
    if (is_async &&
3140
0
        !IS_ASYNC_DEF(st) &&
3141
0
        st->st_cur->ste_comprehension == NoComprehension &&
3142
0
        !allows_top_level_await(st))
3143
0
    {
3144
0
        PyErr_SetString(PyExc_SyntaxError, "asynchronous comprehension outside of "
3145
0
                                           "an asynchronous function");
3146
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3147
0
        return 0;
3148
0
    }
3149
76
    if (is_async) {
3150
0
        st->st_cur->ste_coroutine = 1;
3151
0
    }
3152
76
    return 1;
3153
76
}
3154
3155
static int
3156
symtable_visit_genexp(struct symtable *st, expr_ty e)
3157
26
{
3158
26
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_genexpr),
3159
26
                                         e->v.GeneratorExp.generators,
3160
26
                                         e->v.GeneratorExp.elt, NULL);
3161
26
}
3162
3163
static int
3164
symtable_visit_listcomp(struct symtable *st, expr_ty e)
3165
41
{
3166
41
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_listcomp),
3167
41
                                         e->v.ListComp.generators,
3168
41
                                         e->v.ListComp.elt, NULL);
3169
41
}
3170
3171
static int
3172
symtable_visit_setcomp(struct symtable *st, expr_ty e)
3173
4
{
3174
4
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_setcomp),
3175
4
                                         e->v.SetComp.generators,
3176
4
                                         e->v.SetComp.elt, NULL);
3177
4
}
3178
3179
static int
3180
symtable_visit_dictcomp(struct symtable *st, expr_ty e)
3181
5
{
3182
5
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_dictcomp),
3183
5
                                         e->v.DictComp.generators,
3184
5
                                         e->v.DictComp.key,
3185
5
                                         e->v.DictComp.value);
3186
5
}
3187
3188
static int
3189
symtable_raise_if_annotation_block(struct symtable *st, const char *name, expr_ty e)
3190
108
{
3191
108
    _Py_block_ty type = st->st_cur->ste_type;
3192
108
    if (type == AnnotationBlock)
3193
0
        PyErr_Format(PyExc_SyntaxError, ANNOTATION_NOT_ALLOWED, name);
3194
108
    else if (type == TypeVariableBlock) {
3195
0
        const char *info = st->st_cur->ste_scope_info;
3196
0
        assert(info != NULL); // e.g., info == "a ParamSpec default"
3197
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_VARIABLE, name, info);
3198
0
    }
3199
108
    else if (type == TypeAliasBlock) {
3200
        // for now, we do not have any extra information
3201
0
        assert(st->st_cur->ste_scope_info == NULL);
3202
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_ALIAS, name);
3203
0
    }
3204
108
    else if (type == TypeParametersBlock) {
3205
        // for now, we do not have any extra information
3206
0
        assert(st->st_cur->ste_scope_info == NULL);
3207
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_PARAMETERS, name);
3208
0
    }
3209
108
    else
3210
108
        return 1;
3211
3212
0
    SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3213
0
    return 0;
3214
108
}
3215
3216
static int
3217
0
symtable_raise_if_comprehension_block(struct symtable *st, expr_ty e) {
3218
0
    _Py_comprehension_ty type = st->st_cur->ste_comprehension;
3219
0
    PyErr_SetString(PyExc_SyntaxError,
3220
0
            (type == ListComprehension) ? "'yield' inside list comprehension" :
3221
0
            (type == SetComprehension) ? "'yield' inside set comprehension" :
3222
0
            (type == DictComprehension) ? "'yield' inside dict comprehension" :
3223
0
            "'yield' inside generator expression");
3224
0
    SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3225
0
    return 0;
3226
0
}
3227
3228
static int
3229
0
symtable_raise_if_not_coroutine(struct symtable *st, const char *msg, _Py_SourceLocation loc) {
3230
0
    if (!st->st_cur->ste_coroutine) {
3231
0
        PyErr_SetString(PyExc_SyntaxError, msg);
3232
0
        SET_ERROR_LOCATION(st->st_filename, loc);
3233
0
        return 0;
3234
0
    }
3235
0
    return 1;
3236
0
}
3237
3238
struct symtable *
3239
_Py_SymtableStringObjectFlags(const char *str, PyObject *filename,
3240
                              int start, PyCompilerFlags *flags, PyObject *module)
3241
0
{
3242
0
    struct symtable *st;
3243
0
    mod_ty mod;
3244
0
    PyArena *arena;
3245
3246
0
    arena = _PyArena_New();
3247
0
    if (arena == NULL)
3248
0
        return NULL;
3249
3250
0
    mod = _PyParser_ASTFromString(str, filename, start, flags, arena, module);
3251
0
    if (mod == NULL) {
3252
0
        _PyArena_Free(arena);
3253
0
        return NULL;
3254
0
    }
3255
0
    _PyFutureFeatures future;
3256
0
    if (!_PyFuture_FromAST(mod, filename, &future)) {
3257
0
        _PyArena_Free(arena);
3258
0
        return NULL;
3259
0
    }
3260
0
    future.ff_features |= flags->cf_flags;
3261
0
    st = _PySymtable_Build(mod, filename, &future);
3262
0
    _PyArena_Free(arena);
3263
0
    return st;
3264
0
}
3265
3266
PyObject *
3267
_Py_MaybeMangle(PyObject *privateobj, PySTEntryObject *ste, PyObject *name)
3268
101k
{
3269
    /* Special case for type parameter blocks around generic classes:
3270
     * we want to mangle type parameter names (so a type param with a private
3271
     * name can be used inside the class body), but we don't want to mangle
3272
     * any other names that appear within the type parameter scope.
3273
     */
3274
101k
    if (ste->ste_mangled_names != NULL) {
3275
0
        int result = PySet_Contains(ste->ste_mangled_names, name);
3276
0
        if (result < 0) {
3277
0
            return NULL;
3278
0
        }
3279
0
        if (result == 0) {
3280
0
            return Py_NewRef(name);
3281
0
        }
3282
0
    }
3283
101k
    return _Py_Mangle(privateobj, name);
3284
101k
}
3285
3286
int
3287
_Py_IsPrivateName(PyObject *ident)
3288
0
{
3289
0
    if (!PyUnicode_Check(ident)) {
3290
0
        return 0;
3291
0
    }
3292
0
    Py_ssize_t nlen = PyUnicode_GET_LENGTH(ident);
3293
0
    if (nlen < 3 ||
3294
0
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3295
0
        PyUnicode_READ_CHAR(ident, 1) != '_')
3296
0
    {
3297
0
        return 0;
3298
0
    }
3299
0
    if (PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3300
0
        PyUnicode_READ_CHAR(ident, nlen-2) == '_')
3301
0
    {
3302
0
        return 0; /* Don't mangle __whatever__ */
3303
0
    }
3304
0
    return 1;
3305
0
}
3306
3307
PyObject *
3308
_Py_Mangle(PyObject *privateobj, PyObject *ident)
3309
106k
{
3310
    /* Name mangling: __private becomes _classname__private.
3311
       This is independent from how the name is used. */
3312
106k
    if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
3313
51.5k
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3314
100k
        PyUnicode_READ_CHAR(ident, 1) != '_') {
3315
100k
        return Py_NewRef(ident);
3316
100k
    }
3317
6.00k
    size_t nlen = PyUnicode_GET_LENGTH(ident);
3318
6.00k
    size_t plen = PyUnicode_GET_LENGTH(privateobj);
3319
    /* Don't mangle __id__ or names with dots.
3320
3321
       The only time a name with a dot can occur is when
3322
       we are compiling an import statement that has a
3323
       package name.
3324
3325
       TODO(jhylton): Decide whether we want to support
3326
       mangling of the module name, e.g. __M.X.
3327
    */
3328
6.00k
    if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3329
5.96k
         PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
3330
5.96k
        PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
3331
5.96k
        return Py_NewRef(ident); /* Don't mangle __whatever__ */
3332
5.96k
    }
3333
    /* Strip leading underscores from class name */
3334
41
    size_t ipriv = 0;
3335
41
    while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_') {
3336
0
        ipriv++;
3337
0
    }
3338
41
    if (ipriv == plen) {
3339
0
        return Py_NewRef(ident); /* Don't mangle if class is just underscores */
3340
0
    }
3341
3342
41
    if (nlen + (plen - ipriv) >= PY_SSIZE_T_MAX - 1) {
3343
0
        PyErr_SetString(PyExc_OverflowError,
3344
0
                        "private identifier too large to be mangled");
3345
0
        return NULL;
3346
0
    }
3347
3348
41
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(1 + nlen + (plen - ipriv));
3349
41
    if (!writer) {
3350
0
        return NULL;
3351
0
    }
3352
    // ident = "_" + priv[ipriv:] + ident
3353
41
    if (PyUnicodeWriter_WriteChar(writer, '_') < 0) {
3354
0
        goto error;
3355
0
    }
3356
41
    if (PyUnicodeWriter_WriteSubstring(writer, privateobj, ipriv, plen) < 0) {
3357
0
        goto error;
3358
0
    }
3359
41
    if (PyUnicodeWriter_WriteStr(writer, ident) < 0) {
3360
0
        goto error;
3361
0
    }
3362
41
    return PyUnicodeWriter_Finish(writer);
3363
3364
0
error:
3365
0
    PyUnicodeWriter_Discard(writer);
3366
    return NULL;
3367
41
}