Coverage Report

Created: 2026-02-26 06:53

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