Coverage Report

Created: 2026-06-09 06:53

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