Coverage Report

Created: 2026-08-13 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Python/compile.c
Line
Count
Source
1
/*
2
 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3
 *
4
 * The primary entry point is _PyAST_Compile(), which returns a
5
 * PyCodeObject.  The compiler makes several passes to build the code
6
 * object:
7
 *   1. Checks for future statements.  See future.c
8
 *   2. Builds a symbol table.  See symtable.c.
9
 *   3. Generate an instruction sequence. See compiler_mod() in this file, which
10
 *      calls functions from codegen.c.
11
 *   4. Generate a control flow graph and run optimizations on it.  See flowgraph.c.
12
 *   5. Assemble the basic blocks into final code.  See optimize_and_assemble() in
13
 *      this file, and assembler.c.
14
 *
15
 */
16
17
#include "Python.h"
18
#include "pycore_ast.h"           // PyAST_Check()
19
#include "pycore_code.h"
20
#include "pycore_compile.h"
21
#include "pycore_flowgraph.h"     // _PyCfg_FromInstructionSequence()
22
#include "pycore_pystate.h"       // _Py_GetConfig()
23
#include "pycore_runtime.h"       // _Py_ID()
24
#include "pycore_setobject.h"     // _PySet_NextEntry()
25
#include "pycore_stats.h"
26
#include "pycore_tuple.h"         // _PyTuple_FromPair
27
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString()
28
29
#include "cpython/code.h"
30
31
#include <stdbool.h>
32
33
34
#undef SUCCESS
35
#undef ERROR
36
1.68M
#define SUCCESS 0
37
1.87k
#define ERROR -1
38
39
#define RETURN_IF_ERROR(X)  \
40
583k
    do {                    \
41
583k
        if ((X) == -1) {    \
42
502
            return ERROR;   \
43
502
        }                   \
44
583k
    } while (0)
45
46
typedef _Py_SourceLocation location;
47
typedef _PyJumpTargetLabel jump_target_label;
48
typedef _PyInstructionSequence instr_sequence;
49
typedef struct _PyCfgBuilder cfg_builder;
50
typedef _PyCompile_FBlockInfo fblockinfo;
51
typedef enum _PyCompile_FBlockType fblocktype;
52
53
/* The following items change on entry and exit of code blocks.
54
   They must be saved and restored when returning to a block.
55
*/
56
struct compiler_unit {
57
    PySTEntryObject *u_ste;
58
59
    int u_scope_type;
60
61
    PyObject *u_private;            /* for private name mangling */
62
    PyObject *u_static_attributes;  /* for class: attributes accessed via self.X */
63
    PyObject *u_deferred_annotations; /* AnnAssign nodes deferred to the end of compilation */
64
    PyObject *u_conditional_annotation_indices;  /* indices of annotations that are conditionally executed (or -1 for unconditional annotations) */
65
    long u_next_conditional_annotation_index;  /* index of the next conditional annotation */
66
67
    instr_sequence *u_instr_sequence; /* codegen output */
68
    instr_sequence *u_stashed_instr_sequence; /* temporarily stashed parent instruction sequence */
69
70
    int u_nfblocks;
71
    int u_in_inlined_comp;
72
    int u_in_conditional_block;
73
74
    _PyCompile_FBlockInfo u_fblock[CO_MAXBLOCKS];
75
76
    _PyCompile_CodeUnitMetadata u_metadata;
77
};
78
79
/* This struct captures the global state of a compilation.
80
81
The u pointer points to the current compilation unit, while units
82
for enclosing blocks are stored in c_stack.     The u and c_stack are
83
managed by _PyCompile_EnterScope() and _PyCompile_ExitScope().
84
85
Note that we don't track recursion levels during compilation - the
86
task of detecting and rejecting excessive levels of nesting is
87
handled by the symbol analysis pass.
88
89
*/
90
91
typedef struct _PyCompiler {
92
    PyObject *c_filename;
93
    struct symtable *c_st;
94
    _PyFutureFeatures c_future;  /* module's __future__ */
95
    PyCompilerFlags c_flags;
96
97
    int c_optimize;              /* optimization level */
98
    int c_interactive;           /* true if in interactive mode */
99
    PyObject *c_const_cache;     /* Python dict holding all constants,
100
                                    including names tuple */
101
    struct compiler_unit *u;     /* compiler state for current block */
102
    PyObject *c_stack;           /* Python list holding compiler_unit ptrs */
103
104
    bool c_save_nested_seqs;     /* if true, construct recursive instruction sequences
105
                                  * (including instructions for nested code objects)
106
                                  */
107
    int c_disable_warning;
108
    PyObject *c_module;
109
} compiler;
110
111
static int
112
compiler_setup(compiler *c, mod_ty mod, PyObject *filename,
113
               PyCompilerFlags *flags, int optimize, PyArena *arena,
114
               PyObject *module)
115
10.8k
{
116
10.8k
    PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
117
118
10.8k
    c->c_const_cache = PyDict_New();
119
10.8k
    if (!c->c_const_cache) {
120
0
        return ERROR;
121
0
    }
122
123
10.8k
    c->c_stack = PyList_New(0);
124
10.8k
    if (!c->c_stack) {
125
0
        return ERROR;
126
0
    }
127
128
10.8k
    c->c_filename = Py_NewRef(filename);
129
10.8k
    if (!_PyFuture_FromAST(mod, filename, &c->c_future)) {
130
14
        return ERROR;
131
14
    }
132
10.8k
    c->c_module = Py_XNewRef(module);
133
10.8k
    if (!flags) {
134
0
        flags = &local_flags;
135
0
    }
136
10.8k
    int merged = c->c_future.ff_features | flags->cf_flags;
137
10.8k
    c->c_future.ff_features = merged;
138
10.8k
    flags->cf_flags = merged;
139
10.8k
    c->c_flags = *flags;
140
10.8k
    c->c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
141
10.8k
    c->c_save_nested_seqs = false;
142
143
10.8k
    if (!_PyAST_Preprocess(mod, arena, filename, c->c_optimize, merged,
144
10.8k
                           0, 1, module))
145
0
    {
146
0
        return ERROR;
147
0
    }
148
10.8k
    c->c_st = _PySymtable_Build(mod, filename, &c->c_future);
149
10.8k
    if (c->c_st == NULL) {
150
254
        if (!PyErr_Occurred()) {
151
0
            PyErr_SetString(PyExc_SystemError, "no symtable");
152
0
        }
153
254
        return ERROR;
154
254
    }
155
10.5k
    return SUCCESS;
156
10.8k
}
157
158
static void
159
compiler_free(compiler *c)
160
10.8k
{
161
10.8k
    if (c->c_st) {
162
10.5k
        _PySymtable_Free(c->c_st);
163
10.5k
    }
164
10.8k
    Py_XDECREF(c->c_filename);
165
10.8k
    Py_XDECREF(c->c_module);
166
10.8k
    Py_XDECREF(c->c_const_cache);
167
10.8k
    Py_XDECREF(c->c_stack);
168
10.8k
    PyMem_Free(c);
169
10.8k
}
170
171
static compiler*
172
new_compiler(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
173
             int optimize, PyArena *arena, PyObject *module)
174
10.8k
{
175
10.8k
    compiler *c = PyMem_Calloc(1, sizeof(compiler));
176
10.8k
    if (c == NULL) {
177
0
        PyErr_NoMemory();
178
0
        return NULL;
179
0
    }
180
10.8k
    if (compiler_setup(c, mod, filename, pflags, optimize, arena, module) < 0) {
181
268
        compiler_free(c);
182
268
        return NULL;
183
268
    }
184
10.5k
    return c;
185
10.8k
}
186
187
static void
188
compiler_unit_free(struct compiler_unit *u)
189
53.3k
{
190
53.3k
    Py_CLEAR(u->u_instr_sequence);
191
53.3k
    Py_CLEAR(u->u_stashed_instr_sequence);
192
53.3k
    Py_CLEAR(u->u_ste);
193
53.3k
    Py_CLEAR(u->u_metadata.u_name);
194
53.3k
    Py_CLEAR(u->u_metadata.u_qualname);
195
53.3k
    Py_CLEAR(u->u_metadata.u_consts);
196
53.3k
    Py_CLEAR(u->u_metadata.u_names);
197
53.3k
    Py_CLEAR(u->u_metadata.u_varnames);
198
53.3k
    Py_CLEAR(u->u_metadata.u_freevars);
199
53.3k
    Py_CLEAR(u->u_metadata.u_cellvars);
200
53.3k
    Py_CLEAR(u->u_metadata.u_fasthidden);
201
53.3k
    Py_CLEAR(u->u_private);
202
53.3k
    Py_CLEAR(u->u_static_attributes);
203
53.3k
    Py_CLEAR(u->u_deferred_annotations);
204
53.3k
    Py_CLEAR(u->u_conditional_annotation_indices);
205
53.3k
    PyMem_Free(u);
206
53.3k
}
207
208
105k
#define CAPSULE_NAME "compile.c compiler unit"
209
210
int
211
_PyCompile_MaybeAddStaticAttributeToClass(compiler *c, expr_ty e)
212
13.4k
{
213
13.4k
    assert(e->kind == Attribute_kind);
214
13.4k
    expr_ty attr_value = e->v.Attribute.value;
215
13.4k
    if (attr_value->kind != Name_kind ||
216
8.17k
        e->v.Attribute.ctx != Store ||
217
793
        !_PyUnicode_EqualToASCIIString(attr_value->v.Name.id, "self"))
218
13.2k
    {
219
13.2k
        return SUCCESS;
220
13.2k
    }
221
164
    Py_ssize_t stack_size = PyList_GET_SIZE(c->c_stack);
222
321
    for (Py_ssize_t i = stack_size - 1; i >= 0; i--) {
223
157
        PyObject *capsule = PyList_GET_ITEM(c->c_stack, i);
224
0
        struct compiler_unit *u = (struct compiler_unit *)PyCapsule_GetPointer(
225
157
                                                              capsule, CAPSULE_NAME);
226
157
        assert(u);
227
157
        if (u->u_scope_type == COMPILE_SCOPE_CLASS) {
228
0
            assert(u->u_static_attributes);
229
0
            RETURN_IF_ERROR(PySet_Add(u->u_static_attributes, e->v.Attribute.attr));
230
0
            break;
231
0
        }
232
157
    }
233
164
    return SUCCESS;
234
164
}
235
236
static int
237
compiler_set_qualname(compiler *c)
238
42.8k
{
239
42.8k
    Py_ssize_t stack_size;
240
42.8k
    struct compiler_unit *u = c->u;
241
42.8k
    PyObject *name, *base;
242
243
42.8k
    base = NULL;
244
42.8k
    stack_size = PyList_GET_SIZE(c->c_stack);
245
42.8k
    assert(stack_size >= 1);
246
42.8k
    if (stack_size > 1) {
247
18.1k
        int scope, force_global = 0;
248
18.1k
        struct compiler_unit *parent;
249
18.1k
        PyObject *mangled, *capsule;
250
251
18.1k
        capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
252
18.1k
        parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
253
18.1k
        assert(parent);
254
18.1k
        if (parent->u_scope_type == COMPILE_SCOPE_ANNOTATIONS) {
255
            /* The parent is an annotation scope, so we need to
256
               look at the grandparent. */
257
7.96k
            if (stack_size == 2) {
258
                // If we're immediately within the module, we can skip
259
                // the rest and just set the qualname to be the same as name.
260
6.65k
                u->u_metadata.u_qualname = Py_NewRef(u->u_metadata.u_name);
261
6.65k
                return SUCCESS;
262
6.65k
            }
263
1.31k
            capsule = PyList_GET_ITEM(c->c_stack, stack_size - 2);
264
1.31k
            parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
265
1.31k
            assert(parent);
266
1.31k
        }
267
268
11.5k
        if (u->u_scope_type == COMPILE_SCOPE_FUNCTION
269
11.5k
            || u->u_scope_type == COMPILE_SCOPE_ASYNC_FUNCTION
270
11.5k
            || u->u_scope_type == COMPILE_SCOPE_CLASS) {
271
889
            assert(u->u_metadata.u_name);
272
889
            mangled = _Py_Mangle(parent->u_private, u->u_metadata.u_name);
273
889
            if (!mangled) {
274
0
                return ERROR;
275
0
            }
276
277
889
            scope = _PyST_GetScope(parent->u_ste, mangled);
278
889
            Py_DECREF(mangled);
279
889
            RETURN_IF_ERROR(scope);
280
889
            assert(scope != GLOBAL_IMPLICIT);
281
889
            if (scope == GLOBAL_EXPLICIT)
282
0
                force_global = 1;
283
889
        }
284
285
11.5k
        if (!force_global) {
286
11.5k
            if (parent->u_scope_type == COMPILE_SCOPE_FUNCTION
287
11.4k
                || parent->u_scope_type == COMPILE_SCOPE_ASYNC_FUNCTION
288
9.78k
                || parent->u_scope_type == COMPILE_SCOPE_LAMBDA)
289
5.03k
            {
290
5.03k
                _Py_DECLARE_STR(dot_locals, ".<locals>");
291
5.03k
                base = PyUnicode_Concat(parent->u_metadata.u_qualname,
292
5.03k
                                        &_Py_STR(dot_locals));
293
5.03k
                if (base == NULL) {
294
0
                    return ERROR;
295
0
                }
296
5.03k
            }
297
6.49k
            else {
298
6.49k
                base = Py_NewRef(parent->u_metadata.u_qualname);
299
6.49k
            }
300
11.5k
        }
301
11.5k
        if (u->u_ste->ste_function_name != NULL) {
302
1
            PyObject *tmp = base;
303
1
            base = PyUnicode_FromFormat("%U.%U",
304
1
                base,
305
1
                u->u_ste->ste_function_name);
306
1
            Py_DECREF(tmp);
307
1
            if (base == NULL) {
308
0
                return ERROR;
309
0
            }
310
1
        }
311
11.5k
    }
312
24.6k
    else if (u->u_ste->ste_function_name != NULL) {
313
3.45k
        base = Py_NewRef(u->u_ste->ste_function_name);
314
3.45k
    }
315
316
36.1k
    if (base != NULL) {
317
14.9k
        name = PyUnicode_Concat(base, _Py_LATIN1_CHR('.'));
318
14.9k
        Py_DECREF(base);
319
14.9k
        if (name == NULL) {
320
0
            return ERROR;
321
0
        }
322
14.9k
        PyUnicode_Append(&name, u->u_metadata.u_name);
323
14.9k
        if (name == NULL) {
324
0
            return ERROR;
325
0
        }
326
14.9k
    }
327
21.1k
    else {
328
21.1k
        name = Py_NewRef(u->u_metadata.u_name);
329
21.1k
    }
330
36.1k
    u->u_metadata.u_qualname = name;
331
332
36.1k
    return SUCCESS;
333
36.1k
}
334
335
/* Merge const *o* and return constant key object.
336
 * If recursive, insert all elements if o is a tuple or frozen set.
337
 */
338
static PyObject*
339
const_cache_insert(PyObject *const_cache, PyObject *o, bool recursive)
340
2.25M
{
341
2.25M
    assert(PyDict_CheckExact(const_cache));
342
    // None and Ellipsis are immortal objects, and key is the singleton.
343
    // No need to merge object and key.
344
2.25M
    if (o == Py_None || o == Py_Ellipsis) {
345
154k
        return o;
346
154k
    }
347
348
2.10M
    PyObject *key = _PyCode_ConstantKey(o);
349
2.10M
    if (key == NULL) {
350
0
        return NULL;
351
0
    }
352
353
2.10M
    PyObject *t;
354
2.10M
    int res = PyDict_SetDefaultRef(const_cache, key, key, &t);
355
2.10M
    if (res != 0) {
356
        // o was not inserted into const_cache. t is either the existing value
357
        // or NULL (on error).
358
1.67M
        Py_DECREF(key);
359
1.67M
        return t;
360
1.67M
    }
361
426k
    Py_DECREF(t);
362
363
426k
    if (!recursive) {
364
279k
        return key;
365
279k
    }
366
367
    // We registered o in const_cache.
368
    // When o is a tuple or frozenset, we want to merge its
369
    // items too.
370
147k
    if (PyTuple_CheckExact(o)) {
371
2.63k
        Py_ssize_t len = PyTuple_GET_SIZE(o);
372
5.28k
        for (Py_ssize_t i = 0; i < len; i++) {
373
2.64k
            PyObject *item = PyTuple_GET_ITEM(o, i);
374
0
            PyObject *u = const_cache_insert(const_cache, item, recursive);
375
2.64k
            if (u == NULL) {
376
0
                Py_DECREF(key);
377
0
                return NULL;
378
0
            }
379
380
            // See _PyCode_ConstantKey()
381
2.64k
            PyObject *v;  // borrowed
382
2.64k
            if (PyTuple_CheckExact(u)) {
383
0
                v = PyTuple_GET_ITEM(u, 1);
384
0
            }
385
2.64k
            else {
386
2.64k
                v = u;
387
2.64k
            }
388
2.64k
            if (v != item) {
389
0
                PyTuple_SET_ITEM(o, i, Py_NewRef(v));
390
0
                Py_DECREF(item);
391
0
            }
392
393
2.64k
            Py_DECREF(u);
394
2.64k
        }
395
2.63k
    }
396
144k
    else if (PyFrozenSet_CheckExact(o)) {
397
        // *key* is tuple. And its first item is frozenset of
398
        // constant keys.
399
        // See _PyCode_ConstantKey() for detail.
400
0
        assert(PyTuple_CheckExact(key));
401
0
        assert(PyTuple_GET_SIZE(key) == 2);
402
403
0
        Py_ssize_t len = PySet_GET_SIZE(o);
404
0
        if (len == 0) {  // empty frozenset should not be re-created.
405
0
            return key;
406
0
        }
407
0
        PyObject *tuple = PyTuple_New(len);
408
0
        if (tuple == NULL) {
409
0
            Py_DECREF(key);
410
0
            return NULL;
411
0
        }
412
0
        Py_ssize_t i = 0, pos = 0;
413
0
        PyObject *item;
414
0
        Py_hash_t hash;
415
0
        while (_PySet_NextEntry(o, &pos, &item, &hash)) {
416
0
            PyObject *k = const_cache_insert(const_cache, item, recursive);
417
0
            if (k == NULL) {
418
0
                Py_DECREF(tuple);
419
0
                Py_DECREF(key);
420
0
                return NULL;
421
0
            }
422
0
            PyObject *u;
423
0
            if (PyTuple_CheckExact(k)) {
424
0
                u = Py_NewRef(PyTuple_GET_ITEM(k, 1));
425
0
                Py_DECREF(k);
426
0
            }
427
0
            else {
428
0
                u = k;
429
0
            }
430
0
            PyTuple_SET_ITEM(tuple, i, u);  // Steals reference of u.
431
0
            i++;
432
0
        }
433
434
        // Instead of rewriting o, we create new frozenset and embed in the
435
        // key tuple.  Caller should get merged frozenset from the key tuple.
436
0
        PyObject *new = PyFrozenSet_New(tuple);
437
0
        Py_DECREF(tuple);
438
0
        if (new == NULL) {
439
0
            Py_DECREF(key);
440
0
            return NULL;
441
0
        }
442
0
        assert(PyTuple_GET_ITEM(key, 1) == o);
443
0
        Py_DECREF(o);
444
0
        PyTuple_SET_ITEM(key, 1, new);
445
0
    }
446
447
147k
    return key;
448
147k
}
449
450
static PyObject*
451
merge_consts_recursive(PyObject *const_cache, PyObject *o)
452
1.27M
{
453
1.27M
    return const_cache_insert(const_cache, o, true);
454
1.27M
}
455
456
Py_ssize_t
457
_PyCompile_DictAddObj(PyObject *dict, PyObject *o)
458
1.90M
{
459
1.90M
    PyObject *v;
460
1.90M
    Py_ssize_t arg;
461
462
1.90M
    if (PyDict_GetItemRef(dict, o, &v) < 0) {
463
0
        return ERROR;
464
0
    }
465
1.90M
    if (!v) {
466
552k
        arg = PyDict_GET_SIZE(dict);
467
552k
        v = PyLong_FromSsize_t(arg);
468
552k
        if (!v) {
469
0
            return ERROR;
470
0
        }
471
552k
        if (PyDict_SetItem(dict, o, v) < 0) {
472
0
            Py_DECREF(v);
473
0
            return ERROR;
474
0
        }
475
552k
    }
476
1.35M
    else
477
1.35M
        arg = PyLong_AsLong(v);
478
1.90M
    Py_DECREF(v);
479
1.90M
    return arg;
480
1.90M
}
481
482
Py_ssize_t
483
_PyCompile_AddConst(compiler *c, PyObject *o)
484
1.27M
{
485
1.27M
    PyObject *key = merge_consts_recursive(c->c_const_cache, o);
486
1.27M
    if (key == NULL) {
487
0
        return ERROR;
488
0
    }
489
490
1.27M
    Py_ssize_t arg = _PyCompile_DictAddObj(c->u->u_metadata.u_consts, key);
491
1.27M
    Py_DECREF(key);
492
1.27M
    return arg;
493
1.27M
}
494
495
static PyObject *
496
list2dict(PyObject *list)
497
53.3k
{
498
53.3k
    Py_ssize_t i, n;
499
53.3k
    PyObject *v, *k;
500
53.3k
    PyObject *dict = PyDict_New();
501
53.3k
    if (!dict) return NULL;
502
503
53.3k
    n = PyList_Size(list);
504
78.2k
    for (i = 0; i < n; i++) {
505
24.8k
        v = PyLong_FromSsize_t(i);
506
24.8k
        if (!v) {
507
0
            Py_DECREF(dict);
508
0
            return NULL;
509
0
        }
510
24.8k
        k = PyList_GET_ITEM(list, i);
511
24.8k
        if (PyDict_SetItem(dict, k, v) < 0) {
512
0
            Py_DECREF(v);
513
0
            Py_DECREF(dict);
514
0
            return NULL;
515
0
        }
516
24.8k
        Py_DECREF(v);
517
24.8k
    }
518
53.3k
    return dict;
519
53.3k
}
520
521
/* Return new dict containing names from src that match scope(s).
522
523
src is a symbol table dictionary.  If the scope of a name matches
524
either scope_type or flag is set, insert it into the new dict.  The
525
values are integers, starting at offset and increasing by one for
526
each key.
527
*/
528
529
static PyObject *
530
dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
531
106k
{
532
106k
    Py_ssize_t i = offset, num_keys, key_i;
533
106k
    PyObject *k, *v, *dest = PyDict_New();
534
106k
    PyObject *sorted_keys;
535
536
106k
    assert(offset >= 0);
537
106k
    if (dest == NULL)
538
0
        return NULL;
539
540
    /* Sort the keys so that we have a deterministic order on the indexes
541
       saved in the returned dictionary.  These indexes are used as indexes
542
       into the free and cell var storage.  Therefore if they aren't
543
       deterministic, then the generated bytecode is not deterministic.
544
    */
545
106k
    sorted_keys = PyDict_Keys(src);
546
106k
    if (sorted_keys == NULL) {
547
0
        Py_DECREF(dest);
548
0
        return NULL;
549
0
    }
550
106k
    if (PyList_Sort(sorted_keys) != 0) {
551
0
        Py_DECREF(sorted_keys);
552
0
        Py_DECREF(dest);
553
0
        return NULL;
554
0
    }
555
106k
    num_keys = PyList_GET_SIZE(sorted_keys);
556
557
577k
    for (key_i = 0; key_i < num_keys; key_i++) {
558
470k
        k = PyList_GET_ITEM(sorted_keys, key_i);
559
0
        v = PyDict_GetItemWithError(src, k);
560
470k
        if (!v) {
561
0
            if (!PyErr_Occurred()) {
562
0
                PyErr_SetObject(PyExc_KeyError, k);
563
0
            }
564
0
            Py_DECREF(sorted_keys);
565
0
            Py_DECREF(dest);
566
0
            return NULL;
567
0
        }
568
470k
        long vi = PyLong_AsLong(v);
569
470k
        if (vi == -1 && PyErr_Occurred()) {
570
0
            Py_DECREF(sorted_keys);
571
0
            Py_DECREF(dest);
572
0
            return NULL;
573
0
        }
574
470k
        if (SYMBOL_TO_SCOPE(vi) == scope_type || vi & flag) {
575
14.7k
            PyObject *item = PyLong_FromSsize_t(i);
576
14.7k
            if (item == NULL) {
577
0
                Py_DECREF(sorted_keys);
578
0
                Py_DECREF(dest);
579
0
                return NULL;
580
0
            }
581
14.7k
            i++;
582
14.7k
            if (PyDict_SetItem(dest, k, item) < 0) {
583
0
                Py_DECREF(sorted_keys);
584
0
                Py_DECREF(item);
585
0
                Py_DECREF(dest);
586
0
                return NULL;
587
0
            }
588
14.7k
            Py_DECREF(item);
589
14.7k
        }
590
470k
    }
591
106k
    Py_DECREF(sorted_keys);
592
106k
    return dest;
593
106k
}
594
595
int
596
_PyCompile_EnterScope(compiler *c, identifier name, int scope_type,
597
                       void *key, int lineno, PyObject *private,
598
                      _PyCompile_CodeUnitMetadata *umd)
599
53.3k
{
600
53.3k
    struct compiler_unit *u;
601
53.3k
    u = (struct compiler_unit *)PyMem_Calloc(1, sizeof(struct compiler_unit));
602
53.3k
    if (!u) {
603
0
        PyErr_NoMemory();
604
0
        return ERROR;
605
0
    }
606
53.3k
    u->u_scope_type = scope_type;
607
53.3k
    if (umd != NULL) {
608
27.0k
        u->u_metadata = *umd;
609
27.0k
    }
610
26.3k
    else {
611
26.3k
        u->u_metadata.u_argcount = 0;
612
26.3k
        u->u_metadata.u_posonlyargcount = 0;
613
26.3k
        u->u_metadata.u_kwonlyargcount = 0;
614
26.3k
    }
615
53.3k
    u->u_ste = _PySymtable_Lookup(c->c_st, key);
616
53.3k
    if (!u->u_ste) {
617
0
        compiler_unit_free(u);
618
0
        return ERROR;
619
0
    }
620
53.3k
    u->u_metadata.u_name = Py_NewRef(name);
621
53.3k
    u->u_metadata.u_varnames = list2dict(u->u_ste->ste_varnames);
622
53.3k
    if (!u->u_metadata.u_varnames) {
623
0
        compiler_unit_free(u);
624
0
        return ERROR;
625
0
    }
626
53.3k
    u->u_metadata.u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, DEF_COMP_CELL, 0);
627
53.3k
    if (!u->u_metadata.u_cellvars) {
628
0
        compiler_unit_free(u);
629
0
        return ERROR;
630
0
    }
631
53.3k
    if (u->u_ste->ste_needs_class_closure) {
632
        /* Cook up an implicit __class__ cell. */
633
25
        Py_ssize_t res;
634
25
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS);
635
25
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__class__));
636
25
        if (res < 0) {
637
0
            compiler_unit_free(u);
638
0
            return ERROR;
639
0
        }
640
25
    }
641
53.3k
    if (u->u_ste->ste_needs_classdict) {
642
        /* Cook up an implicit __classdict__ cell. */
643
6.06k
        Py_ssize_t res;
644
6.06k
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS);
645
6.06k
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__classdict__));
646
6.06k
        if (res < 0) {
647
0
            compiler_unit_free(u);
648
0
            return ERROR;
649
0
        }
650
6.06k
    }
651
53.3k
    if (u->u_ste->ste_has_conditional_annotations) {
652
        /* Cook up an implicit __conditional_annotations__ cell */
653
2.90k
        Py_ssize_t res;
654
2.90k
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS || u->u_scope_type == COMPILE_SCOPE_MODULE);
655
2.90k
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__conditional_annotations__));
656
2.90k
        if (res < 0) {
657
0
            compiler_unit_free(u);
658
0
            return ERROR;
659
0
        }
660
2.90k
    }
661
662
53.3k
    u->u_metadata.u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
663
53.3k
                               PyDict_GET_SIZE(u->u_metadata.u_cellvars));
664
53.3k
    if (!u->u_metadata.u_freevars) {
665
0
        compiler_unit_free(u);
666
0
        return ERROR;
667
0
    }
668
669
53.3k
    u->u_metadata.u_fasthidden = PyDict_New();
670
53.3k
    if (!u->u_metadata.u_fasthidden) {
671
0
        compiler_unit_free(u);
672
0
        return ERROR;
673
0
    }
674
675
53.3k
    u->u_nfblocks = 0;
676
53.3k
    u->u_in_inlined_comp = 0;
677
53.3k
    u->u_metadata.u_firstlineno = lineno;
678
53.3k
    u->u_metadata.u_consts = PyDict_New();
679
53.3k
    if (!u->u_metadata.u_consts) {
680
0
        compiler_unit_free(u);
681
0
        return ERROR;
682
0
    }
683
53.3k
    u->u_metadata.u_names = PyDict_New();
684
53.3k
    if (!u->u_metadata.u_names) {
685
0
        compiler_unit_free(u);
686
0
        return ERROR;
687
0
    }
688
689
53.3k
    u->u_deferred_annotations = NULL;
690
53.3k
    u->u_conditional_annotation_indices = NULL;
691
53.3k
    u->u_next_conditional_annotation_index = 0;
692
53.3k
    if (scope_type == COMPILE_SCOPE_CLASS) {
693
13.0k
        u->u_static_attributes = PySet_New(0);
694
13.0k
        if (!u->u_static_attributes) {
695
0
            compiler_unit_free(u);
696
0
            return ERROR;
697
0
        }
698
13.0k
    }
699
40.3k
    else {
700
40.3k
        u->u_static_attributes = NULL;
701
40.3k
    }
702
703
53.3k
    u->u_instr_sequence = (instr_sequence*)_PyInstructionSequence_New();
704
53.3k
    if (!u->u_instr_sequence) {
705
0
        compiler_unit_free(u);
706
0
        return ERROR;
707
0
    }
708
53.3k
    u->u_stashed_instr_sequence = NULL;
709
710
    /* Push the old compiler_unit on the stack. */
711
53.3k
    if (c->u) {
712
42.8k
        PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
713
42.8k
        if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
714
0
            Py_XDECREF(capsule);
715
0
            compiler_unit_free(u);
716
0
            return ERROR;
717
0
        }
718
42.8k
        Py_DECREF(capsule);
719
42.8k
        if (private == NULL) {
720
27.0k
            private = c->u->u_private;
721
27.0k
        }
722
42.8k
    }
723
724
53.3k
    u->u_private = Py_XNewRef(private);
725
726
53.3k
    c->u = u;
727
53.3k
    if (scope_type != COMPILE_SCOPE_MODULE) {
728
42.8k
        RETURN_IF_ERROR(compiler_set_qualname(c));
729
42.8k
    }
730
53.3k
    return SUCCESS;
731
53.3k
}
732
733
void
734
_PyCompile_ExitScope(compiler *c)
735
53.3k
{
736
    // Don't call PySequence_DelItem() with an exception raised
737
53.3k
    PyObject *exc = PyErr_GetRaisedException();
738
739
53.3k
    instr_sequence *nested_seq = NULL;
740
53.3k
    if (c->c_save_nested_seqs) {
741
0
        nested_seq = c->u->u_instr_sequence;
742
0
        Py_INCREF(nested_seq);
743
0
    }
744
53.3k
    compiler_unit_free(c->u);
745
    /* Restore c->u to the parent unit. */
746
53.3k
    Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
747
53.3k
    if (n >= 0) {
748
42.8k
        PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
749
42.8k
        c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
750
42.8k
        assert(c->u);
751
        /* we are deleting from a list so this really shouldn't fail */
752
42.8k
        if (PySequence_DelItem(c->c_stack, n) < 0) {
753
0
            PyErr_FormatUnraisable("Exception ignored while removing "
754
0
                                   "the last compiler stack item");
755
0
        }
756
42.8k
        if (nested_seq != NULL) {
757
0
            if (_PyInstructionSequence_AddNested(c->u->u_instr_sequence, nested_seq) < 0) {
758
0
                PyErr_FormatUnraisable("Exception ignored while appending "
759
0
                                       "nested instruction sequence");
760
0
            }
761
0
        }
762
42.8k
    }
763
10.5k
    else {
764
10.5k
        c->u = NULL;
765
10.5k
    }
766
53.3k
    Py_XDECREF(nested_seq);
767
768
53.3k
    PyErr_SetRaisedException(exc);
769
53.3k
}
770
771
/*
772
 * Frame block handling functions
773
 */
774
775
int
776
_PyCompile_PushFBlock(compiler *c, location loc,
777
                     fblocktype t, jump_target_label block_label,
778
                     jump_target_label exit, void *datum)
779
32.4k
{
780
32.4k
    fblockinfo *f;
781
32.4k
    if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
782
7
        return _PyCompile_Error(c, loc, "too many statically nested blocks");
783
7
    }
784
32.4k
    f = &c->u->u_fblock[c->u->u_nfblocks++];
785
32.4k
    f->fb_type = t;
786
32.4k
    f->fb_block = block_label;
787
32.4k
    f->fb_loc = loc;
788
32.4k
    f->fb_exit = exit;
789
32.4k
    f->fb_datum = datum;
790
32.4k
    if (t == COMPILE_FBLOCK_FINALLY_END) {
791
2.14k
        c->c_disable_warning++;
792
2.14k
    }
793
32.4k
    return SUCCESS;
794
32.4k
}
795
796
void
797
_PyCompile_PopFBlock(compiler *c, fblocktype t, jump_target_label block_label)
798
32.1k
{
799
32.1k
    struct compiler_unit *u = c->u;
800
32.1k
    assert(u->u_nfblocks > 0);
801
32.1k
    u->u_nfblocks--;
802
32.1k
    assert(u->u_fblock[u->u_nfblocks].fb_type == t);
803
32.1k
    assert(SAME_JUMP_TARGET_LABEL(u->u_fblock[u->u_nfblocks].fb_block, block_label));
804
32.1k
    if (t == COMPILE_FBLOCK_FINALLY_END) {
805
2.14k
        c->c_disable_warning--;
806
2.14k
    }
807
32.1k
}
808
809
fblockinfo *
810
_PyCompile_TopFBlock(compiler *c)
811
2.57k
{
812
2.57k
    if (c->u->u_nfblocks == 0) {
813
229
        return NULL;
814
229
    }
815
2.34k
    return &c->u->u_fblock[c->u->u_nfblocks - 1];
816
2.57k
}
817
818
bool
819
_PyCompile_InExceptionHandler(compiler *c)
820
10.5k
{
821
12.1k
    for (Py_ssize_t i = 0; i < c->u->u_nfblocks; i++) {
822
1.75k
        fblockinfo *block = &c->u->u_fblock[i];
823
1.75k
        switch (block->fb_type) {
824
0
            case COMPILE_FBLOCK_TRY_EXCEPT:
825
1
            case COMPILE_FBLOCK_FINALLY_TRY:
826
20
            case COMPILE_FBLOCK_FINALLY_END:
827
100
            case COMPILE_FBLOCK_EXCEPTION_HANDLER:
828
156
            case COMPILE_FBLOCK_EXCEPTION_GROUP_HANDLER:
829
156
            case COMPILE_FBLOCK_HANDLER_CLEANUP:
830
156
                return true;
831
1.60k
            default:
832
1.60k
                break;
833
1.75k
        }
834
1.75k
    }
835
10.3k
    return false;
836
10.5k
}
837
838
void
839
_PyCompile_DeferredAnnotations(compiler *c,
840
                               PyObject **deferred_annotations,
841
                               PyObject **conditional_annotation_indices)
842
19.3k
{
843
19.3k
    *deferred_annotations = Py_XNewRef(c->u->u_deferred_annotations);
844
19.3k
    *conditional_annotation_indices = Py_XNewRef(c->u->u_conditional_annotation_indices);
845
19.3k
}
846
847
static location
848
start_location(asdl_stmt_seq *stmts)
849
9.05k
{
850
9.05k
    if (asdl_seq_LEN(stmts) > 0) {
851
        /* Set current line number to the line number of first statement.
852
         * This way line number for SETUP_ANNOTATIONS will always
853
         * coincide with the line number of first "real" statement in module.
854
         * If body is empty, then lineno will be set later in the assembly stage.
855
         */
856
8.96k
        stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
857
8.96k
        return SRC_LOCATION_FROM_AST(st);
858
8.96k
    }
859
91
    return (const _Py_SourceLocation){1, 1, 0, 0};
860
9.05k
}
861
862
static int
863
compiler_codegen(compiler *c, mod_ty mod)
864
10.5k
{
865
10.5k
    RETURN_IF_ERROR(_PyCodegen_EnterAnonymousScope(c, mod));
866
10.5k
    assert(c->u->u_scope_type == COMPILE_SCOPE_MODULE);
867
10.5k
    switch (mod->kind) {
868
7.25k
    case Module_kind: {
869
7.25k
        asdl_stmt_seq *stmts = mod->v.Module.body;
870
7.25k
        RETURN_IF_ERROR(_PyCodegen_Module(c, start_location(stmts), stmts, false));
871
6.91k
        break;
872
7.25k
    }
873
6.91k
    case Interactive_kind: {
874
1.80k
        c->c_interactive = 1;
875
1.80k
        asdl_stmt_seq *stmts = mod->v.Interactive.body;
876
1.80k
        RETURN_IF_ERROR(_PyCodegen_Module(c, start_location(stmts), stmts, true));
877
1.68k
        break;
878
1.80k
    }
879
1.68k
    case Expression_kind: {
880
1.51k
        RETURN_IF_ERROR(_PyCodegen_Expression(c, mod->v.Expression.body));
881
1.47k
        break;
882
1.51k
    }
883
1.47k
    default: {
884
0
        PyErr_Format(PyExc_SystemError,
885
0
                     "module kind %d should not be possible",
886
0
                     mod->kind);
887
0
        return ERROR;
888
1.51k
    }}
889
10.0k
    return SUCCESS;
890
10.5k
}
891
892
static PyCodeObject *
893
compiler_mod(compiler *c, mod_ty mod)
894
10.5k
{
895
10.5k
    PyCodeObject *co = NULL;
896
10.5k
    int addNone = mod->kind != Expression_kind;
897
10.5k
    assert(c->u == NULL);
898
10.5k
    if (compiler_codegen(c, mod) < 0) {
899
502
        goto finally;
900
502
    }
901
10.0k
    co = _PyCompile_OptimizeAndAssemble(c, addNone);
902
10.5k
finally:
903
10.5k
    if (c->u != NULL) {
904
10.5k
        _PyCompile_ExitScope(c);
905
10.5k
    }
906
10.5k
    return co;
907
10.0k
}
908
909
int
910
_PyCompile_GetRefType(compiler *c, PyObject *name)
911
12.3k
{
912
12.3k
    if (c->u->u_scope_type == COMPILE_SCOPE_CLASS &&
913
6.95k
        (_PyUnicode_EqualToASCIIString(name, "__class__") ||
914
6.92k
         _PyUnicode_EqualToASCIIString(name, "__classdict__") ||
915
6.95k
         _PyUnicode_EqualToASCIIString(name, "__conditional_annotations__"))) {
916
6.95k
        return CELL;
917
6.95k
    }
918
5.42k
    PySTEntryObject *ste = c->u->u_ste;
919
5.42k
    int scope = _PyST_GetScope(ste, name);
920
5.42k
    if (scope == 0) {
921
0
        PyErr_Format(PyExc_SystemError,
922
0
                     "_PyST_GetScope(name=%R) failed: "
923
0
                     "unknown scope in unit %S (%R); "
924
0
                     "symbols: %R; locals: %R; "
925
0
                     "globals: %R",
926
0
                     name,
927
0
                     c->u->u_metadata.u_name, ste->ste_id,
928
0
                     ste->ste_symbols, c->u->u_metadata.u_varnames,
929
0
                     c->u->u_metadata.u_names);
930
0
        return ERROR;
931
0
    }
932
5.42k
    return scope;
933
5.42k
}
934
935
static int
936
dict_lookup_arg(PyObject *dict, PyObject *name)
937
18.4k
{
938
18.4k
    PyObject *v = PyDict_GetItemWithError(dict, name);
939
18.4k
    if (v == NULL) {
940
0
        return ERROR;
941
0
    }
942
18.4k
    return PyLong_AsLong(v);
943
18.4k
}
944
945
int
946
_PyCompile_LookupCellvar(compiler *c, PyObject *name)
947
6.07k
{
948
6.07k
    assert(c->u->u_metadata.u_cellvars);
949
6.07k
    return dict_lookup_arg(c->u->u_metadata.u_cellvars, name);
950
6.07k
}
951
952
int
953
_PyCompile_LookupArg(compiler *c, PyCodeObject *co, PyObject *name)
954
12.3k
{
955
    /* Special case: If a class contains a method with a
956
     * free variable that has the same name as a method,
957
     * the name will be considered free *and* local in the
958
     * class.  It should be handled by the closure, as
959
     * well as by the normal name lookup logic.
960
     */
961
12.3k
    int reftype = _PyCompile_GetRefType(c, name);
962
12.3k
    if (reftype == -1) {
963
0
        return ERROR;
964
0
    }
965
12.3k
    int arg;
966
12.3k
    if (reftype == CELL) {
967
9.73k
        arg = dict_lookup_arg(c->u->u_metadata.u_cellvars, name);
968
9.73k
    }
969
2.63k
    else {
970
2.63k
        arg = dict_lookup_arg(c->u->u_metadata.u_freevars, name);
971
2.63k
    }
972
12.3k
    if (arg == -1 && !PyErr_Occurred()) {
973
0
        PyObject *freevars = _PyCode_GetFreevars(co);
974
0
        if (freevars == NULL) {
975
0
            PyErr_Clear();
976
0
        }
977
0
        PyErr_Format(PyExc_SystemError,
978
0
            "compiler_lookup_arg(name=%R) with reftype=%d failed in %S; "
979
0
            "freevars of code %S: %R",
980
0
            name,
981
0
            reftype,
982
0
            c->u->u_metadata.u_name,
983
0
            co->co_name,
984
0
            freevars);
985
0
        Py_XDECREF(freevars);
986
0
        return ERROR;
987
0
    }
988
12.3k
    return arg;
989
12.3k
}
990
991
PyObject *
992
_PyCompile_StaticAttributesAsTuple(compiler *c)
993
13.0k
{
994
13.0k
    assert(c->u->u_static_attributes);
995
13.0k
    PyObject *static_attributes_unsorted = PySequence_List(c->u->u_static_attributes);
996
13.0k
    if (static_attributes_unsorted == NULL) {
997
0
        return NULL;
998
0
    }
999
13.0k
    if (PyList_Sort(static_attributes_unsorted) != 0) {
1000
0
        Py_DECREF(static_attributes_unsorted);
1001
0
        return NULL;
1002
0
    }
1003
13.0k
    PyObject *static_attributes = PySequence_Tuple(static_attributes_unsorted);
1004
13.0k
    Py_DECREF(static_attributes_unsorted);
1005
13.0k
    return static_attributes;
1006
13.0k
}
1007
1008
int
1009
_PyCompile_ResolveNameop(compiler *c, PyObject *mangled, int scope,
1010
                          _PyCompile_optype *optype, Py_ssize_t *arg)
1011
526k
{
1012
526k
    PyObject *dict = c->u->u_metadata.u_names;
1013
526k
    *optype = COMPILE_OP_NAME;
1014
1015
526k
    assert(scope >= 0);
1016
526k
    switch (scope) {
1017
3.63k
    case FREE:
1018
3.63k
        dict = c->u->u_metadata.u_freevars;
1019
3.63k
        *optype = COMPILE_OP_DEREF;
1020
3.63k
        break;
1021
5.67k
    case CELL:
1022
5.67k
        dict = c->u->u_metadata.u_cellvars;
1023
5.67k
        *optype = COMPILE_OP_DEREF;
1024
5.67k
        break;
1025
195k
    case LOCAL:
1026
195k
        if (_PyST_IsFunctionLike(c->u->u_ste)) {
1027
115k
            *optype = COMPILE_OP_FAST;
1028
115k
        }
1029
79.8k
        else {
1030
79.8k
            PyObject *item;
1031
79.8k
            RETURN_IF_ERROR(PyDict_GetItemRef(c->u->u_metadata.u_fasthidden, mangled,
1032
79.8k
                                              &item));
1033
79.8k
            if (item == Py_True) {
1034
16.0k
                *optype = COMPILE_OP_FAST;
1035
16.0k
            }
1036
79.8k
            Py_XDECREF(item);
1037
79.8k
        }
1038
195k
        break;
1039
241k
    case GLOBAL_IMPLICIT:
1040
241k
        if (_PyST_IsFunctionLike(c->u->u_ste)) {
1041
92.6k
            *optype = COMPILE_OP_GLOBAL;
1042
92.6k
        }
1043
241k
        break;
1044
903
    case GLOBAL_EXPLICIT:
1045
903
        *optype = COMPILE_OP_GLOBAL;
1046
903
        break;
1047
79.1k
    default:
1048
        /* scope can be 0 */
1049
79.1k
        break;
1050
526k
    }
1051
526k
    if (*optype != COMPILE_OP_FAST) {
1052
394k
        *arg = _PyCompile_DictAddObj(dict, mangled);
1053
394k
        RETURN_IF_ERROR(*arg);
1054
394k
    }
1055
526k
    return SUCCESS;
1056
526k
}
1057
1058
int
1059
_PyCompile_TweakInlinedComprehensionScopes(compiler *c, location loc,
1060
                                            PySTEntryObject *entry,
1061
                                            _PyCompile_InlinedComprehensionState *state)
1062
2.34k
{
1063
2.34k
    int in_class_block = (c->u->u_ste->ste_type == ClassBlock) && !c->u->u_in_inlined_comp;
1064
2.34k
    c->u->u_in_inlined_comp++;
1065
1066
2.34k
    PyObject *k, *v;
1067
2.34k
    Py_ssize_t pos = 0;
1068
14.8k
    while (PyDict_Next(entry->ste_symbols, &pos, &k, &v)) {
1069
12.4k
        long symbol = PyLong_AsLong(v);
1070
12.4k
        assert(symbol >= 0 || PyErr_Occurred());
1071
12.4k
        RETURN_IF_ERROR(symbol);
1072
12.4k
        long scope = SYMBOL_TO_SCOPE(symbol);
1073
1074
12.4k
        long outsymbol = _PyST_GetSymbol(c->u->u_ste, k);
1075
12.4k
        RETURN_IF_ERROR(outsymbol);
1076
12.4k
        long outsc = SYMBOL_TO_SCOPE(outsymbol);
1077
1078
        // If a name has different scope inside than outside the comprehension,
1079
        // we need to temporarily handle it with the right scope while
1080
        // compiling the comprehension. If it's free in the comprehension
1081
        // scope, no special handling; it should be handled the same as the
1082
        // enclosing scope. (If it's free in outer scope and cell in inner
1083
        // scope, we can't treat it as both cell and free in the same function,
1084
        // but treating it as free throughout is fine; it's *_DEREF
1085
        // either way.)
1086
12.4k
        if ((scope != outsc && scope != FREE && !(scope == CELL && outsc == FREE))
1087
9.98k
                || in_class_block) {
1088
2.54k
            if (state->temp_symbols == NULL) {
1089
2.29k
                state->temp_symbols = PyDict_New();
1090
2.29k
                if (state->temp_symbols == NULL) {
1091
0
                    return ERROR;
1092
0
                }
1093
2.29k
            }
1094
            // update the symbol to the in-comprehension version and save
1095
            // the outer version; we'll restore it after running the
1096
            // comprehension
1097
2.54k
            if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v) < 0) {
1098
0
                return ERROR;
1099
0
            }
1100
2.54k
            PyObject *outv = PyLong_FromLong(outsymbol);
1101
2.54k
            if (outv == NULL) {
1102
0
                return ERROR;
1103
0
            }
1104
2.54k
            int res = PyDict_SetItem(state->temp_symbols, k, outv);
1105
2.54k
            Py_DECREF(outv);
1106
2.54k
            RETURN_IF_ERROR(res);
1107
2.54k
        }
1108
        // locals handling for names bound in comprehension (DEF_LOCAL |
1109
        // DEF_NONLOCAL occurs in assignment expression to nonlocal)
1110
12.4k
        if ((symbol & DEF_LOCAL && !(symbol & DEF_NONLOCAL)) || in_class_block) {
1111
6.64k
            if (!_PyST_IsFunctionLike(c->u->u_ste)) {
1112
                // non-function scope: override this name to use fast locals
1113
4.91k
                PyObject *orig;
1114
4.91k
                if (PyDict_GetItemRef(c->u->u_metadata.u_fasthidden, k, &orig) < 0) {
1115
0
                    return ERROR;
1116
0
                }
1117
4.91k
                assert(orig == NULL || orig == Py_True || orig == Py_False);
1118
4.91k
                if (orig != Py_True) {
1119
4.86k
                    if (PyDict_SetItem(c->u->u_metadata.u_fasthidden, k, Py_True) < 0) {
1120
0
                        Py_XDECREF(orig);
1121
0
                        return ERROR;
1122
0
                    }
1123
4.86k
                    if (state->fast_hidden == NULL) {
1124
681
                        state->fast_hidden = PySet_New(NULL);
1125
681
                        if (state->fast_hidden == NULL) {
1126
0
                            Py_XDECREF(orig);
1127
0
                            return ERROR;
1128
0
                        }
1129
681
                    }
1130
4.86k
                    if (PySet_Add(state->fast_hidden, k) < 0) {
1131
0
                        Py_XDECREF(orig);
1132
0
                        return ERROR;
1133
0
                    }
1134
4.86k
                }
1135
4.91k
                Py_XDECREF(orig);
1136
4.91k
            }
1137
6.64k
        }
1138
12.4k
    }
1139
2.34k
    return SUCCESS;
1140
2.34k
}
1141
1142
int
1143
_PyCompile_RevertInlinedComprehensionScopes(compiler *c, location loc,
1144
                                             _PyCompile_InlinedComprehensionState *state)
1145
2.33k
{
1146
2.33k
    c->u->u_in_inlined_comp--;
1147
2.33k
    if (state->temp_symbols) {
1148
2.28k
        PyObject *k, *v;
1149
2.28k
        Py_ssize_t pos = 0;
1150
4.82k
        while (PyDict_Next(state->temp_symbols, &pos, &k, &v)) {
1151
2.53k
            if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v)) {
1152
0
                return ERROR;
1153
0
            }
1154
2.53k
        }
1155
2.28k
        Py_CLEAR(state->temp_symbols);
1156
2.28k
    }
1157
2.33k
    if (state->fast_hidden) {
1158
5.49k
        while (PySet_Size(state->fast_hidden) > 0) {
1159
4.82k
            PyObject *k = PySet_Pop(state->fast_hidden);
1160
4.82k
            if (k == NULL) {
1161
0
                return ERROR;
1162
0
            }
1163
            // we set to False instead of clearing, so we can track which names
1164
            // were temporarily fast-locals and should use CO_FAST_HIDDEN
1165
4.82k
            if (PyDict_SetItem(c->u->u_metadata.u_fasthidden, k, Py_False)) {
1166
0
                Py_DECREF(k);
1167
0
                return ERROR;
1168
0
            }
1169
4.82k
            Py_DECREF(k);
1170
4.82k
        }
1171
669
        Py_CLEAR(state->fast_hidden);
1172
669
    }
1173
2.33k
    return SUCCESS;
1174
2.33k
}
1175
1176
void
1177
_PyCompile_EnterConditionalBlock(struct _PyCompiler *c)
1178
11.0k
{
1179
11.0k
    c->u->u_in_conditional_block++;
1180
11.0k
}
1181
1182
void
1183
_PyCompile_LeaveConditionalBlock(struct _PyCompiler *c)
1184
11.0k
{
1185
11.0k
    assert(c->u->u_in_conditional_block > 0);
1186
11.0k
    c->u->u_in_conditional_block--;
1187
11.0k
}
1188
1189
int
1190
_PyCompile_AddDeferredAnnotation(compiler *c, stmt_ty s,
1191
                                 PyObject **conditional_annotation_index)
1192
16.5k
{
1193
16.5k
    if (c->u->u_deferred_annotations == NULL) {
1194
6.52k
        c->u->u_deferred_annotations = PyList_New(0);
1195
6.52k
        if (c->u->u_deferred_annotations == NULL) {
1196
0
            return ERROR;
1197
0
        }
1198
6.52k
    }
1199
16.5k
    if (c->u->u_conditional_annotation_indices == NULL) {
1200
6.52k
        c->u->u_conditional_annotation_indices = PyList_New(0);
1201
6.52k
        if (c->u->u_conditional_annotation_indices == NULL) {
1202
0
            return ERROR;
1203
0
        }
1204
6.52k
    }
1205
16.5k
    PyObject *ptr = PyLong_FromVoidPtr((void *)s);
1206
16.5k
    if (ptr == NULL) {
1207
0
        return ERROR;
1208
0
    }
1209
16.5k
    if (PyList_Append(c->u->u_deferred_annotations, ptr) < 0) {
1210
0
        Py_DECREF(ptr);
1211
0
        return ERROR;
1212
0
    }
1213
16.5k
    Py_DECREF(ptr);
1214
16.5k
    PyObject *index;
1215
16.5k
    if (c->u->u_scope_type == COMPILE_SCOPE_MODULE || c->u->u_in_conditional_block) {
1216
4.49k
        index = PyLong_FromLong(c->u->u_next_conditional_annotation_index);
1217
4.49k
        if (index == NULL) {
1218
0
            return ERROR;
1219
0
        }
1220
4.49k
        *conditional_annotation_index = Py_NewRef(index);
1221
4.49k
        c->u->u_next_conditional_annotation_index++;
1222
4.49k
    }
1223
12.0k
    else {
1224
12.0k
        index = PyLong_FromLong(-1);
1225
12.0k
        if (index == NULL) {
1226
0
            return ERROR;
1227
0
        }
1228
12.0k
    }
1229
16.5k
    int rc = PyList_Append(c->u->u_conditional_annotation_indices, index);
1230
16.5k
    Py_DECREF(index);
1231
16.5k
    RETURN_IF_ERROR(rc);
1232
16.5k
    return SUCCESS;
1233
16.5k
}
1234
1235
/* Raises a SyntaxError and returns ERROR.
1236
 * If something goes wrong, a different exception may be raised.
1237
 */
1238
int
1239
_PyCompile_Error(compiler *c, location loc, const char *format, ...)
1240
502
{
1241
502
    va_list vargs;
1242
502
    va_start(vargs, format);
1243
502
    PyObject *msg = PyUnicode_FromFormatV(format, vargs);
1244
502
    va_end(vargs);
1245
502
    if (msg == NULL) {
1246
0
        return ERROR;
1247
0
    }
1248
502
    _PyErr_RaiseSyntaxError(msg, c->c_filename, loc.lineno, loc.col_offset + 1,
1249
502
                            loc.end_lineno, loc.end_col_offset + 1);
1250
502
    Py_DECREF(msg);
1251
502
    return ERROR;
1252
502
}
1253
1254
/* Emits a SyntaxWarning and returns 0 on success.
1255
   If a SyntaxWarning raised as error, replaces it with a SyntaxError
1256
   and returns -1.
1257
*/
1258
int
1259
_PyCompile_Warn(compiler *c, location loc, const char *format, ...)
1260
6.15k
{
1261
6.15k
    if (c->c_disable_warning) {
1262
415
        return 0;
1263
415
    }
1264
5.74k
    va_list vargs;
1265
5.74k
    va_start(vargs, format);
1266
5.74k
    PyObject *msg = PyUnicode_FromFormatV(format, vargs);
1267
5.74k
    va_end(vargs);
1268
5.74k
    if (msg == NULL) {
1269
0
        return ERROR;
1270
0
    }
1271
5.74k
    int ret = _PyErr_EmitSyntaxWarning(msg, c->c_filename, loc.lineno, loc.col_offset + 1,
1272
5.74k
                                       loc.end_lineno, loc.end_col_offset + 1,
1273
5.74k
                                       c->c_module);
1274
5.74k
    Py_DECREF(msg);
1275
5.74k
    return ret;
1276
5.74k
}
1277
1278
PyObject *
1279
_PyCompile_Mangle(compiler *c, PyObject *name)
1280
16.4k
{
1281
16.4k
    return _Py_Mangle(c->u->u_private, name);
1282
16.4k
}
1283
1284
PyObject *
1285
_PyCompile_MaybeMangle(compiler *c, PyObject *name)
1286
600k
{
1287
600k
    return _Py_MaybeMangle(c->u->u_private, c->u->u_ste, name);
1288
600k
}
1289
1290
instr_sequence *
1291
_PyCompile_InstrSequence(compiler *c)
1292
5.72M
{
1293
5.72M
    return c->u->u_instr_sequence;
1294
5.72M
}
1295
1296
int
1297
_PyCompile_StartAnnotationSetup(struct _PyCompiler *c)
1298
608
{
1299
608
    instr_sequence *new_seq = (instr_sequence *)_PyInstructionSequence_New();
1300
608
    if (new_seq == NULL) {
1301
0
        return ERROR;
1302
0
    }
1303
608
    assert(c->u->u_stashed_instr_sequence == NULL);
1304
608
    c->u->u_stashed_instr_sequence = c->u->u_instr_sequence;
1305
608
    c->u->u_instr_sequence = new_seq;
1306
608
    return SUCCESS;
1307
608
}
1308
1309
int
1310
_PyCompile_EndAnnotationSetup(struct _PyCompiler *c)
1311
599
{
1312
599
    assert(c->u->u_stashed_instr_sequence != NULL);
1313
599
    instr_sequence *parent_seq = c->u->u_stashed_instr_sequence;
1314
599
    instr_sequence *anno_seq = c->u->u_instr_sequence;
1315
599
    c->u->u_stashed_instr_sequence = NULL;
1316
599
    c->u->u_instr_sequence = parent_seq;
1317
599
    if (_PyInstructionSequence_SetAnnotationsCode(parent_seq, anno_seq) == ERROR) {
1318
0
        Py_DECREF(anno_seq);
1319
0
        return ERROR;
1320
0
    }
1321
599
    return SUCCESS;
1322
599
}
1323
1324
1325
int
1326
_PyCompile_FutureFeatures(compiler *c)
1327
72.4k
{
1328
72.4k
    return c->c_future.ff_features;
1329
72.4k
}
1330
1331
struct symtable *
1332
_PyCompile_Symtable(compiler *c)
1333
11.0k
{
1334
11.0k
    return c->c_st;
1335
11.0k
}
1336
1337
PySTEntryObject *
1338
_PyCompile_SymtableEntry(compiler *c)
1339
979k
{
1340
979k
    return c->u->u_ste;
1341
979k
}
1342
1343
int
1344
_PyCompile_OptimizationLevel(compiler *c)
1345
3.49k
{
1346
3.49k
    return c->c_optimize;
1347
3.49k
}
1348
1349
int
1350
_PyCompile_IsInteractiveTopLevel(compiler *c)
1351
89.8k
{
1352
89.8k
    assert(c->c_stack != NULL);
1353
89.8k
    assert(PyList_CheckExact(c->c_stack));
1354
89.8k
    bool is_nested_scope = PyList_GET_SIZE(c->c_stack) > 0;
1355
89.8k
    return c->c_interactive && !is_nested_scope;
1356
89.8k
}
1357
1358
int
1359
_PyCompile_ScopeType(compiler *c)
1360
63.3k
{
1361
63.3k
    return c->u->u_scope_type;
1362
63.3k
}
1363
1364
int
1365
_PyCompile_IsInInlinedComp(compiler *c)
1366
52.6k
{
1367
52.6k
    return c->u->u_in_inlined_comp;
1368
52.6k
}
1369
1370
PyObject *
1371
_PyCompile_Qualname(compiler *c)
1372
13.0k
{
1373
13.0k
    assert(c->u->u_metadata.u_qualname);
1374
13.0k
    return c->u->u_metadata.u_qualname;
1375
13.0k
}
1376
1377
_PyCompile_CodeUnitMetadata *
1378
_PyCompile_Metadata(compiler *c)
1379
234k
{
1380
234k
    return &c->u->u_metadata;
1381
234k
}
1382
1383
// Merge *obj* with constant cache, without recursion.
1384
int
1385
_PyCompile_ConstCacheMergeOne(PyObject *const_cache, PyObject **obj)
1386
973k
{
1387
973k
    PyObject *key = const_cache_insert(const_cache, *obj, false);
1388
973k
    if (key == NULL) {
1389
0
        return ERROR;
1390
0
    }
1391
973k
    if (PyTuple_CheckExact(key)) {
1392
728k
        PyObject *item = PyTuple_GET_ITEM(key, 1);
1393
728k
        Py_SETREF(*obj, Py_NewRef(item));
1394
728k
        Py_DECREF(key);
1395
728k
    }
1396
245k
    else {
1397
245k
        Py_SETREF(*obj, key);
1398
245k
    }
1399
973k
    return SUCCESS;
1400
973k
}
1401
1402
static PyObject *
1403
consts_dict_keys_inorder(PyObject *dict)
1404
52.7k
{
1405
52.7k
    PyObject *consts, *k, *v;
1406
52.7k
    Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
1407
1408
52.7k
    consts = PyList_New(size);   /* PyCode_Optimize() requires a list */
1409
52.7k
    if (consts == NULL)
1410
0
        return NULL;
1411
330k
    while (PyDict_Next(dict, &pos, &k, &v)) {
1412
277k
        assert(PyLong_CheckExact(v));
1413
277k
        i = PyLong_AsLong(v);
1414
        /* The keys of the dictionary can be tuples wrapping a constant.
1415
         * (see _PyCompile_DictAddObj and _PyCode_ConstantKey). In that case
1416
         * the object we want is always second. */
1417
277k
        if (PyTuple_CheckExact(k)) {
1418
34.9k
            k = PyTuple_GET_ITEM(k, 1);
1419
34.9k
        }
1420
277k
        assert(i < size);
1421
277k
        assert(i >= 0);
1422
277k
        PyList_SET_ITEM(consts, i, Py_NewRef(k));
1423
277k
    }
1424
52.7k
    return consts;
1425
52.7k
}
1426
1427
static int
1428
compute_code_flags(compiler *c)
1429
52.7k
{
1430
52.7k
    PySTEntryObject *ste = c->u->u_ste;
1431
52.7k
    int flags = 0;
1432
52.7k
    if (_PyST_IsFunctionLike(ste)) {
1433
29.6k
        flags |= CO_NEWLOCALS | CO_OPTIMIZED;
1434
29.6k
        if (ste->ste_nested)
1435
10.9k
            flags |= CO_NESTED;
1436
29.6k
        if (ste->ste_generator && !ste->ste_coroutine)
1437
369
            flags |= CO_GENERATOR;
1438
29.6k
        if (ste->ste_generator && ste->ste_coroutine)
1439
59
            flags |= CO_ASYNC_GENERATOR;
1440
29.6k
        if (ste->ste_varargs)
1441
2.65k
            flags |= CO_VARARGS;
1442
29.6k
        if (ste->ste_varkeywords)
1443
815
            flags |= CO_VARKEYWORDS;
1444
29.6k
        if (ste->ste_has_docstring)
1445
628
            flags |= CO_HAS_DOCSTRING;
1446
29.6k
        if (ste->ste_method)
1447
16
            flags |= CO_METHOD;
1448
29.6k
    }
1449
1450
52.7k
    if (ste->ste_coroutine && !ste->ste_generator) {
1451
2.53k
        flags |= CO_COROUTINE;
1452
2.53k
    }
1453
1454
    /* (Only) inherit compilerflags in PyCF_MASK */
1455
52.7k
    flags |= (c->c_flags.cf_flags & PyCF_MASK);
1456
1457
52.7k
    return flags;
1458
52.7k
}
1459
1460
static PyCodeObject *
1461
optimize_and_assemble_code_unit(struct compiler_unit *u, PyObject *const_cache,
1462
                                int code_flags, PyObject *filename)
1463
52.7k
{
1464
52.7k
    cfg_builder *g = NULL;
1465
52.7k
    instr_sequence optimized_instrs;
1466
52.7k
    memset(&optimized_instrs, 0, sizeof(instr_sequence));
1467
1468
52.7k
    PyCodeObject *co = NULL;
1469
52.7k
    PyObject *consts = consts_dict_keys_inorder(u->u_metadata.u_consts);
1470
52.7k
    if (consts == NULL) {
1471
0
        goto error;
1472
0
    }
1473
52.7k
    g = _PyCfg_FromInstructionSequence(u->u_instr_sequence);
1474
52.7k
    if (g == NULL) {
1475
0
        goto error;
1476
0
    }
1477
52.7k
    int nlocals = (int)PyDict_GET_SIZE(u->u_metadata.u_varnames);
1478
52.7k
    int nparams = (int)PyList_GET_SIZE(u->u_ste->ste_varnames);
1479
52.7k
    assert(u->u_metadata.u_firstlineno);
1480
1481
52.7k
    if (_PyCfg_OptimizeCodeUnit(g, consts, const_cache, nlocals,
1482
52.7k
                                nparams, u->u_metadata.u_firstlineno) < 0) {
1483
0
        goto error;
1484
0
    }
1485
1486
52.7k
    int stackdepth;
1487
52.7k
    int nlocalsplus;
1488
52.7k
    if (_PyCfg_OptimizedCfgToInstructionSequence(g, &u->u_metadata,
1489
52.7k
                                                 &stackdepth, &nlocalsplus,
1490
52.7k
                                                 &optimized_instrs) < 0) {
1491
0
        goto error;
1492
0
    }
1493
1494
    /** Assembly **/
1495
52.7k
    co = _PyAssemble_MakeCodeObject(&u->u_metadata, const_cache, consts,
1496
52.7k
                                    stackdepth, &optimized_instrs, nlocalsplus,
1497
52.7k
                                    code_flags, filename);
1498
1499
52.7k
error:
1500
52.7k
    Py_XDECREF(consts);
1501
52.7k
    PyInstructionSequence_Fini(&optimized_instrs);
1502
52.7k
    _PyCfgBuilder_Free(g);
1503
52.7k
    return co;
1504
52.7k
}
1505
1506
1507
PyCodeObject *
1508
_PyCompile_OptimizeAndAssemble(compiler *c, int addNone)
1509
52.7k
{
1510
52.7k
    struct compiler_unit *u = c->u;
1511
52.7k
    PyObject *const_cache = c->c_const_cache;
1512
52.7k
    PyObject *filename = c->c_filename;
1513
1514
52.7k
    int code_flags = compute_code_flags(c);
1515
52.7k
    if (code_flags < 0) {
1516
0
        return NULL;
1517
0
    }
1518
1519
52.7k
    if (_PyCodegen_AddReturnAtEnd(c, addNone) < 0) {
1520
0
        return NULL;
1521
0
    }
1522
1523
52.7k
    return optimize_and_assemble_code_unit(u, const_cache, code_flags, filename);
1524
52.7k
}
1525
1526
PyCodeObject *
1527
_PyAST_Compile(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
1528
               int optimize, PyArena *arena, PyObject *module)
1529
10.8k
{
1530
10.8k
    assert(!PyErr_Occurred());
1531
10.8k
    compiler *c = new_compiler(mod, filename, pflags, optimize, arena, module);
1532
10.8k
    if (c == NULL) {
1533
268
        return NULL;
1534
268
    }
1535
1536
10.5k
    PyCodeObject *co = compiler_mod(c, mod);
1537
10.5k
    compiler_free(c);
1538
10.5k
    assert(co || PyErr_Occurred());
1539
10.5k
    return co;
1540
10.5k
}
1541
1542
int
1543
_PyCompile_AstPreprocess(mod_ty mod, PyObject *filename, PyCompilerFlags *cf,
1544
                         int optimize, PyArena *arena, int no_const_folding,
1545
                         PyObject *module)
1546
1.89k
{
1547
1.89k
    _PyFutureFeatures future;
1548
1.89k
    if (!_PyFuture_FromAST(mod, filename, &future)) {
1549
1
        return -1;
1550
1
    }
1551
1.89k
    int flags = future.ff_features | cf->cf_flags;
1552
1.89k
    if (optimize == -1) {
1553
555
        optimize = _Py_GetConfig()->optimization_level;
1554
555
    }
1555
1.89k
    if (!_PyAST_Preprocess(mod, arena, filename, optimize, flags,
1556
1.89k
                           no_const_folding, 0, module))
1557
0
    {
1558
0
        return -1;
1559
0
    }
1560
1.89k
    return 0;
1561
1.89k
}
1562
1563
// C implementation of inspect.cleandoc()
1564
//
1565
// Difference from inspect.cleandoc():
1566
// - Do not remove leading and trailing blank lines to keep lineno.
1567
PyObject *
1568
_PyCompile_CleanDoc(PyObject *doc)
1569
1.94k
{
1570
1.94k
    doc = PyObject_CallMethod(doc, "expandtabs", NULL);
1571
1.94k
    if (doc == NULL) {
1572
0
        return NULL;
1573
0
    }
1574
1575
1.94k
    Py_ssize_t doc_size;
1576
1.94k
    const char *doc_utf8 = PyUnicode_AsUTF8AndSize(doc, &doc_size);
1577
1.94k
    if (doc_utf8 == NULL) {
1578
0
        Py_DECREF(doc);
1579
0
        return NULL;
1580
0
    }
1581
1.94k
    const char *p = doc_utf8;
1582
1.94k
    const char *pend = p + doc_size;
1583
1584
    // First pass: find minimum indentation of any non-blank lines
1585
    // after first line.
1586
49.5k
    while (p < pend && *p++ != '\n') {
1587
47.6k
    }
1588
1589
1.94k
    Py_ssize_t margin = PY_SSIZE_T_MAX;
1590
30.3k
    while (p < pend) {
1591
28.3k
        const char *s = p;
1592
41.5k
        while (*p == ' ') p++;
1593
28.3k
        if (p < pend && *p != '\n') {
1594
3.79k
            margin = Py_MIN(margin, p - s);
1595
3.79k
        }
1596
173k
        while (p < pend && *p++ != '\n') {
1597
145k
        }
1598
28.3k
    }
1599
1.94k
    if (margin == PY_SSIZE_T_MAX) {
1600
1.30k
        margin = 0;
1601
1.30k
    }
1602
1603
    // Second pass: write cleandoc into buff.
1604
1605
    // copy first line without leading spaces.
1606
1.94k
    p = doc_utf8;
1607
4.99k
    while (*p == ' ') {
1608
3.04k
        p++;
1609
3.04k
    }
1610
1.94k
    if (p == doc_utf8 && margin == 0 ) {
1611
        // doc is already clean.
1612
763
        return doc;
1613
763
    }
1614
1615
1.18k
    char *buff = PyMem_Malloc(doc_size);
1616
1.18k
    if (buff == NULL){
1617
0
        Py_DECREF(doc);
1618
0
        PyErr_NoMemory();
1619
0
        return NULL;
1620
0
    }
1621
1622
1.18k
    char *w = buff;
1623
1624
17.3k
    while (p < pend) {
1625
16.5k
        int ch = *w++ = *p++;
1626
16.5k
        if (ch == '\n') {
1627
390
            break;
1628
390
        }
1629
16.5k
    }
1630
1631
    // copy subsequent lines without margin.
1632
29.0k
    while (p < pend) {
1633
29.1k
        for (Py_ssize_t i = 0; i < margin; i++, p++) {
1634
1.42k
            if (*p != ' ') {
1635
108
                assert(*p == '\n' || *p == '\0');
1636
108
                break;
1637
108
            }
1638
1.42k
        }
1639
155k
        while (p < pend) {
1640
155k
            int ch = *w++ = *p++;
1641
155k
            if (ch == '\n') {
1642
27.7k
                break;
1643
27.7k
            }
1644
155k
        }
1645
27.8k
    }
1646
1647
1.18k
    Py_DECREF(doc);
1648
1.18k
    PyObject *res = PyUnicode_FromStringAndSize(buff, w - buff);
1649
1.18k
    PyMem_Free(buff);
1650
1.18k
    return res;
1651
1.18k
}
1652
1653
/* Access to compiler optimizations for unit tests.
1654
 *
1655
 * _PyCompile_CodeGen takes an AST, applies code-gen and
1656
 * returns the unoptimized CFG as an instruction list.
1657
 *
1658
 */
1659
PyObject *
1660
_PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
1661
                   int optimize, int compile_mode)
1662
0
{
1663
0
    PyObject *res = NULL;
1664
0
    PyObject *metadata = NULL;
1665
0
    PyObject *consts_list = NULL;
1666
1667
0
    if (!PyAST_Check(ast)) {
1668
0
        PyErr_SetString(PyExc_TypeError, "expected an AST");
1669
0
        return NULL;
1670
0
    }
1671
1672
0
    PyArena *arena = _PyArena_New();
1673
0
    if (arena == NULL) {
1674
0
        return NULL;
1675
0
    }
1676
1677
0
    mod_ty mod = PyAST_obj2mod(ast, arena, compile_mode);
1678
0
    if (mod == NULL || !_PyAST_Validate(mod)) {
1679
0
        _PyArena_Free(arena);
1680
0
        return NULL;
1681
0
    }
1682
1683
0
    compiler *c = new_compiler(mod, filename, pflags, optimize, arena, NULL);
1684
0
    if (c == NULL) {
1685
0
        _PyArena_Free(arena);
1686
0
        return NULL;
1687
0
    }
1688
0
    c->c_save_nested_seqs = true;
1689
1690
0
    metadata = PyDict_New();
1691
0
    if (metadata == NULL) {
1692
0
        goto finally;
1693
0
    }
1694
1695
0
    if (compiler_codegen(c, mod) < 0) {
1696
0
        goto finally;
1697
0
    }
1698
1699
0
    _PyCompile_CodeUnitMetadata *umd = &c->u->u_metadata;
1700
1701
0
#define SET_METADATA_INT(key, value) do { \
1702
0
        PyObject *v = PyLong_FromLong((long)value); \
1703
0
        if (v == NULL) goto finally; \
1704
0
        int res = PyDict_SetItemString(metadata, key, v); \
1705
0
        Py_XDECREF(v); \
1706
0
        if (res < 0) goto finally; \
1707
0
    } while (0);
1708
1709
0
    SET_METADATA_INT("argcount", umd->u_argcount);
1710
0
    SET_METADATA_INT("posonlyargcount", umd->u_posonlyargcount);
1711
0
    SET_METADATA_INT("kwonlyargcount", umd->u_kwonlyargcount);
1712
0
#undef SET_METADATA_INT
1713
1714
0
    int addNone = mod->kind != Expression_kind;
1715
0
    if (_PyCodegen_AddReturnAtEnd(c, addNone) < 0) {
1716
0
        goto finally;
1717
0
    }
1718
1719
0
    if (_PyInstructionSequence_ApplyLabelMap(_PyCompile_InstrSequence(c)) < 0) {
1720
0
        goto finally;
1721
0
    }
1722
1723
    /* After AddReturnAtEnd: co_consts indices match the final instruction stream. */
1724
0
    consts_list = consts_dict_keys_inorder(umd->u_consts);
1725
0
    if (consts_list == NULL) {
1726
0
        goto finally;
1727
0
    }
1728
0
    if (PyDict_SetItemString(metadata, "consts", consts_list) < 0) {
1729
0
        goto finally;
1730
0
    }
1731
1732
    /* Allocate a copy of the instruction sequence on the heap */
1733
0
    res = _PyTuple_FromPair((PyObject *)_PyCompile_InstrSequence(c), metadata);
1734
1735
0
finally:
1736
0
    Py_XDECREF(consts_list);
1737
0
    Py_XDECREF(metadata);
1738
0
    _PyCompile_ExitScope(c);
1739
0
    compiler_free(c);
1740
0
    _PyArena_Free(arena);
1741
0
    return res;
1742
0
}
1743
1744
int _PyCfg_JumpLabelsToTargets(cfg_builder *g);
1745
1746
PyCodeObject *
1747
_PyCompile_Assemble(_PyCompile_CodeUnitMetadata *umd, PyObject *filename,
1748
                    PyObject *seq)
1749
0
{
1750
0
    if (!_PyInstructionSequence_Check(seq)) {
1751
0
        PyErr_SetString(PyExc_TypeError, "expected an instruction sequence");
1752
0
        return NULL;
1753
0
    }
1754
0
    cfg_builder *g = NULL;
1755
0
    PyCodeObject *co = NULL;
1756
0
    instr_sequence optimized_instrs;
1757
0
    memset(&optimized_instrs, 0, sizeof(instr_sequence));
1758
1759
0
    PyObject *const_cache = PyDict_New();
1760
0
    if (const_cache == NULL) {
1761
0
        return NULL;
1762
0
    }
1763
1764
0
    g = _PyCfg_FromInstructionSequence((instr_sequence*)seq);
1765
0
    if (g == NULL) {
1766
0
        goto error;
1767
0
    }
1768
1769
0
    if (_PyCfg_JumpLabelsToTargets(g) < 0) {
1770
0
        goto error;
1771
0
    }
1772
1773
0
    int code_flags = 0;
1774
0
    int stackdepth, nlocalsplus;
1775
0
    if (_PyCfg_OptimizedCfgToInstructionSequence(g, umd,
1776
0
                                                 &stackdepth, &nlocalsplus,
1777
0
                                                 &optimized_instrs) < 0) {
1778
0
        goto error;
1779
0
    }
1780
1781
0
    PyObject *consts = consts_dict_keys_inorder(umd->u_consts);
1782
0
    if (consts == NULL) {
1783
0
        goto error;
1784
0
    }
1785
0
    co = _PyAssemble_MakeCodeObject(umd, const_cache,
1786
0
                                    consts, stackdepth, &optimized_instrs,
1787
0
                                    nlocalsplus, code_flags, filename);
1788
0
    Py_DECREF(consts);
1789
1790
0
error:
1791
0
    Py_DECREF(const_cache);
1792
0
    _PyCfgBuilder_Free(g);
1793
0
    PyInstructionSequence_Fini(&optimized_instrs);
1794
0
    return co;
1795
0
}
1796
1797
/* Retained for API compatibility.
1798
 * Optimization is now done in _PyCfg_OptimizeCodeUnit */
1799
1800
PyObject *
1801
PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
1802
                PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
1803
0
{
1804
0
    return Py_NewRef(code);
1805
0
}