Coverage Report

Created: 2026-03-23 06:45

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