Coverage Report

Created: 2026-08-28 06:28

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