Coverage Report

Created: 2026-09-27 06:15

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