Coverage Report

Created: 2025-11-11 06:44

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