Coverage Report

Created: 2026-04-20 06:11

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
94.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
341
#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
9.32k
{
96
9.32k
    PySTEntryObject *ste = NULL;
97
9.32k
    PyObject *k = NULL;
98
99
9.32k
    k = PyLong_FromVoidPtr(key);
100
9.32k
    if (k == NULL)
101
0
        goto fail;
102
9.32k
    ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
103
9.32k
    if (ste == NULL) {
104
0
        Py_DECREF(k);
105
0
        goto fail;
106
0
    }
107
9.32k
    ste->ste_table = st;
108
9.32k
    ste->ste_id = k; /* ste owns reference to k */
109
110
9.32k
    ste->ste_name = Py_NewRef(name);
111
9.32k
    ste->ste_function_name = NULL;
112
113
9.32k
    ste->ste_symbols = NULL;
114
9.32k
    ste->ste_varnames = NULL;
115
9.32k
    ste->ste_children = NULL;
116
117
9.32k
    ste->ste_directives = NULL;
118
9.32k
    ste->ste_mangled_names = NULL;
119
120
9.32k
    ste->ste_type = block;
121
9.32k
    ste->ste_scope_info = NULL;
122
123
9.32k
    ste->ste_nested = 0;
124
9.32k
    ste->ste_varargs = 0;
125
9.32k
    ste->ste_varkeywords = 0;
126
9.32k
    ste->ste_annotations_used = 0;
127
9.32k
    ste->ste_loc = loc;
128
129
9.32k
    if (st->st_cur != NULL &&
130
8.46k
        (st->st_cur->ste_nested ||
131
8.44k
         _PyST_IsFunctionLike(st->st_cur)))
132
2.28k
        ste->ste_nested = 1;
133
9.32k
    ste->ste_generator = 0;
134
9.32k
    ste->ste_coroutine = 0;
135
9.32k
    ste->ste_comprehension = NoComprehension;
136
9.32k
    ste->ste_returns_value = 0;
137
9.32k
    ste->ste_needs_class_closure = 0;
138
9.32k
    ste->ste_comp_inlined = 0;
139
9.32k
    ste->ste_comp_iter_target = 0;
140
9.32k
    ste->ste_can_see_class_scope = 0;
141
9.32k
    ste->ste_comp_iter_expr = 0;
142
9.32k
    ste->ste_needs_classdict = 0;
143
9.32k
    ste->ste_has_conditional_annotations = 0;
144
9.32k
    ste->ste_in_conditional_block = 0;
145
9.32k
    ste->ste_in_try_block = 0;
146
9.32k
    ste->ste_in_unevaluated_annotation = 0;
147
9.32k
    ste->ste_annotation_block = NULL;
148
149
9.32k
    ste->ste_has_docstring = 0;
150
151
9.32k
    ste->ste_method = 0;
152
9.32k
    if (st->st_cur != NULL &&
153
8.46k
        st->st_cur->ste_type == ClassBlock &&
154
3.61k
        block == FunctionBlock) {
155
1.80k
        ste->ste_method = 1;
156
1.80k
    }
157
158
9.32k
    ste->ste_symbols = PyDict_New();
159
9.32k
    ste->ste_varnames = PyList_New(0);
160
9.32k
    ste->ste_children = PyList_New(0);
161
9.32k
    if (ste->ste_symbols == NULL
162
9.32k
        || ste->ste_varnames == NULL
163
9.32k
        || ste->ste_children == NULL)
164
0
        goto fail;
165
166
9.32k
    if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0)
167
0
        goto fail;
168
169
9.32k
    return ste;
170
0
 fail:
171
0
    Py_XDECREF(ste);
172
0
    return NULL;
173
9.32k
}
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
9.32k
{
186
9.32k
    PySTEntryObject *ste = (PySTEntryObject *)op;
187
9.32k
    ste->ste_table = NULL;
188
9.32k
    Py_XDECREF(ste->ste_id);
189
9.32k
    Py_XDECREF(ste->ste_name);
190
9.32k
    Py_XDECREF(ste->ste_function_name);
191
9.32k
    Py_XDECREF(ste->ste_symbols);
192
9.32k
    Py_XDECREF(ste->ste_varnames);
193
9.32k
    Py_XDECREF(ste->ste_children);
194
9.32k
    Py_XDECREF(ste->ste_directives);
195
9.32k
    Py_XDECREF(ste->ste_annotation_block);
196
9.32k
    Py_XDECREF(ste->ste_mangled_names);
197
9.32k
    PyObject_Free(ste);
198
9.32k
}
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
856
{
392
856
    struct symtable *st;
393
394
856
    st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
395
856
    if (st == NULL) {
396
0
        PyErr_NoMemory();
397
0
        return NULL;
398
0
    }
399
400
856
    st->st_filename = NULL;
401
856
    st->st_blocks = NULL;
402
403
856
    if ((st->st_stack = PyList_New(0)) == NULL)
404
0
        goto fail;
405
856
    if ((st->st_blocks = PyDict_New()) == NULL)
406
0
        goto fail;
407
856
    st->st_cur = NULL;
408
856
    st->st_private = NULL;
409
856
    return st;
410
0
 fail:
411
0
    _PySymtable_Free(st);
412
0
    return NULL;
413
856
}
414
415
struct symtable *
416
_PySymtable_Build(mod_ty mod, PyObject *filename, _PyFutureFeatures *future)
417
856
{
418
856
    struct symtable *st = symtable_new();
419
856
    asdl_stmt_seq *seq;
420
856
    Py_ssize_t i;
421
856
    PyThreadState *tstate;
422
423
856
    if (st == NULL)
424
0
        return NULL;
425
856
    if (filename == NULL) {
426
0
        _PySymtable_Free(st);
427
0
        return NULL;
428
0
    }
429
856
    st->st_filename = Py_NewRef(filename);
430
856
    st->st_future = future;
431
432
    /* Setup recursion depth check counters */
433
856
    tstate = _PyThreadState_GET();
434
856
    if (!tstate) {
435
0
        _PySymtable_Free(st);
436
0
        return NULL;
437
0
    }
438
439
    /* Make the initial symbol information gathering pass */
440
441
856
    _Py_SourceLocation loc0 = {0, 0, 0, 0};
442
856
    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
856
    st->st_top = st->st_cur;
448
856
    switch (mod->kind) {
449
605
    case Module_kind:
450
605
        seq = mod->v.Module.body;
451
605
        if (_PyAST_GetDocString(seq)) {
452
119
            st->st_cur->ste_has_docstring = 1;
453
119
        }
454
3.61k
        for (i = 0; i < asdl_seq_LEN(seq); i++)
455
3.01k
            if (!symtable_visit_stmt(st,
456
3.01k
                        (stmt_ty)asdl_seq_GET(seq, i)))
457
0
                goto error;
458
605
        break;
459
605
    case Expression_kind:
460
251
        if (!symtable_visit_expr(st, mod->v.Expression.body))
461
0
            goto error;
462
251
        break;
463
251
    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
856
    }
475
856
    if (!symtable_exit_block(st)) {
476
0
        _PySymtable_Free(st);
477
0
        return NULL;
478
0
    }
479
    /* Make the second symbol analysis pass */
480
856
    if (symtable_analyze(st)) {
481
#if _PY_DUMP_SYMTABLE
482
        dump_symtable(st->st_top);
483
#endif
484
856
        return st;
485
856
    }
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
856
}
493
494
495
void
496
_PySymtable_Free(struct symtable *st)
497
856
{
498
856
    Py_XDECREF(st->st_filename);
499
856
    Py_XDECREF(st->st_blocks);
500
856
    Py_XDECREF(st->st_stack);
501
856
    PyMem_Free((void *)st);
502
856
}
503
504
PySTEntryObject *
505
_PySymtable_Lookup(struct symtable *st, void *key)
506
5.75k
{
507
5.75k
    PyObject *k, *v;
508
509
5.75k
    k = PyLong_FromVoidPtr(key);
510
5.75k
    if (k == NULL)
511
0
        return NULL;
512
5.75k
    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.75k
    Py_DECREF(k);
517
518
5.75k
    assert(v == NULL || PySTEntry_Check(v));
519
5.75k
    return (PySTEntryObject *)v;
520
5.75k
}
521
522
int
523
_PySymtable_LookupOptional(struct symtable *st, void *key,
524
                           PySTEntryObject **out)
525
3.67k
{
526
3.67k
    PyObject *k = PyLong_FromVoidPtr(key);
527
3.67k
    if (k == NULL) {
528
0
        *out = NULL;
529
0
        return -1;
530
0
    }
531
3.67k
    int result = PyDict_GetItemRef(st->st_blocks, k, (PyObject **)out);
532
3.67k
    Py_DECREF(k);
533
3.67k
    assert(*out == NULL || PySTEntry_Check(*out));
534
3.67k
    return result;
535
3.67k
}
536
537
long
538
_PyST_GetSymbol(PySTEntryObject *ste, PyObject *name)
539
69.6k
{
540
69.6k
    PyObject *v;
541
69.6k
    if (PyDict_GetItemRef(ste->ste_symbols, name, &v) < 0) {
542
0
        return -1;
543
0
    }
544
69.6k
    if (!v) {
545
10.3k
        return 0;
546
10.3k
    }
547
59.3k
    long symbol = PyLong_AsLong(v);
548
59.3k
    Py_DECREF(v);
549
59.3k
    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
59.3k
    return symbol;
556
59.3k
}
557
558
int
559
_PyST_GetScope(PySTEntryObject *ste, PyObject *name)
560
62.3k
{
561
62.3k
    long symbol = _PyST_GetSymbol(ste, name);
562
62.3k
    if (symbol < 0) {
563
0
        return -1;
564
0
    }
565
62.3k
    return SYMBOL_TO_SCOPE(symbol);
566
62.3k
}
567
568
int
569
_PyST_IsFunctionLike(PySTEntryObject *ste)
570
128k
{
571
128k
    return ste->ste_type == FunctionBlock
572
27.2k
        || ste->ste_type == AnnotationBlock
573
19.5k
        || ste->ste_type == TypeVariableBlock
574
19.5k
        || ste->ste_type == TypeAliasBlock
575
19.5k
        || ste->ste_type == TypeParametersBlock;
576
128k
}
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
32.9k
    do { \
651
32.9k
        PyObject *o = PyLong_FromLong(I); \
652
32.9k
        if (!o) \
653
32.9k
            return 0; \
654
32.9k
        if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
655
0
            Py_DECREF(o); \
656
0
            return 0; \
657
0
        } \
658
32.9k
        Py_DECREF(o); \
659
32.9k
    } while(0)
660
661
/* Decide on scope of name, given flags.
662
663
   The namespace dictionaries may be modified to record information
664
   about the new name.  For example, a new global will add an entry to
665
   global.  A name that was global can be changed to local.
666
*/
667
668
static int
669
analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags,
670
             PyObject *bound, PyObject *local, PyObject *free,
671
             PyObject *global, PyObject *type_params, PySTEntryObject *class_entry)
672
32.9k
{
673
32.9k
    int contains;
674
32.9k
    if (flags & DEF_GLOBAL) {
675
20
        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
20
        SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
682
20
        if (PySet_Add(global, name) < 0)
683
0
            return 0;
684
20
        if (bound && (PySet_Discard(bound, name) < 0))
685
0
            return 0;
686
20
        return 1;
687
20
    }
688
32.9k
    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
32.9k
    if (flags & DEF_BOUND) {
719
23.5k
        SET_SCOPE(scopes, name, LOCAL);
720
23.5k
        if (PySet_Add(local, name) < 0)
721
0
            return 0;
722
23.5k
        if (PySet_Discard(global, name) < 0)
723
0
            return 0;
724
23.5k
        if (flags & DEF_TYPE_PARAM) {
725
0
            if (PySet_Add(type_params, name) < 0)
726
0
                return 0;
727
0
        }
728
23.5k
        else {
729
23.5k
            if (PySet_Discard(type_params, name) < 0)
730
0
                return 0;
731
23.5k
        }
732
23.5k
        return 1;
733
23.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.37k
    if (class_entry != NULL) {
742
1.85k
        long class_flags = _PyST_GetSymbol(class_entry, name);
743
1.85k
        if (class_flags < 0) {
744
0
            return 0;
745
0
        }
746
1.85k
        if (class_flags & DEF_GLOBAL) {
747
0
            SET_SCOPE(scopes, name, GLOBAL_EXPLICIT);
748
0
            return 1;
749
0
        }
750
1.85k
        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.85k
    }
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.37k
    if (bound) {
761
9.21k
        contains = PySet_Contains(bound, name);
762
9.21k
        if (contains < 0) {
763
0
            return 0;
764
0
        }
765
9.21k
        if (contains) {
766
2.95k
            SET_SCOPE(scopes, name, FREE);
767
2.95k
            return PySet_Add(free, name) >= 0;
768
2.95k
        }
769
9.21k
    }
770
    /* If a parent has a global statement, then call it global
771
       explicit?  It could also be global implicit.
772
     */
773
6.41k
    if (global) {
774
6.41k
        contains = PySet_Contains(global, name);
775
6.41k
        if (contains < 0) {
776
0
            return 0;
777
0
        }
778
6.41k
        if (contains) {
779
4
            SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
780
4
            return 1;
781
4
        }
782
6.41k
    }
783
6.41k
    SET_SCOPE(scopes, name, GLOBAL_IMPLICIT);
784
6.41k
    return 1;
785
6.41k
}
786
787
static int
788
is_free_in_any_child(PySTEntryObject *entry, PyObject *key)
789
44
{
790
44
    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
44
    return 0;
802
44
}
803
804
static int
805
inline_comprehension(PySTEntryObject *ste, PySTEntryObject *comp,
806
                     PyObject *scopes, PyObject *comp_free,
807
                     PyObject *inlined_cells)
808
55
{
809
55
    PyObject *k, *v;
810
55
    Py_ssize_t pos = 0;
811
55
    int remove_dunder_class = 0;
812
55
    int remove_dunder_classdict = 0;
813
55
    int remove_dunder_cond_annotations = 0;
814
815
226
    while (PyDict_Next(comp->ste_symbols, &pos, &k, &v)) {
816
        // skip comprehension parameter
817
171
        long comp_flags = PyLong_AsLong(v);
818
171
        if (comp_flags == -1 && PyErr_Occurred()) {
819
0
            return 0;
820
0
        }
821
171
        if (comp_flags & DEF_PARAM) {
822
55
            assert(_PyUnicode_EqualToASCIIString(k, ".0"));
823
55
            continue;
824
55
        }
825
116
        int scope = SYMBOL_TO_SCOPE(comp_flags);
826
116
        int only_flags = comp_flags & ((1 << SCOPE_OFFSET) - 1);
827
116
        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
116
        PyObject *existing = PyDict_GetItemWithError(ste->ste_symbols, k);
833
116
        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
116
        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
116
        if (!existing) {
859
            // name does not exist in scope, copy from comprehension
860
68
            assert(scope != FREE || PySet_Contains(comp_free, k) == 1);
861
68
            PyObject *v_flags = PyLong_FromLong(only_flags);
862
68
            if (v_flags == NULL) {
863
0
                return 0;
864
0
            }
865
68
            int ok = PyDict_SetItem(ste->ste_symbols, k, v_flags);
866
68
            Py_DECREF(v_flags);
867
68
            if (ok < 0) {
868
0
                return 0;
869
0
            }
870
68
            SET_SCOPE(scopes, k, scope);
871
68
        }
872
48
        else {
873
48
            long flags = PyLong_AsLong(existing);
874
48
            if (flags == -1 && PyErr_Occurred()) {
875
0
                return 0;
876
0
            }
877
48
            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
44
                int ok = is_free_in_any_child(comp, k);
882
44
                if (ok < 0) {
883
0
                    return 0;
884
0
                }
885
44
                if (!ok) {
886
44
                    if (PySet_Discard(comp_free, k) < 0) {
887
0
                        return 0;
888
0
                    }
889
44
                }
890
44
            }
891
48
        }
892
116
    }
893
55
    if (remove_dunder_class && PyDict_DelItemString(comp->ste_symbols, "__class__") < 0) {
894
0
        return 0;
895
0
    }
896
55
    if (remove_dunder_classdict && PyDict_DelItemString(comp->ste_symbols, "__classdict__") < 0) {
897
0
        return 0;
898
0
    }
899
55
    if (remove_dunder_cond_annotations && PyDict_DelItemString(comp->ste_symbols, "__conditional_annotations__") < 0) {
900
0
        return 0;
901
0
    }
902
55
    return 1;
903
55
}
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.72k
{
918
7.72k
    PyObject *name, *v, *v_cell;
919
7.72k
    int success = 0;
920
7.72k
    Py_ssize_t pos = 0;
921
922
7.72k
    v_cell = PyLong_FromLong(CELL);
923
7.72k
    if (!v_cell)
924
0
        return 0;
925
35.3k
    while (PyDict_Next(scopes, &pos, &name, &v)) {
926
27.6k
        long scope = PyLong_AsLong(v);
927
27.6k
        if (scope == -1 && PyErr_Occurred()) {
928
0
            goto error;
929
0
        }
930
27.6k
        if (scope != LOCAL)
931
9.08k
            continue;
932
18.5k
        int contains = PySet_Contains(free, name);
933
18.5k
        if (contains < 0) {
934
0
            goto error;
935
0
        }
936
18.5k
        if (!contains) {
937
17.7k
            contains = PySet_Contains(inlined_cells, name);
938
17.7k
            if (contains < 0) {
939
0
                goto error;
940
0
            }
941
17.7k
            if (!contains) {
942
17.7k
                continue;
943
17.7k
            }
944
17.7k
        }
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
783
        if (PyDict_SetItem(scopes, name, v_cell) < 0)
950
0
            goto error;
951
783
        if (PySet_Discard(free, name) < 0)
952
0
            goto error;
953
783
    }
954
7.72k
    success = 1;
955
7.72k
 error:
956
7.72k
    Py_DECREF(v_cell);
957
7.72k
    return success;
958
7.72k
}
959
960
static int
961
drop_class_free(PySTEntryObject *ste, PyObject *free)
962
741
{
963
741
    int res;
964
741
    res = PySet_Discard(free, &_Py_ID(__class__));
965
741
    if (res < 0)
966
0
        return 0;
967
741
    if (res)
968
36
        ste->ste_needs_class_closure = 1;
969
741
    res = PySet_Discard(free, &_Py_ID(__classdict__));
970
741
    if (res < 0)
971
0
        return 0;
972
741
    if (res)
973
406
        ste->ste_needs_classdict = 1;
974
741
    res = PySet_Discard(free, &_Py_ID(__conditional_annotations__));
975
741
    if (res < 0)
976
0
        return 0;
977
741
    if (res) {
978
0
        ste->ste_has_conditional_annotations = 1;
979
0
    }
980
741
    return 1;
981
741
}
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
9.32k
{
992
9.32k
    PyObject *name = NULL, *itr = NULL;
993
9.32k
    PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL;
994
9.32k
    Py_ssize_t pos = 0;
995
996
    /* Update scope information for all symbols in this scope */
997
42.3k
    while (PyDict_Next(symbols, &pos, &name, &v)) {
998
32.9k
        long flags = PyLong_AsLong(v);
999
32.9k
        if (flags == -1 && PyErr_Occurred()) {
1000
0
            return 0;
1001
0
        }
1002
32.9k
        int contains = PySet_Contains(inlined_cells, name);
1003
32.9k
        if (contains < 0) {
1004
0
            return 0;
1005
0
        }
1006
32.9k
        if (contains) {
1007
0
            flags |= DEF_COMP_CELL;
1008
0
        }
1009
32.9k
        if (PyDict_GetItemRef(scopes, name, &v_scope) < 0) {
1010
0
            return 0;
1011
0
        }
1012
32.9k
        if (!v_scope) {
1013
0
            PyErr_SetObject(PyExc_KeyError, name);
1014
0
            return 0;
1015
0
        }
1016
32.9k
        long scope = PyLong_AsLong(v_scope);
1017
32.9k
        Py_DECREF(v_scope);
1018
32.9k
        if (scope == -1 && PyErr_Occurred()) {
1019
0
            return 0;
1020
0
        }
1021
32.9k
        flags |= (scope << SCOPE_OFFSET);
1022
32.9k
        v_new = PyLong_FromLong(flags);
1023
32.9k
        if (!v_new)
1024
0
            return 0;
1025
32.9k
        if (PyDict_SetItem(symbols, name, v_new) < 0) {
1026
0
            Py_DECREF(v_new);
1027
0
            return 0;
1028
0
        }
1029
32.9k
        Py_DECREF(v_new);
1030
32.9k
    }
1031
1032
    /* Record not yet resolved free variables from children (if any) */
1033
9.32k
    v_free = PyLong_FromLong(FREE << SCOPE_OFFSET);
1034
9.32k
    if (!v_free)
1035
0
        return 0;
1036
1037
9.32k
    itr = PyObject_GetIter(free);
1038
9.32k
    if (itr == NULL) {
1039
0
        Py_DECREF(v_free);
1040
0
        return 0;
1041
0
    }
1042
1043
9.32k
    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
9.32k
    if (PyErr_Occurred()) {
1095
0
        goto error;
1096
0
    }
1097
1098
9.32k
    Py_DECREF(itr);
1099
9.32k
    Py_DECREF(v_free);
1100
9.32k
    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
9.32k
}
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
9.32k
{
1138
9.32k
    PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL;
1139
9.32k
    PyObject *newglobal = NULL, *newfree = NULL, *inlined_cells = NULL;
1140
9.32k
    PyObject *temp;
1141
9.32k
    int success = 0;
1142
9.32k
    Py_ssize_t i, pos = 0;
1143
1144
9.32k
    local = PySet_New(NULL);  /* collect new names bound in block */
1145
9.32k
    if (!local)
1146
0
        goto error;
1147
9.32k
    scopes = PyDict_New();  /* collect scopes defined for each name */
1148
9.32k
    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
9.32k
    newglobal = PySet_New(NULL);
1163
9.32k
    if (!newglobal)
1164
0
        goto error;
1165
9.32k
    newfree = PySet_New(NULL);
1166
9.32k
    if (!newfree)
1167
0
        goto error;
1168
9.32k
    newbound = PySet_New(NULL);
1169
9.32k
    if (!newbound)
1170
0
        goto error;
1171
9.32k
    inlined_cells = PySet_New(NULL);
1172
9.32k
    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
9.32k
    if (ste->ste_type == ClassBlock) {
1181
        /* Pass down known globals */
1182
741
        temp = PyNumber_InPlaceOr(newglobal, global);
1183
741
        if (!temp)
1184
0
            goto error;
1185
741
        Py_DECREF(temp);
1186
        /* Pass down previously bound symbols */
1187
741
        if (bound) {
1188
741
            temp = PyNumber_InPlaceOr(newbound, bound);
1189
741
            if (!temp)
1190
0
                goto error;
1191
741
            Py_DECREF(temp);
1192
741
        }
1193
741
    }
1194
1195
42.2k
    while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
1196
32.9k
        long flags = PyLong_AsLong(v);
1197
32.9k
        if (flags == -1 && PyErr_Occurred()) {
1198
0
            goto error;
1199
0
        }
1200
32.9k
        if (!analyze_name(ste, scopes, name, flags,
1201
32.9k
                          bound, local, free, global, type_params, class_entry))
1202
0
            goto error;
1203
32.9k
    }
1204
1205
    /* Populate global and bound sets to be passed to children. */
1206
9.32k
    if (ste->ste_type != ClassBlock) {
1207
        /* Add function locals to bound set */
1208
8.58k
        if (_PyST_IsFunctionLike(ste)) {
1209
7.72k
            temp = PyNumber_InPlaceOr(newbound, local);
1210
7.72k
            if (!temp)
1211
0
                goto error;
1212
7.72k
            Py_DECREF(temp);
1213
7.72k
        }
1214
        /* Pass down previously bound symbols */
1215
8.58k
        if (bound) {
1216
7.72k
            temp = PyNumber_InPlaceOr(newbound, bound);
1217
7.72k
            if (!temp)
1218
0
                goto error;
1219
7.72k
            Py_DECREF(temp);
1220
7.72k
        }
1221
        /* Pass down known globals */
1222
8.58k
        temp = PyNumber_InPlaceOr(newglobal, global);
1223
8.58k
        if (!temp)
1224
0
            goto error;
1225
8.58k
        Py_DECREF(temp);
1226
8.58k
    }
1227
741
    else {
1228
        /* Special-case __class__ and __classdict__ */
1229
741
        if (PySet_Add(newbound, &_Py_ID(__class__)) < 0)
1230
0
            goto error;
1231
741
        if (PySet_Add(newbound, &_Py_ID(__classdict__)) < 0)
1232
0
            goto error;
1233
741
        if (PySet_Add(newbound, &_Py_ID(__conditional_annotations__)) < 0)
1234
0
            goto error;
1235
741
    }
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
17.7k
    for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
1244
8.46k
        PyObject *child_free = NULL;
1245
8.46k
        PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
1246
8.46k
        PySTEntryObject* entry;
1247
8.46k
        assert(c && PySTEntry_Check(c));
1248
8.46k
        entry = (PySTEntryObject*)c;
1249
1250
8.46k
        PySTEntryObject *new_class_entry = NULL;
1251
8.46k
        if (entry->ste_can_see_class_scope) {
1252
1.81k
            if (ste->ste_type == ClassBlock) {
1253
1.81k
                new_class_entry = ste;
1254
1.81k
            }
1255
0
            else if (class_entry) {
1256
0
                new_class_entry = class_entry;
1257
0
            }
1258
1.81k
        }
1259
1260
        // we inline all non-generator-expression comprehensions,
1261
        // except those in annotation scopes that are nested in classes
1262
8.46k
        int inline_comp =
1263
8.46k
            entry->ste_comprehension &&
1264
95
            !entry->ste_generator &&
1265
55
            !ste->ste_can_see_class_scope;
1266
1267
8.46k
        if (!analyze_child_block(entry, newbound, newfree, newglobal,
1268
8.46k
                                 type_params, new_class_entry, &child_free))
1269
0
        {
1270
0
            goto error;
1271
0
        }
1272
8.46k
        if (inline_comp) {
1273
55
            if (!inline_comprehension(ste, entry, scopes, child_free, inlined_cells)) {
1274
0
                Py_DECREF(child_free);
1275
0
                goto error;
1276
0
            }
1277
55
            entry->ste_comp_inlined = 1;
1278
55
        }
1279
8.46k
        temp = PyNumber_InPlaceOr(newfree, child_free);
1280
8.46k
        Py_DECREF(child_free);
1281
8.46k
        if (!temp)
1282
0
            goto error;
1283
8.46k
        Py_DECREF(temp);
1284
8.46k
    }
1285
1286
    /* Splice children of inlined comprehensions into our children list */
1287
17.7k
    for (i = PyList_GET_SIZE(ste->ste_children) - 1; i >= 0; --i) {
1288
8.46k
        PyObject* c = PyList_GET_ITEM(ste->ste_children, i);
1289
8.46k
        PySTEntryObject* entry;
1290
8.46k
        assert(c && PySTEntry_Check(c));
1291
8.46k
        entry = (PySTEntryObject*)c;
1292
8.46k
        if (entry->ste_comp_inlined &&
1293
55
            PyList_SetSlice(ste->ste_children, i, i + 1,
1294
55
                            entry->ste_children) < 0)
1295
0
        {
1296
0
            goto error;
1297
0
        }
1298
8.46k
    }
1299
1300
    /* Check if any local variables must be converted to cell variables */
1301
9.32k
    if (_PyST_IsFunctionLike(ste) && !analyze_cells(scopes, newfree, inlined_cells))
1302
0
        goto error;
1303
9.32k
    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
9.32k
    if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, inlined_cells,
1307
9.32k
                        (ste->ste_type == ClassBlock) || ste->ste_can_see_class_scope))
1308
0
        goto error;
1309
1310
9.32k
    temp = PyNumber_InPlaceOr(free, newfree);
1311
9.32k
    if (!temp)
1312
0
        goto error;
1313
9.32k
    Py_DECREF(temp);
1314
9.32k
    success = 1;
1315
9.32k
 error:
1316
9.32k
    Py_XDECREF(scopes);
1317
9.32k
    Py_XDECREF(local);
1318
9.32k
    Py_XDECREF(newbound);
1319
9.32k
    Py_XDECREF(newglobal);
1320
9.32k
    Py_XDECREF(newfree);
1321
9.32k
    Py_XDECREF(inlined_cells);
1322
9.32k
    if (!success)
1323
9.32k
        assert(PyErr_Occurred());
1324
9.32k
    return success;
1325
9.32k
}
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
8.46k
{
1332
8.46k
    PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
1333
8.46k
    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
8.46k
    temp_bound = PySet_New(bound);
1343
8.46k
    if (!temp_bound)
1344
0
        goto error;
1345
8.46k
    temp_free = PySet_New(free);
1346
8.46k
    if (!temp_free)
1347
0
        goto error;
1348
8.46k
    temp_global = PySet_New(global);
1349
8.46k
    if (!temp_global)
1350
0
        goto error;
1351
8.46k
    temp_type_params = PySet_New(type_params);
1352
8.46k
    if (!temp_type_params)
1353
0
        goto error;
1354
1355
8.46k
    if (!analyze_block(entry, temp_bound, temp_free, temp_global,
1356
8.46k
                       temp_type_params, class_entry))
1357
0
        goto error;
1358
8.46k
    *child_free = temp_free;
1359
8.46k
    Py_DECREF(temp_bound);
1360
8.46k
    Py_DECREF(temp_global);
1361
8.46k
    Py_DECREF(temp_type_params);
1362
8.46k
    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
8.46k
}
1370
1371
static int
1372
symtable_analyze(struct symtable *st)
1373
856
{
1374
856
    PyObject *free, *global, *type_params;
1375
856
    int r;
1376
1377
856
    free = PySet_New(NULL);
1378
856
    if (!free)
1379
0
        return 0;
1380
856
    global = PySet_New(NULL);
1381
856
    if (!global) {
1382
0
        Py_DECREF(free);
1383
0
        return 0;
1384
0
    }
1385
856
    type_params = PySet_New(NULL);
1386
856
    if (!type_params) {
1387
0
        Py_DECREF(free);
1388
0
        Py_DECREF(global);
1389
0
        return 0;
1390
0
    }
1391
856
    r = analyze_block(st->st_top, NULL, free, global, type_params, NULL);
1392
856
    Py_DECREF(free);
1393
856
    Py_DECREF(global);
1394
856
    Py_DECREF(type_params);
1395
856
    return r;
1396
856
}
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
9.33k
{
1406
9.33k
    Py_ssize_t size;
1407
1408
9.33k
    st->st_cur = NULL;
1409
9.33k
    size = PyList_GET_SIZE(st->st_stack);
1410
9.33k
    if (size) {
1411
9.33k
        if (PyList_SetSlice(st->st_stack, size - 1, size, NULL) < 0)
1412
0
            return 0;
1413
9.33k
        if (--size)
1414
8.47k
            st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, size - 1);
1415
9.33k
    }
1416
9.33k
    return 1;
1417
9.33k
}
1418
1419
static int
1420
symtable_enter_existing_block(struct symtable *st, PySTEntryObject* ste, bool add_to_children)
1421
9.33k
{
1422
9.33k
    if (PyList_Append(st->st_stack, (PyObject *)ste) < 0) {
1423
0
        return 0;
1424
0
    }
1425
9.33k
    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
9.33k
    if (prev) {
1431
8.47k
        ste->ste_comp_iter_expr = prev->ste_comp_iter_expr;
1432
8.47k
    }
1433
    /* No need to inherit ste_mangled_names in classes, where all names
1434
     * are mangled. */
1435
9.33k
    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
9.33k
    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
9.33k
    if (st->st_future->ff_features & CO_FUTURE_ANNOTATIONS && ste->ste_type == AnnotationBlock) {
1445
0
        return 1;
1446
0
    }
1447
1448
9.33k
    if (ste->ste_type == ModuleBlock)
1449
856
        st->st_global = st->st_cur->ste_symbols;
1450
1451
9.33k
    if (add_to_children && prev) {
1452
8.46k
        if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) {
1453
0
            return 0;
1454
0
        }
1455
8.46k
    }
1456
9.33k
    return 1;
1457
9.33k
}
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.64k
{
1463
5.64k
    PySTEntryObject *ste = ste_new(st, name, block, ast, loc);
1464
5.64k
    if (ste == NULL)
1465
0
        return 0;
1466
5.64k
    int result = symtable_enter_existing_block(st, ste, /* add_to_children */true);
1467
5.64k
    Py_DECREF(ste);
1468
5.64k
    if (block == AnnotationBlock || block == TypeVariableBlock || block == TypeAliasBlock) {
1469
3.68k
        _Py_DECLARE_STR(format, ".format");
1470
        // We need to insert code that reads this "parameter" to the function.
1471
3.68k
        if (!symtable_add_def(st, &_Py_STR(format), DEF_PARAM, loc)) {
1472
0
            return 0;
1473
0
        }
1474
3.68k
        if (!symtable_add_def(st, &_Py_STR(format), USE, loc)) {
1475
0
            return 0;
1476
0
        }
1477
3.68k
    }
1478
5.64k
    return result;
1479
5.64k
}
1480
1481
static long
1482
symtable_lookup_entry(struct symtable *st, PySTEntryObject *ste, PyObject *name)
1483
33
{
1484
33
    PyObject *mangled = _Py_MaybeMangle(st->st_private, ste, name);
1485
33
    if (!mangled)
1486
0
        return -1;
1487
33
    long ret = _PyST_GetSymbol(ste, mangled);
1488
33
    Py_DECREF(mangled);
1489
33
    if (ret < 0) {
1490
0
        return -1;
1491
0
    }
1492
33
    return ret;
1493
33
}
1494
1495
static long
1496
symtable_lookup(struct symtable *st, PyObject *name)
1497
33
{
1498
33
    return symtable_lookup_entry(st, st->st_cur, name);
1499
33
}
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
73.0k
{
1505
73.0k
    PyObject *o;
1506
73.0k
    PyObject *dict;
1507
73.0k
    long val;
1508
73.0k
    PyObject *mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1509
1510
73.0k
    if (!mangled)
1511
0
        return 0;
1512
73.0k
    dict = ste->ste_symbols;
1513
73.0k
    if ((o = PyDict_GetItemWithError(dict, mangled))) {
1514
40.1k
        val = PyLong_AsLong(o);
1515
40.1k
        if (val == -1 && PyErr_Occurred()) {
1516
0
            goto error;
1517
0
        }
1518
40.1k
        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
40.1k
        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
40.1k
        val |= flag;
1530
40.1k
    }
1531
32.9k
    else if (PyErr_Occurred()) {
1532
0
        goto error;
1533
0
    }
1534
32.9k
    else {
1535
32.9k
        val = flag;
1536
32.9k
    }
1537
73.0k
    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
121
        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
121
        val |= DEF_COMP_ITER;
1550
121
    }
1551
73.0k
    o = PyLong_FromLong(val);
1552
73.0k
    if (o == NULL)
1553
0
        goto error;
1554
73.0k
    if (PyDict_SetItem(dict, mangled, o) < 0) {
1555
0
        Py_DECREF(o);
1556
0
        goto error;
1557
0
    }
1558
73.0k
    Py_DECREF(o);
1559
1560
73.0k
    if (flag & DEF_PARAM) {
1561
14.9k
        if (PyList_Append(ste->ste_varnames, mangled) < 0)
1562
0
            goto error;
1563
58.0k
    } else if (flag & DEF_GLOBAL) {
1564
        /* XXX need to update DEF_GLOBAL for other flags too;
1565
           perhaps only DEF_FREE_GLOBAL */
1566
11
        val = 0;
1567
11
        if ((o = PyDict_GetItemWithError(st->st_global, mangled))) {
1568
6
            val = PyLong_AsLong(o);
1569
6
            if (val == -1 && PyErr_Occurred()) {
1570
0
                goto error;
1571
0
            }
1572
6
        }
1573
5
        else if (PyErr_Occurred()) {
1574
0
            goto error;
1575
0
        }
1576
11
        val |= flag;
1577
11
        o = PyLong_FromLong(val);
1578
11
        if (o == NULL)
1579
0
            goto error;
1580
11
        if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
1581
0
            Py_DECREF(o);
1582
0
            goto error;
1583
0
        }
1584
11
        Py_DECREF(o);
1585
11
    }
1586
73.0k
    Py_DECREF(mangled);
1587
73.0k
    return 1;
1588
1589
0
error:
1590
0
    Py_DECREF(mangled);
1591
0
    return 0;
1592
73.0k
}
1593
1594
static int
1595
check_name(struct symtable *st, PyObject *name, _Py_SourceLocation loc,
1596
           expr_context_ty ctx)
1597
45.3k
{
1598
45.3k
    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
45.3k
    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
45.3k
    return 1;
1609
45.3k
}
1610
1611
static int
1612
check_keywords(struct symtable *st, asdl_keyword_seq *keywords)
1613
11.5k
{
1614
13.4k
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(keywords); i++) {
1615
1.84k
        keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
1616
1.84k
        if (key->arg  && !check_name(st, key->arg, LOCATION(key), Store)) {
1617
0
            return 0;
1618
0
        }
1619
1.84k
    }
1620
11.5k
    return 1;
1621
11.5k
}
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
73.0k
{
1642
73.0k
    int write_mask = DEF_PARAM | DEF_LOCAL | DEF_IMPORT;
1643
73.0k
    if ((flag & write_mask) && !check_name(st, name, loc, ctx)) {
1644
0
        return 0;
1645
0
    }
1646
73.0k
    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
73.0k
    return symtable_add_def_helper(st, name, flag, st->st_cur, loc);
1652
73.0k
}
1653
1654
static int
1655
symtable_add_def(struct symtable *st, PyObject *name, int flag,
1656
                 _Py_SourceLocation loc)
1657
26.2k
{
1658
26.2k
    return symtable_add_def_ctx(st, name, flag, loc,
1659
26.2k
                                flag == USE ? Load : Store);
1660
26.2k
}
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 VIST_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
65.1k
    do { \
1727
65.1k
        if (!symtable_visit_ ## TYPE((ST), (V))) { \
1728
0
            return 0; \
1729
0
        } \
1730
65.1k
    } while(0)
1731
1732
#define VISIT_SEQ(ST, TYPE, SEQ) \
1733
40.7k
    do { \
1734
40.7k
        Py_ssize_t i; \
1735
40.7k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1736
109k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1737
68.7k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1738
68.7k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1739
68.7k
                return 0;                 \
1740
68.7k
        } \
1741
40.7k
    } while(0)
1742
1743
#define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) \
1744
95
    do { \
1745
95
        Py_ssize_t i; \
1746
95
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1747
96
        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
95
    } while(0)
1753
1754
#define VISIT_SEQ_WITH_NULL(ST, TYPE, SEQ) \
1755
14.9k
    do { \
1756
14.9k
        int i = 0; \
1757
14.9k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
1758
24.8k
        for (i = 0; i < asdl_seq_LEN(seq); i++) { \
1759
9.89k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
1760
9.89k
            if (!elt) continue; /* can be NULL */ \
1761
9.89k
            if (!symtable_visit_ ## TYPE((ST), elt)) \
1762
9.88k
                return 0;             \
1763
9.88k
        } \
1764
14.9k
    } while(0)
1765
1766
#define ENTER_CONDITIONAL_BLOCK(ST) \
1767
4.12k
    int in_conditional_block = (ST)->st_cur->ste_in_conditional_block; \
1768
4.12k
    (ST)->st_cur->ste_in_conditional_block = 1;
1769
1770
#define LEAVE_CONDITIONAL_BLOCK(ST) \
1771
4.12k
    (ST)->st_cur->ste_in_conditional_block = in_conditional_block;
1772
1773
#define ENTER_TRY_BLOCK(ST) \
1774
396
    int in_try_block = (ST)->st_cur->ste_in_try_block; \
1775
396
    (ST)->st_cur->ste_in_try_block = 1;
1776
1777
#define LEAVE_TRY_BLOCK(ST) \
1778
396
    (ST)->st_cur->ste_in_try_block = in_try_block;
1779
1780
139k
#define ENTER_RECURSIVE() \
1781
139k
if (Py_EnterRecursiveCall(" during compilation")) { \
1782
0
    return 0; \
1783
0
}
1784
1785
139k
#define LEAVE_RECURSIVE() Py_LeaveRecursiveCall();
1786
1787
1788
static int
1789
symtable_record_directive(struct symtable *st, identifier name, _Py_SourceLocation loc)
1790
17
{
1791
17
    PyObject *data, *mangled;
1792
17
    int res;
1793
17
    if (!st->st_cur->ste_directives) {
1794
13
        st->st_cur->ste_directives = PyList_New(0);
1795
13
        if (!st->st_cur->ste_directives)
1796
0
            return 0;
1797
13
    }
1798
17
    mangled = _Py_MaybeMangle(st->st_private, st->st_cur, name);
1799
17
    if (!mangled)
1800
0
        return 0;
1801
17
    data = Py_BuildValue("(Niiii)", mangled, loc.lineno, loc.col_offset,
1802
17
                                    loc.end_lineno, loc.end_col_offset);
1803
17
    if (!data)
1804
0
        return 0;
1805
17
    res = PyList_Append(st->st_cur->ste_directives, data);
1806
17
    Py_DECREF(data);
1807
17
    return res == 0;
1808
17
}
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
385
{
1825
385
    assert(s->kind == ImportFrom_kind);
1826
385
    _Py_SourceLocation fut = st->st_future->ff_location;
1827
385
    if (s->v.ImportFrom.module && s->v.ImportFrom.level == 0 &&
1828
240
        _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__") &&
1829
0
        ((s->lineno > fut.lineno) ||
1830
0
         ((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
385
    return 1;
1839
385
}
1840
1841
static int
1842
check_lazy_import_context(struct symtable *st, stmt_ty s,
1843
                          const char* import_type)
1844
0
{
1845
    // Check if inside try/except block.
1846
0
    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
0
    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
0
    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
0
    return 1;
1871
0
}
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
23.8k
{
1892
23.8k
    ENTER_RECURSIVE();
1893
23.8k
    switch (s->kind) {
1894
3.54k
    case FunctionDef_kind: {
1895
3.54k
        if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL, LOCATION(s)))
1896
0
            return 0;
1897
3.54k
        if (s->v.FunctionDef.args->defaults)
1898
3.54k
            VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
1899
3.54k
        if (s->v.FunctionDef.args->kw_defaults)
1900
3.54k
            VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults);
1901
3.54k
        if (s->v.FunctionDef.decorator_list)
1902
212
            VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
1903
3.54k
        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.54k
        PySTEntryObject *new_ste = ste_new(st, s->v.FunctionDef.name, FunctionBlock, (void *)s,
1917
3.54k
                                           LOCATION(s));
1918
3.54k
        if (!new_ste) {
1919
0
            return 0;
1920
0
        }
1921
1922
3.54k
        if (_PyAST_GetDocString(s->v.FunctionDef.body)) {
1923
517
            new_ste->ste_has_docstring = 1;
1924
517
        }
1925
1926
3.54k
        if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args,
1927
3.54k
                                        s->v.FunctionDef.returns, new_ste)) {
1928
0
            Py_DECREF(new_ste);
1929
0
            return 0;
1930
0
        }
1931
3.54k
        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.54k
        Py_DECREF(new_ste);
1936
3.54k
        VISIT(st, arguments, s->v.FunctionDef.args);
1937
3.54k
        VISIT_SEQ(st, stmt, s->v.FunctionDef.body);
1938
3.54k
        if (!symtable_exit_block(st))
1939
0
            return 0;
1940
3.54k
        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.54k
        break;
1945
3.54k
    }
1946
3.54k
    case ClassDef_kind: {
1947
741
        PyObject *tmp;
1948
741
        if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL, LOCATION(s)))
1949
0
            return 0;
1950
741
        if (s->v.ClassDef.decorator_list)
1951
3
            VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
1952
741
        tmp = st->st_private;
1953
741
        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
741
        VISIT_SEQ(st, expr, s->v.ClassDef.bases);
1968
741
        if (!check_keywords(st, s->v.ClassDef.keywords)) {
1969
0
            return 0;
1970
0
        }
1971
741
        VISIT_SEQ(st, keyword, s->v.ClassDef.keywords);
1972
741
        if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
1973
741
                                  (void *)s, LOCATION(s))) {
1974
0
            return 0;
1975
0
        }
1976
741
        st->st_private = s->v.ClassDef.name;
1977
741
        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
741
        if (_PyAST_GetDocString(s->v.ClassDef.body)) {
1990
116
            st->st_cur->ste_has_docstring = 1;
1991
116
        }
1992
1993
741
        VISIT_SEQ(st, stmt, s->v.ClassDef.body);
1994
741
        if (!symtable_exit_block(st))
1995
0
            return 0;
1996
741
        if (asdl_seq_LEN(s->v.ClassDef.type_params) > 0) {
1997
0
            if (!symtable_exit_block(st))
1998
0
                return 0;
1999
0
        }
2000
741
        st->st_private = tmp;
2001
741
        break;
2002
741
    }
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
3.04k
    case Return_kind:
2037
3.04k
        if (s->v.Return.value) {
2038
2.78k
            VISIT(st, expr, s->v.Return.value);
2039
2.78k
            st->st_cur->ste_returns_value = 1;
2040
2.78k
        }
2041
3.04k
        break;
2042
3.04k
    case Delete_kind:
2043
50
        VISIT_SEQ(st, expr, s->v.Delete.targets);
2044
50
        break;
2045
4.92k
    case Assign_kind:
2046
4.92k
        VISIT_SEQ(st, expr, s->v.Assign.targets);
2047
4.92k
        VISIT(st, expr, s->v.Assign.value);
2048
4.92k
        break;
2049
4.92k
    case AnnAssign_kind:
2050
18
        st->st_cur->ste_annotations_used = 1;
2051
18
        if (s->v.AnnAssign.target->kind == Name_kind) {
2052
16
            expr_ty e_name = s->v.AnnAssign.target;
2053
16
            long cur = symtable_lookup(st, e_name->v.Name.id);
2054
16
            if (cur < 0) {
2055
0
                return 0;
2056
0
            }
2057
16
            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
16
            if (s->v.AnnAssign.simple &&
2067
16
                !symtable_add_def(st, e_name->v.Name.id,
2068
16
                                  DEF_ANNOT | DEF_LOCAL, LOCATION(e_name))) {
2069
0
                return 0;
2070
0
            }
2071
16
            else {
2072
16
                if (s->v.AnnAssign.value
2073
12
                    && !symtable_add_def(st, e_name->v.Name.id, DEF_LOCAL, LOCATION(e_name))) {
2074
0
                    return 0;
2075
0
                }
2076
16
            }
2077
16
        }
2078
2
        else {
2079
2
            VISIT(st, expr, s->v.AnnAssign.target);
2080
2
        }
2081
18
        if (!symtable_visit_annotation(st, s->v.AnnAssign.annotation,
2082
18
                                       (void *)((uintptr_t)st->st_cur->ste_id + 1))) {
2083
0
            return 0;
2084
0
        }
2085
2086
18
        if (s->v.AnnAssign.value) {
2087
14
            VISIT(st, expr, s->v.AnnAssign.value);
2088
14
        }
2089
18
        break;
2090
197
    case AugAssign_kind: {
2091
197
        VISIT(st, expr, s->v.AugAssign.target);
2092
197
        VISIT(st, expr, s->v.AugAssign.value);
2093
197
        break;
2094
197
    }
2095
311
    case For_kind: {
2096
311
        VISIT(st, expr, s->v.For.target);
2097
311
        VISIT(st, expr, s->v.For.iter);
2098
311
        ENTER_CONDITIONAL_BLOCK(st);
2099
311
        VISIT_SEQ(st, stmt, s->v.For.body);
2100
311
        if (s->v.For.orelse)
2101
4
            VISIT_SEQ(st, stmt, s->v.For.orelse);
2102
311
        LEAVE_CONDITIONAL_BLOCK(st);
2103
311
        break;
2104
311
    }
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.21k
    case If_kind: {
2115
        /* XXX if 0: and lookup_yield() hacks */
2116
3.21k
        VISIT(st, expr, s->v.If.test);
2117
3.21k
        ENTER_CONDITIONAL_BLOCK(st);
2118
3.21k
        VISIT_SEQ(st, stmt, s->v.If.body);
2119
3.21k
        if (s->v.If.orelse)
2120
706
            VISIT_SEQ(st, stmt, s->v.If.orelse);
2121
3.21k
        LEAVE_CONDITIONAL_BLOCK(st);
2122
3.21k
        break;
2123
3.21k
    }
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
891
    case Raise_kind:
2132
891
        if (s->v.Raise.exc) {
2133
792
            VISIT(st, expr, s->v.Raise.exc);
2134
792
            if (s->v.Raise.cause) {
2135
27
                VISIT(st, expr, s->v.Raise.cause);
2136
27
            }
2137
792
        }
2138
891
        break;
2139
891
    case Try_kind: {
2140
396
        ENTER_CONDITIONAL_BLOCK(st);
2141
396
        ENTER_TRY_BLOCK(st);
2142
396
        VISIT_SEQ(st, stmt, s->v.Try.body);
2143
396
        VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
2144
396
        VISIT_SEQ(st, stmt, s->v.Try.orelse);
2145
396
        VISIT_SEQ(st, stmt, s->v.Try.finalbody);
2146
396
        LEAVE_TRY_BLOCK(st);
2147
396
        LEAVE_CONDITIONAL_BLOCK(st);
2148
396
        break;
2149
396
    }
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
487
    case Import_kind:
2167
487
        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
487
        VISIT_SEQ(st, alias, s->v.Import.names);
2173
487
        break;
2174
487
    case ImportFrom_kind:
2175
385
        if (s->v.ImportFrom.is_lazy) {
2176
0
            if (!check_lazy_import_context(st, s, "from ... import")) {
2177
0
                return 0;
2178
0
            }
2179
2180
            // Check for import *
2181
0
            for (Py_ssize_t i = 0; i < asdl_seq_LEN(s->v.ImportFrom.names);
2182
0
                 i++) {
2183
0
                alias_ty alias = (alias_ty)asdl_seq_GET(
2184
0
                    s->v.ImportFrom.names, i);
2185
0
                if (alias->name &&
2186
0
                        _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
0
            }
2193
0
        }
2194
385
        VISIT_SEQ(st, alias, s->v.ImportFrom.names);
2195
385
        if (!check_import_from(st, s)) {
2196
0
            return 0;
2197
0
        }
2198
385
        break;
2199
385
    case Global_kind: {
2200
9
        Py_ssize_t i;
2201
9
        asdl_identifier_seq *seq = s->v.Global.names;
2202
20
        for (i = 0; i < asdl_seq_LEN(seq); i++) {
2203
11
            identifier name = (identifier)asdl_seq_GET(seq, i);
2204
11
            long cur = symtable_lookup(st, name);
2205
11
            if (cur < 0)
2206
0
                return 0;
2207
11
            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
11
            if (!symtable_add_def(st, name, DEF_GLOBAL, LOCATION(s))) {
2224
0
                return 0;
2225
0
            }
2226
11
            if (!symtable_record_directive(st, name, LOCATION(s))) {
2227
0
                return 0;
2228
0
            }
2229
11
        }
2230
9
        break;
2231
9
    }
2232
9
    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.89k
    case Expr_kind:
2264
4.89k
        VISIT(st, expr, s->v.Expr.value);
2265
4.89k
        break;
2266
4.89k
    case Pass_kind:
2267
294
    case Break_kind:
2268
343
    case Continue_kind:
2269
        /* nothing to do here */
2270
343
        break;
2271
114
    case With_kind: {
2272
114
        ENTER_CONDITIONAL_BLOCK(st);
2273
114
        VISIT_SEQ(st, withitem, s->v.With.items);
2274
114
        VISIT_SEQ(st, stmt, s->v.With.body);
2275
114
        LEAVE_CONDITIONAL_BLOCK(st);
2276
114
        break;
2277
114
    }
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
23.8k
    }
2359
23.8k
    LEAVE_RECURSIVE();
2360
23.8k
    return 1;
2361
23.8k
}
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
115k
{
2482
115k
    ENTER_RECURSIVE();
2483
115k
    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
821
    case BoolOp_kind:
2492
821
        VISIT_SEQ(st, expr, e->v.BoolOp.values);
2493
821
        break;
2494
821
    case BinOp_kind:
2495
705
        VISIT(st, expr, e->v.BinOp.left);
2496
705
        VISIT(st, expr, e->v.BinOp.right);
2497
705
        break;
2498
705
    case UnaryOp_kind:
2499
587
        VISIT(st, expr, e->v.UnaryOp.operand);
2500
587
        break;
2501
587
    case Lambda_kind: {
2502
270
        if (e->v.Lambda.args->defaults)
2503
270
            VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
2504
270
        if (e->v.Lambda.args->kw_defaults)
2505
270
            VISIT_SEQ_WITH_NULL(st, expr, e->v.Lambda.args->kw_defaults);
2506
270
        if (!symtable_enter_block(st, &_Py_STR(anon_lambda),
2507
270
                                  FunctionBlock, (void *)e, LOCATION(e))) {
2508
0
            return 0;
2509
0
        }
2510
270
        VISIT(st, arguments, e->v.Lambda.args);
2511
270
        VISIT(st, expr, e->v.Lambda.body);
2512
270
        if (!symtable_exit_block(st))
2513
0
            return 0;
2514
270
        break;
2515
270
    }
2516
270
    case IfExp_kind:
2517
136
        VISIT(st, expr, e->v.IfExp.test);
2518
136
        VISIT(st, expr, e->v.IfExp.body);
2519
136
        VISIT(st, expr, e->v.IfExp.orelse);
2520
136
        break;
2521
145
    case Dict_kind:
2522
145
        VISIT_SEQ_WITH_NULL(st, expr, e->v.Dict.keys);
2523
145
        VISIT_SEQ(st, expr, e->v.Dict.values);
2524
145
        break;
2525
237
    case Set_kind:
2526
237
        VISIT_SEQ(st, expr, e->v.Set.elts);
2527
237
        break;
2528
237
    case GeneratorExp_kind:
2529
40
        if (!symtable_visit_genexp(st, e))
2530
0
            return 0;
2531
40
        break;
2532
43
    case ListComp_kind:
2533
43
        if (!symtable_visit_listcomp(st, e))
2534
0
            return 0;
2535
43
        break;
2536
43
    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
3.71k
    case Compare_kind:
2587
3.71k
        VISIT(st, expr, e->v.Compare.left);
2588
3.71k
        VISIT_SEQ(st, expr, e->v.Compare.comparators);
2589
3.71k
        break;
2590
10.8k
    case Call_kind:
2591
10.8k
        VISIT(st, expr, e->v.Call.func);
2592
10.8k
        VISIT_SEQ(st, expr, e->v.Call.args);
2593
10.8k
        if (!check_keywords(st, e->v.Call.keywords)) {
2594
0
            return 0;
2595
0
        }
2596
10.8k
        VISIT_SEQ_WITH_NULL(st, keyword, e->v.Call.keywords);
2597
10.8k
        break;
2598
10.8k
    case FormattedValue_kind:
2599
2.19k
        VISIT(st, expr, e->v.FormattedValue.value);
2600
2.19k
        if (e->v.FormattedValue.format_spec)
2601
7
            VISIT(st, expr, e->v.FormattedValue.format_spec);
2602
2.19k
        break;
2603
2.19k
    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
788
    case JoinedStr_kind:
2609
788
        VISIT_SEQ(st, expr, e->v.JoinedStr.values);
2610
788
        break;
2611
788
    case TemplateStr_kind:
2612
1
        VISIT_SEQ(st, expr, e->v.TemplateStr.values);
2613
1
        break;
2614
26.8k
    case Constant_kind:
2615
        /* Nothing to do here. */
2616
26.8k
        break;
2617
    /* The following exprs can be assignment targets. */
2618
18.7k
    case Attribute_kind:
2619
18.7k
        if (!check_name(st, e->v.Attribute.attr, LOCATION(e), e->v.Attribute.ctx)) {
2620
0
            return 0;
2621
0
        }
2622
18.7k
        VISIT(st, expr, e->v.Attribute.value);
2623
18.7k
        break;
2624
18.7k
    case Subscript_kind:
2625
912
        VISIT(st, expr, e->v.Subscript.value);
2626
912
        VISIT(st, expr, e->v.Subscript.slice);
2627
912
        break;
2628
912
    case Starred_kind:
2629
114
        VISIT(st, expr, e->v.Starred.value);
2630
114
        break;
2631
131
    case Slice_kind:
2632
131
        if (e->v.Slice.lower)
2633
71
            VISIT(st, expr, e->v.Slice.lower);
2634
131
        if (e->v.Slice.upper)
2635
77
            VISIT(st, expr, e->v.Slice.upper);
2636
131
        if (e->v.Slice.step)
2637
0
            VISIT(st, expr, e->v.Slice.step);
2638
131
        break;
2639
46.7k
    case Name_kind:
2640
46.7k
        if (!st->st_cur->ste_in_unevaluated_annotation) {
2641
46.7k
            if (!symtable_add_def_ctx(st, e->v.Name.id,
2642
46.7k
                                    e->v.Name.ctx == Load ? USE : DEF_LOCAL,
2643
46.7k
                                    LOCATION(e), e->v.Name.ctx)) {
2644
0
                return 0;
2645
0
            }
2646
            /* Special-case super: it counts as a use of __class__ */
2647
46.7k
            if (e->v.Name.ctx == Load &&
2648
42.3k
                _PyST_IsFunctionLike(st->st_cur) &&
2649
40.2k
                _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
2650
292
                if (!symtable_add_def(st, &_Py_ID(__class__), USE, LOCATION(e)))
2651
0
                    return 0;
2652
292
            }
2653
46.7k
        }
2654
46.7k
        break;
2655
    /* child nodes of List and Tuple will have expr_context set */
2656
46.7k
    case List_kind:
2657
220
        VISIT_SEQ(st, expr, e->v.List.elts);
2658
220
        break;
2659
1.38k
    case Tuple_kind:
2660
1.38k
        VISIT_SEQ(st, expr, e->v.Tuple.elts);
2661
1.38k
        break;
2662
115k
    }
2663
115k
    LEAVE_RECURSIVE();
2664
115k
    return 1;
2665
115k
}
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
95
{
2819
95
    PyObject *id = PyUnicode_FromFormat(".%d", pos);
2820
95
    if (id == NULL)
2821
0
        return 0;
2822
95
    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
95
    Py_DECREF(id);
2827
95
    return 1;
2828
95
}
2829
2830
static int
2831
symtable_visit_params(struct symtable *st, asdl_arg_seq *args)
2832
11.8k
{
2833
11.8k
    Py_ssize_t i;
2834
2835
22.8k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2836
10.9k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2837
10.9k
        if (!symtable_add_def(st, arg->arg, DEF_PARAM, LOCATION(arg)))
2838
0
            return 0;
2839
10.9k
    }
2840
2841
11.8k
    return 1;
2842
11.8k
}
2843
2844
static int
2845
symtable_visit_annotation(struct symtable *st, expr_ty annotation, void *key)
2846
18
{
2847
    // Annotations in local scopes are not executed and should not affect the symtable
2848
18
    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
18
    if ((((st->st_cur->ste_type == ClassBlock && st->st_cur->ste_in_conditional_block)
2853
18
            || st->st_cur->ste_type == ModuleBlock))
2854
0
            && !st->st_cur->ste_has_conditional_annotations)
2855
0
    {
2856
0
        st->st_cur->ste_has_conditional_annotations = 1;
2857
0
        if (!symtable_add_def(st, &_Py_ID(__conditional_annotations__), USE, LOCATION(annotation))) {
2858
0
            return 0;
2859
0
        }
2860
0
    }
2861
18
    struct _symtable_entry *parent_ste = st->st_cur;
2862
18
    if (parent_ste->ste_annotation_block == NULL) {
2863
10
        _Py_block_ty current_type = parent_ste->ste_type;
2864
10
        if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2865
10
                                    key, LOCATION(annotation))) {
2866
0
            return 0;
2867
0
        }
2868
10
        parent_ste->ste_annotation_block =
2869
10
            (struct _symtable_entry *)Py_NewRef(st->st_cur);
2870
10
        int future_annotations = st->st_future->ff_features & CO_FUTURE_ANNOTATIONS;
2871
10
        if (current_type == ClassBlock && !future_annotations) {
2872
6
            st->st_cur->ste_can_see_class_scope = 1;
2873
6
            if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(annotation))) {
2874
0
                return 0;
2875
0
            }
2876
6
        }
2877
10
    }
2878
8
    else {
2879
8
        if (!symtable_enter_existing_block(st, parent_ste->ste_annotation_block,
2880
8
                                           /* add_to_children */false)) {
2881
0
            return 0;
2882
0
        }
2883
8
    }
2884
18
    if (is_unevaluated) {
2885
6
        st->st_cur->ste_in_unevaluated_annotation = 1;
2886
6
    }
2887
18
    int rc = symtable_visit_expr(st, annotation);
2888
18
    if (is_unevaluated) {
2889
6
        st->st_cur->ste_in_unevaluated_annotation = 0;
2890
6
    }
2891
18
    if (!symtable_exit_block(st)) {
2892
0
        return 0;
2893
0
    }
2894
18
    return rc;
2895
18
}
2896
2897
static int
2898
symtable_visit_argannotations(struct symtable *st, asdl_arg_seq *args)
2899
11.0k
{
2900
11.0k
    Py_ssize_t i;
2901
2902
20.8k
    for (i = 0; i < asdl_seq_LEN(args); i++) {
2903
9.78k
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
2904
9.78k
        if (arg->annotation) {
2905
49
            st->st_cur->ste_annotations_used = 1;
2906
49
            VISIT(st, expr, arg->annotation);
2907
49
        }
2908
9.78k
    }
2909
2910
11.0k
    return 1;
2911
11.0k
}
2912
2913
static int
2914
symtable_visit_annotations(struct symtable *st, stmt_ty o, arguments_ty a, expr_ty returns,
2915
                           struct _symtable_entry *function_ste)
2916
3.67k
{
2917
3.67k
    int is_in_class = st->st_cur->ste_can_see_class_scope;
2918
3.67k
    _Py_block_ty current_type = st->st_cur->ste_type;
2919
3.67k
    if (!symtable_enter_block(st, &_Py_ID(__annotate__), AnnotationBlock,
2920
3.67k
                              (void *)a, LOCATION(o))) {
2921
0
        return 0;
2922
0
    }
2923
3.67k
    Py_XSETREF(st->st_cur->ste_function_name, Py_NewRef(function_ste->ste_name));
2924
3.67k
    if (is_in_class || current_type == ClassBlock) {
2925
1.80k
        st->st_cur->ste_can_see_class_scope = 1;
2926
1.80k
        if (!symtable_add_def(st, &_Py_ID(__classdict__), USE, LOCATION(o))) {
2927
0
            return 0;
2928
0
        }
2929
1.80k
    }
2930
3.67k
    if (a->posonlyargs && !symtable_visit_argannotations(st, a->posonlyargs))
2931
0
        return 0;
2932
3.67k
    if (a->args && !symtable_visit_argannotations(st, a->args))
2933
0
        return 0;
2934
3.67k
    if (a->vararg && a->vararg->annotation) {
2935
0
        st->st_cur->ste_annotations_used = 1;
2936
0
        VISIT(st, expr, a->vararg->annotation);
2937
0
    }
2938
3.67k
    if (a->kwarg && a->kwarg->annotation) {
2939
0
        st->st_cur->ste_annotations_used = 1;
2940
0
        VISIT(st, expr, a->kwarg->annotation);
2941
0
    }
2942
3.67k
    if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs))
2943
0
        return 0;
2944
3.67k
    if (returns) {
2945
36
        st->st_cur->ste_annotations_used = 1;
2946
36
        VISIT(st, expr, returns);
2947
36
    }
2948
3.67k
    if (!symtable_exit_block(st)) {
2949
0
        return 0;
2950
0
    }
2951
3.67k
    return 1;
2952
3.67k
}
2953
2954
static int
2955
symtable_visit_arguments(struct symtable *st, arguments_ty a)
2956
3.94k
{
2957
    /* skip default arguments inside function block
2958
       XXX should ast be different?
2959
    */
2960
3.94k
    if (a->posonlyargs && !symtable_visit_params(st, a->posonlyargs))
2961
0
        return 0;
2962
3.94k
    if (a->args && !symtable_visit_params(st, a->args))
2963
0
        return 0;
2964
3.94k
    if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs))
2965
0
        return 0;
2966
3.94k
    if (a->vararg) {
2967
117
        if (!symtable_add_def(st, a->vararg->arg, DEF_PARAM, LOCATION(a->vararg)))
2968
0
            return 0;
2969
117
        st->st_cur->ste_varargs = 1;
2970
117
    }
2971
3.94k
    if (a->kwarg) {
2972
106
        if (!symtable_add_def(st, a->kwarg->arg, DEF_PARAM, LOCATION(a->kwarg)))
2973
0
            return 0;
2974
106
        st->st_cur->ste_varkeywords = 1;
2975
106
    }
2976
3.94k
    return 1;
2977
3.94k
}
2978
2979
2980
static int
2981
symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
2982
439
{
2983
439
    if (eh->v.ExceptHandler.type)
2984
413
        VISIT(st, expr, eh->v.ExceptHandler.type);
2985
439
    if (eh->v.ExceptHandler.name)
2986
102
        if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL, LOCATION(eh)))
2987
0
            return 0;
2988
439
    VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
2989
439
    return 1;
2990
439
}
2991
2992
static int
2993
symtable_visit_withitem(struct symtable *st, withitem_ty item)
2994
123
{
2995
123
    VISIT(st, expr, item->context_expr);
2996
123
    if (item->optional_vars) {
2997
31
        VISIT(st, expr, item->optional_vars);
2998
31
    }
2999
123
    return 1;
3000
123
}
3001
3002
static int
3003
symtable_visit_match_case(struct symtable *st, match_case_ty m)
3004
4
{
3005
4
    VISIT(st, pattern, m->pattern);
3006
4
    if (m->guard) {
3007
0
        VISIT(st, expr, m->guard);
3008
0
    }
3009
4
    VISIT_SEQ(st, stmt, m->body);
3010
4
    return 1;
3011
4
}
3012
3013
static int
3014
symtable_visit_alias(struct symtable *st, alias_ty a)
3015
956
{
3016
    /* Compute store_name, the name actually bound by the import
3017
       operation.  It is different than a->name when a->name is a
3018
       dotted package name (e.g. spam.eggs)
3019
    */
3020
956
    PyObject *store_name;
3021
956
    PyObject *name = (a->asname == NULL) ? a->name : a->asname;
3022
956
    Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
3023
956
                                        PyUnicode_GET_LENGTH(name), 1);
3024
956
    if (dot != -1) {
3025
10
        store_name = PyUnicode_Substring(name, 0, dot);
3026
10
        if (!store_name)
3027
0
            return 0;
3028
10
    }
3029
946
    else {
3030
946
        store_name = Py_NewRef(name);
3031
946
    }
3032
956
    if (!_PyUnicode_EqualToASCIIString(name, "*")) {
3033
935
        int r = symtable_add_def(st, store_name, DEF_IMPORT, LOCATION(a));
3034
935
        Py_DECREF(store_name);
3035
935
        return r;
3036
935
    }
3037
21
    else {
3038
21
        if (st->st_cur->ste_type != ModuleBlock) {
3039
0
            PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING);
3040
0
            SET_ERROR_LOCATION(st->st_filename, LOCATION(a));
3041
0
            Py_DECREF(store_name);
3042
0
            return 0;
3043
0
        }
3044
21
        Py_DECREF(store_name);
3045
21
        return 1;
3046
21
    }
3047
956
}
3048
3049
3050
static int
3051
symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
3052
1
{
3053
1
    st->st_cur->ste_comp_iter_target = 1;
3054
1
    VISIT(st, expr, lc->target);
3055
1
    st->st_cur->ste_comp_iter_target = 0;
3056
1
    st->st_cur->ste_comp_iter_expr++;
3057
1
    VISIT(st, expr, lc->iter);
3058
1
    st->st_cur->ste_comp_iter_expr--;
3059
1
    VISIT_SEQ(st, expr, lc->ifs);
3060
1
    if (lc->is_async) {
3061
0
        st->st_cur->ste_coroutine = 1;
3062
0
    }
3063
1
    return 1;
3064
1
}
3065
3066
3067
static int
3068
symtable_visit_keyword(struct symtable *st, keyword_ty k)
3069
1.84k
{
3070
1.84k
    VISIT(st, expr, k->value);
3071
1.84k
    return 1;
3072
1.84k
}
3073
3074
3075
static int
3076
symtable_handle_comprehension(struct symtable *st, expr_ty e,
3077
                              identifier scope_name, asdl_comprehension_seq *generators,
3078
                              expr_ty elt, expr_ty value)
3079
95
{
3080
95
    int is_generator = (e->kind == GeneratorExp_kind);
3081
95
    comprehension_ty outermost = ((comprehension_ty)
3082
95
                                    asdl_seq_GET(generators, 0));
3083
    /* Outermost iterator is evaluated in current scope */
3084
95
    st->st_cur->ste_comp_iter_expr++;
3085
95
    VISIT(st, expr, outermost->iter);
3086
95
    st->st_cur->ste_comp_iter_expr--;
3087
    /* Create comprehension scope for the rest */
3088
95
    if (!scope_name ||
3089
95
        !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, LOCATION(e))) {
3090
0
        return 0;
3091
0
    }
3092
95
    switch(e->kind) {
3093
43
        case ListComp_kind:
3094
43
            st->st_cur->ste_comprehension = ListComprehension;
3095
43
            break;
3096
7
        case SetComp_kind:
3097
7
            st->st_cur->ste_comprehension = SetComprehension;
3098
7
            break;
3099
5
        case DictComp_kind:
3100
5
            st->st_cur->ste_comprehension = DictComprehension;
3101
5
            break;
3102
40
        default:
3103
40
            st->st_cur->ste_comprehension = GeneratorExpression;
3104
40
            break;
3105
95
    }
3106
95
    if (outermost->is_async) {
3107
0
        st->st_cur->ste_coroutine = 1;
3108
0
    }
3109
3110
    /* Outermost iter is received as an argument */
3111
95
    if (!symtable_implicit_arg(st, 0)) {
3112
0
        symtable_exit_block(st);
3113
0
        return 0;
3114
0
    }
3115
    /* Visit iteration variable target, and mark them as such */
3116
95
    st->st_cur->ste_comp_iter_target = 1;
3117
95
    VISIT(st, expr, outermost->target);
3118
95
    st->st_cur->ste_comp_iter_target = 0;
3119
    /* Visit the rest of the comprehension body */
3120
95
    VISIT_SEQ(st, expr, outermost->ifs);
3121
95
    VISIT_SEQ_TAIL(st, comprehension, generators, 1);
3122
95
    if (value)
3123
5
        VISIT(st, expr, value);
3124
95
    VISIT(st, expr, elt);
3125
95
    st->st_cur->ste_generator = is_generator;
3126
95
    int is_async = st->st_cur->ste_coroutine && !is_generator;
3127
95
    if (!symtable_exit_block(st)) {
3128
0
        return 0;
3129
0
    }
3130
95
    if (is_async &&
3131
0
        !IS_ASYNC_DEF(st) &&
3132
0
        st->st_cur->ste_comprehension == NoComprehension &&
3133
0
        !allows_top_level_await(st))
3134
0
    {
3135
0
        PyErr_SetString(PyExc_SyntaxError, "asynchronous comprehension outside of "
3136
0
                                           "an asynchronous function");
3137
0
        SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3138
0
        return 0;
3139
0
    }
3140
95
    if (is_async) {
3141
0
        st->st_cur->ste_coroutine = 1;
3142
0
    }
3143
95
    return 1;
3144
95
}
3145
3146
static int
3147
symtable_visit_genexp(struct symtable *st, expr_ty e)
3148
40
{
3149
40
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_genexpr),
3150
40
                                         e->v.GeneratorExp.generators,
3151
40
                                         e->v.GeneratorExp.elt, NULL);
3152
40
}
3153
3154
static int
3155
symtable_visit_listcomp(struct symtable *st, expr_ty e)
3156
43
{
3157
43
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_listcomp),
3158
43
                                         e->v.ListComp.generators,
3159
43
                                         e->v.ListComp.elt, NULL);
3160
43
}
3161
3162
static int
3163
symtable_visit_setcomp(struct symtable *st, expr_ty e)
3164
7
{
3165
7
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_setcomp),
3166
7
                                         e->v.SetComp.generators,
3167
7
                                         e->v.SetComp.elt, NULL);
3168
7
}
3169
3170
static int
3171
symtable_visit_dictcomp(struct symtable *st, expr_ty e)
3172
5
{
3173
5
    return symtable_handle_comprehension(st, e, &_Py_STR(anon_dictcomp),
3174
5
                                         e->v.DictComp.generators,
3175
5
                                         e->v.DictComp.key,
3176
5
                                         e->v.DictComp.value);
3177
5
}
3178
3179
static int
3180
symtable_raise_if_annotation_block(struct symtable *st, const char *name, expr_ty e)
3181
239
{
3182
239
    _Py_block_ty type = st->st_cur->ste_type;
3183
239
    if (type == AnnotationBlock)
3184
0
        PyErr_Format(PyExc_SyntaxError, ANNOTATION_NOT_ALLOWED, name);
3185
239
    else if (type == TypeVariableBlock) {
3186
0
        const char *info = st->st_cur->ste_scope_info;
3187
0
        assert(info != NULL); // e.g., info == "a ParamSpec default"
3188
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_VARIABLE, name, info);
3189
0
    }
3190
239
    else if (type == TypeAliasBlock) {
3191
        // for now, we do not have any extra information
3192
0
        assert(st->st_cur->ste_scope_info == NULL);
3193
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_ALIAS, name);
3194
0
    }
3195
239
    else if (type == TypeParametersBlock) {
3196
        // for now, we do not have any extra information
3197
0
        assert(st->st_cur->ste_scope_info == NULL);
3198
0
        PyErr_Format(PyExc_SyntaxError, EXPR_NOT_ALLOWED_IN_TYPE_PARAMETERS, name);
3199
0
    }
3200
239
    else
3201
239
        return 1;
3202
3203
0
    SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3204
0
    return 0;
3205
239
}
3206
3207
static int
3208
0
symtable_raise_if_comprehension_block(struct symtable *st, expr_ty e) {
3209
0
    _Py_comprehension_ty type = st->st_cur->ste_comprehension;
3210
0
    PyErr_SetString(PyExc_SyntaxError,
3211
0
            (type == ListComprehension) ? "'yield' inside list comprehension" :
3212
0
            (type == SetComprehension) ? "'yield' inside set comprehension" :
3213
0
            (type == DictComprehension) ? "'yield' inside dict comprehension" :
3214
0
            "'yield' inside generator expression");
3215
0
    SET_ERROR_LOCATION(st->st_filename, LOCATION(e));
3216
0
    return 0;
3217
0
}
3218
3219
static int
3220
5
symtable_raise_if_not_coroutine(struct symtable *st, const char *msg, _Py_SourceLocation loc) {
3221
5
    if (!st->st_cur->ste_coroutine) {
3222
0
        PyErr_SetString(PyExc_SyntaxError, msg);
3223
0
        SET_ERROR_LOCATION(st->st_filename, loc);
3224
0
        return 0;
3225
0
    }
3226
5
    return 1;
3227
5
}
3228
3229
struct symtable *
3230
_Py_SymtableStringObjectFlags(const char *str, PyObject *filename,
3231
                              int start, PyCompilerFlags *flags, PyObject *module)
3232
0
{
3233
0
    struct symtable *st;
3234
0
    mod_ty mod;
3235
0
    PyArena *arena;
3236
3237
0
    arena = _PyArena_New();
3238
0
    if (arena == NULL)
3239
0
        return NULL;
3240
3241
0
    mod = _PyParser_ASTFromString(str, filename, start, flags, arena, module);
3242
0
    if (mod == NULL) {
3243
0
        _PyArena_Free(arena);
3244
0
        return NULL;
3245
0
    }
3246
0
    _PyFutureFeatures future;
3247
0
    if (!_PyFuture_FromAST(mod, filename, &future)) {
3248
0
        _PyArena_Free(arena);
3249
0
        return NULL;
3250
0
    }
3251
0
    future.ff_features |= flags->cf_flags;
3252
0
    st = _PySymtable_Build(mod, filename, &future);
3253
0
    _PyArena_Free(arena);
3254
0
    return st;
3255
0
}
3256
3257
PyObject *
3258
_Py_MaybeMangle(PyObject *privateobj, PySTEntryObject *ste, PyObject *name)
3259
152k
{
3260
    /* Special case for type parameter blocks around generic classes:
3261
     * we want to mangle type parameter names (so a type param with a private
3262
     * name can be used inside the class body), but we don't want to mangle
3263
     * any other names that appear within the type parameter scope.
3264
     */
3265
152k
    if (ste->ste_mangled_names != NULL) {
3266
0
        int result = PySet_Contains(ste->ste_mangled_names, name);
3267
0
        if (result < 0) {
3268
0
            return NULL;
3269
0
        }
3270
0
        if (result == 0) {
3271
0
            return Py_NewRef(name);
3272
0
        }
3273
0
    }
3274
152k
    return _Py_Mangle(privateobj, name);
3275
152k
}
3276
3277
int
3278
_Py_IsPrivateName(PyObject *ident)
3279
0
{
3280
0
    if (!PyUnicode_Check(ident)) {
3281
0
        return 0;
3282
0
    }
3283
0
    Py_ssize_t nlen = PyUnicode_GET_LENGTH(ident);
3284
0
    if (nlen < 3 ||
3285
0
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3286
0
        PyUnicode_READ_CHAR(ident, 1) != '_')
3287
0
    {
3288
0
        return 0;
3289
0
    }
3290
0
    if (PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3291
0
        PyUnicode_READ_CHAR(ident, nlen-2) == '_')
3292
0
    {
3293
0
        return 0; /* Don't mangle __whatever__ */
3294
0
    }
3295
0
    return 1;
3296
0
}
3297
3298
PyObject *
3299
_Py_Mangle(PyObject *privateobj, PyObject *ident)
3300
157k
{
3301
    /* Name mangling: __private becomes _classname__private.
3302
       This is independent from how the name is used. */
3303
157k
    if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
3304
75.8k
        PyUnicode_READ_CHAR(ident, 0) != '_' ||
3305
150k
        PyUnicode_READ_CHAR(ident, 1) != '_') {
3306
150k
        return Py_NewRef(ident);
3307
150k
    }
3308
7.77k
    size_t nlen = PyUnicode_GET_LENGTH(ident);
3309
7.77k
    size_t plen = PyUnicode_GET_LENGTH(privateobj);
3310
    /* Don't mangle __id__ or names with dots.
3311
3312
       The only time a name with a dot can occur is when
3313
       we are compiling an import statement that has a
3314
       package name.
3315
3316
       TODO(jhylton): Decide whether we want to support
3317
       mangling of the module name, e.g. __M.X.
3318
    */
3319
7.77k
    if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
3320
7.68k
         PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
3321
7.68k
        PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
3322
7.68k
        return Py_NewRef(ident); /* Don't mangle __whatever__ */
3323
7.68k
    }
3324
    /* Strip leading underscores from class name */
3325
90
    size_t ipriv = 0;
3326
90
    while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_') {
3327
0
        ipriv++;
3328
0
    }
3329
90
    if (ipriv == plen) {
3330
0
        return Py_NewRef(ident); /* Don't mangle if class is just underscores */
3331
0
    }
3332
3333
90
    if (nlen + (plen - ipriv) >= PY_SSIZE_T_MAX - 1) {
3334
0
        PyErr_SetString(PyExc_OverflowError,
3335
0
                        "private identifier too large to be mangled");
3336
0
        return NULL;
3337
0
    }
3338
3339
90
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(1 + nlen + (plen - ipriv));
3340
90
    if (!writer) {
3341
0
        return NULL;
3342
0
    }
3343
    // ident = "_" + priv[ipriv:] + ident
3344
90
    if (PyUnicodeWriter_WriteChar(writer, '_') < 0) {
3345
0
        goto error;
3346
0
    }
3347
90
    if (PyUnicodeWriter_WriteSubstring(writer, privateobj, ipriv, plen) < 0) {
3348
0
        goto error;
3349
0
    }
3350
90
    if (PyUnicodeWriter_WriteStr(writer, ident) < 0) {
3351
0
        goto error;
3352
0
    }
3353
90
    return PyUnicodeWriter_Finish(writer);
3354
3355
0
error:
3356
0
    PyUnicodeWriter_Discard(writer);
3357
    return NULL;
3358
90
}