Coverage Report

Created: 2026-04-12 06:54

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
122k
#define SUCCESS 0
37
0
#define ERROR -1
38
39
#define RETURN_IF_ERROR(X)  \
40
40.3k
    do {                    \
41
40.3k
        if ((X) == -1) {    \
42
0
            return ERROR;   \
43
0
        }                   \
44
40.3k
    } 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
859
{
116
859
    PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
117
118
859
    c->c_const_cache = PyDict_New();
119
859
    if (!c->c_const_cache) {
120
0
        return ERROR;
121
0
    }
122
123
859
    c->c_stack = PyList_New(0);
124
859
    if (!c->c_stack) {
125
0
        return ERROR;
126
0
    }
127
128
859
    c->c_filename = Py_NewRef(filename);
129
859
    if (!_PyFuture_FromAST(mod, filename, &c->c_future)) {
130
0
        return ERROR;
131
0
    }
132
859
    c->c_module = Py_XNewRef(module);
133
859
    if (!flags) {
134
108
        flags = &local_flags;
135
108
    }
136
859
    int merged = c->c_future.ff_features | flags->cf_flags;
137
859
    c->c_future.ff_features = merged;
138
859
    flags->cf_flags = merged;
139
859
    c->c_flags = *flags;
140
859
    c->c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
141
859
    c->c_save_nested_seqs = false;
142
143
859
    if (!_PyAST_Preprocess(mod, arena, filename, c->c_optimize, merged,
144
859
                           0, 1, module))
145
0
    {
146
0
        return ERROR;
147
0
    }
148
859
    c->c_st = _PySymtable_Build(mod, filename, &c->c_future);
149
859
    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
859
    return SUCCESS;
156
859
}
157
158
static void
159
compiler_free(compiler *c)
160
859
{
161
859
    if (c->c_st) {
162
859
        _PySymtable_Free(c->c_st);
163
859
    }
164
859
    Py_XDECREF(c->c_filename);
165
859
    Py_XDECREF(c->c_module);
166
859
    Py_XDECREF(c->c_const_cache);
167
859
    Py_XDECREF(c->c_stack);
168
859
    PyMem_Free(c);
169
859
}
170
171
static compiler*
172
new_compiler(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
173
             int optimize, PyArena *arena, PyObject *module)
174
859
{
175
859
    compiler *c = PyMem_Calloc(1, sizeof(compiler));
176
859
    if (c == NULL) {
177
0
        return NULL;
178
0
    }
179
859
    if (compiler_setup(c, mod, filename, pflags, optimize, arena, module) < 0) {
180
0
        compiler_free(c);
181
0
        return NULL;
182
0
    }
183
859
    return c;
184
859
}
185
186
static void
187
compiler_unit_free(struct compiler_unit *u)
188
5.68k
{
189
5.68k
    Py_CLEAR(u->u_instr_sequence);
190
5.68k
    Py_CLEAR(u->u_stashed_instr_sequence);
191
5.68k
    Py_CLEAR(u->u_ste);
192
5.68k
    Py_CLEAR(u->u_metadata.u_name);
193
5.68k
    Py_CLEAR(u->u_metadata.u_qualname);
194
5.68k
    Py_CLEAR(u->u_metadata.u_consts);
195
5.68k
    Py_CLEAR(u->u_metadata.u_names);
196
5.68k
    Py_CLEAR(u->u_metadata.u_varnames);
197
5.68k
    Py_CLEAR(u->u_metadata.u_freevars);
198
5.68k
    Py_CLEAR(u->u_metadata.u_cellvars);
199
5.68k
    Py_CLEAR(u->u_metadata.u_fasthidden);
200
5.68k
    Py_CLEAR(u->u_private);
201
5.68k
    Py_CLEAR(u->u_static_attributes);
202
5.68k
    Py_CLEAR(u->u_deferred_annotations);
203
5.68k
    Py_CLEAR(u->u_conditional_annotation_indices);
204
5.68k
    PyMem_Free(u);
205
5.68k
}
206
207
14.0k
#define CAPSULE_NAME "compile.c compiler unit"
208
209
int
210
_PyCompile_MaybeAddStaticAttributeToClass(compiler *c, expr_ty e)
211
13.8k
{
212
13.8k
    assert(e->kind == Attribute_kind);
213
13.8k
    expr_ty attr_value = e->v.Attribute.value;
214
13.8k
    if (attr_value->kind != Name_kind ||
215
13.1k
        e->v.Attribute.ctx != Store ||
216
1.36k
        !_PyUnicode_EqualToASCIIString(attr_value->v.Name.id, "self"))
217
12.6k
    {
218
12.6k
        return SUCCESS;
219
12.6k
    }
220
1.17k
    Py_ssize_t stack_size = PyList_GET_SIZE(c->c_stack);
221
1.52k
    for (Py_ssize_t i = stack_size - 1; i >= 0; i--) {
222
1.35k
        PyObject *capsule = PyList_GET_ITEM(c->c_stack, i);
223
1.35k
        struct compiler_unit *u = (struct compiler_unit *)PyCapsule_GetPointer(
224
1.35k
                                                              capsule, CAPSULE_NAME);
225
1.35k
        assert(u);
226
1.35k
        if (u->u_scope_type == COMPILE_SCOPE_CLASS) {
227
1.00k
            assert(u->u_static_attributes);
228
1.00k
            RETURN_IF_ERROR(PySet_Add(u->u_static_attributes, e->v.Attribute.attr));
229
1.00k
            break;
230
1.00k
        }
231
1.35k
    }
232
1.17k
    return SUCCESS;
233
1.17k
}
234
235
static int
236
compiler_set_qualname(compiler *c)
237
4.82k
{
238
4.82k
    Py_ssize_t stack_size;
239
4.82k
    struct compiler_unit *u = c->u;
240
4.82k
    PyObject *name, *base;
241
242
4.82k
    base = NULL;
243
4.82k
    stack_size = PyList_GET_SIZE(c->c_stack);
244
4.82k
    assert(stack_size >= 1);
245
4.82k
    if (stack_size > 1) {
246
3.02k
        int scope, force_global = 0;
247
3.02k
        struct compiler_unit *parent;
248
3.02k
        PyObject *mangled, *capsule;
249
250
3.02k
        capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
251
3.02k
        parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
252
3.02k
        assert(parent);
253
3.02k
        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
3.02k
        if (u->u_scope_type == COMPILE_SCOPE_FUNCTION
268
251
            || u->u_scope_type == COMPILE_SCOPE_ASYNC_FUNCTION
269
2.90k
            || u->u_scope_type == COMPILE_SCOPE_CLASS) {
270
2.90k
            assert(u->u_metadata.u_name);
271
2.90k
            mangled = _Py_Mangle(parent->u_private, u->u_metadata.u_name);
272
2.90k
            if (!mangled) {
273
0
                return ERROR;
274
0
            }
275
276
2.90k
            scope = _PyST_GetScope(parent->u_ste, mangled);
277
2.90k
            Py_DECREF(mangled);
278
2.90k
            RETURN_IF_ERROR(scope);
279
2.90k
            assert(scope != GLOBAL_IMPLICIT);
280
2.90k
            if (scope == GLOBAL_EXPLICIT)
281
0
                force_global = 1;
282
2.90k
        }
283
284
3.02k
        if (!force_global) {
285
3.02k
            if (parent->u_scope_type == COMPILE_SCOPE_FUNCTION
286
1.87k
                || parent->u_scope_type == COMPILE_SCOPE_ASYNC_FUNCTION
287
1.85k
                || parent->u_scope_type == COMPILE_SCOPE_LAMBDA)
288
1.17k
            {
289
1.17k
                _Py_DECLARE_STR(dot_locals, ".<locals>");
290
1.17k
                base = PyUnicode_Concat(parent->u_metadata.u_qualname,
291
1.17k
                                        &_Py_STR(dot_locals));
292
1.17k
                if (base == NULL) {
293
0
                    return ERROR;
294
0
                }
295
1.17k
            }
296
1.85k
            else {
297
1.85k
                base = Py_NewRef(parent->u_metadata.u_qualname);
298
1.85k
            }
299
3.02k
        }
300
3.02k
    }
301
302
4.82k
    if (base != NULL) {
303
3.02k
        name = PyUnicode_Concat(base, _Py_LATIN1_CHR('.'));
304
3.02k
        Py_DECREF(base);
305
3.02k
        if (name == NULL) {
306
0
            return ERROR;
307
0
        }
308
3.02k
        PyUnicode_Append(&name, u->u_metadata.u_name);
309
3.02k
        if (name == NULL) {
310
0
            return ERROR;
311
0
        }
312
3.02k
    }
313
1.80k
    else {
314
1.80k
        name = Py_NewRef(u->u_metadata.u_name);
315
1.80k
    }
316
4.82k
    u->u_metadata.u_qualname = name;
317
318
4.82k
    return SUCCESS;
319
4.82k
}
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
84.8k
{
327
84.8k
    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
84.8k
    if (o == Py_None || o == Py_Ellipsis) {
331
10.0k
        return o;
332
10.0k
    }
333
334
74.8k
    PyObject *key = _PyCode_ConstantKey(o);
335
74.8k
    if (key == NULL) {
336
0
        return NULL;
337
0
    }
338
339
74.8k
    PyObject *t;
340
74.8k
    int res = PyDict_SetDefaultRef(const_cache, key, key, &t);
341
74.8k
    if (res != 0) {
342
        // o was not inserted into const_cache. t is either the existing value
343
        // or NULL (on error).
344
26.9k
        Py_DECREF(key);
345
26.9k
        return t;
346
26.9k
    }
347
47.9k
    Py_DECREF(t);
348
349
47.9k
    if (!recursive) {
350
25.3k
        return key;
351
25.3k
    }
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
22.6k
    if (PyTuple_CheckExact(o)) {
357
1.01k
        Py_ssize_t len = PyTuple_GET_SIZE(o);
358
3.44k
        for (Py_ssize_t i = 0; i < len; i++) {
359
2.43k
            PyObject *item = PyTuple_GET_ITEM(o, i);
360
2.43k
            PyObject *u = const_cache_insert(const_cache, item, recursive);
361
2.43k
            if (u == NULL) {
362
0
                Py_DECREF(key);
363
0
                return NULL;
364
0
            }
365
366
            // See _PyCode_ConstantKey()
367
2.43k
            PyObject *v;  // borrowed
368
2.43k
            if (PyTuple_CheckExact(u)) {
369
0
                v = PyTuple_GET_ITEM(u, 1);
370
0
            }
371
2.43k
            else {
372
2.43k
                v = u;
373
2.43k
            }
374
2.43k
            if (v != item) {
375
112
                PyTuple_SET_ITEM(o, i, Py_NewRef(v));
376
112
                Py_DECREF(item);
377
112
            }
378
379
2.43k
            Py_DECREF(u);
380
2.43k
        }
381
1.01k
    }
382
21.6k
    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
22.6k
    return key;
434
22.6k
}
435
436
static PyObject*
437
merge_consts_recursive(PyObject *const_cache, PyObject *o)
438
47.1k
{
439
47.1k
    return const_cache_insert(const_cache, o, true);
440
47.1k
}
441
442
Py_ssize_t
443
_PyCompile_DictAddObj(PyObject *dict, PyObject *o)
444
126k
{
445
126k
    PyObject *v;
446
126k
    Py_ssize_t arg;
447
448
126k
    if (PyDict_GetItemRef(dict, o, &v) < 0) {
449
0
        return ERROR;
450
0
    }
451
126k
    if (!v) {
452
66.4k
        arg = PyDict_GET_SIZE(dict);
453
66.4k
        v = PyLong_FromSsize_t(arg);
454
66.4k
        if (!v) {
455
0
            return ERROR;
456
0
        }
457
66.4k
        if (PyDict_SetItem(dict, o, v) < 0) {
458
0
            Py_DECREF(v);
459
0
            return ERROR;
460
0
        }
461
66.4k
    }
462
60.3k
    else
463
60.3k
        arg = PyLong_AsLong(v);
464
126k
    Py_DECREF(v);
465
126k
    return arg;
466
126k
}
467
468
Py_ssize_t
469
_PyCompile_AddConst(compiler *c, PyObject *o)
470
47.1k
{
471
47.1k
    PyObject *key = merge_consts_recursive(c->c_const_cache, o);
472
47.1k
    if (key == NULL) {
473
0
        return ERROR;
474
0
    }
475
476
47.1k
    Py_ssize_t arg = _PyCompile_DictAddObj(c->u->u_metadata.u_consts, key);
477
47.1k
    Py_DECREF(key);
478
47.1k
    return arg;
479
47.1k
}
480
481
static PyObject *
482
list2dict(PyObject *list)
483
5.68k
{
484
5.68k
    Py_ssize_t i, n;
485
5.68k
    PyObject *v, *k;
486
5.68k
    PyObject *dict = PyDict_New();
487
5.68k
    if (!dict) return NULL;
488
489
5.68k
    n = PyList_Size(list);
490
17.0k
    for (i = 0; i < n; i++) {
491
11.3k
        v = PyLong_FromSsize_t(i);
492
11.3k
        if (!v) {
493
0
            Py_DECREF(dict);
494
0
            return NULL;
495
0
        }
496
11.3k
        k = PyList_GET_ITEM(list, i);
497
11.3k
        if (PyDict_SetItem(dict, k, v) < 0) {
498
0
            Py_DECREF(v);
499
0
            Py_DECREF(dict);
500
0
            return NULL;
501
0
        }
502
11.3k
        Py_DECREF(v);
503
11.3k
    }
504
5.68k
    return dict;
505
5.68k
}
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
11.3k
{
518
11.3k
    Py_ssize_t i = offset, num_keys, key_i;
519
11.3k
    PyObject *k, *v, *dest = PyDict_New();
520
11.3k
    PyObject *sorted_keys;
521
522
11.3k
    assert(offset >= 0);
523
11.3k
    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
11.3k
    sorted_keys = PyDict_Keys(src);
532
11.3k
    if (sorted_keys == NULL) {
533
0
        Py_DECREF(dest);
534
0
        return NULL;
535
0
    }
536
11.3k
    if (PyList_Sort(sorted_keys) != 0) {
537
0
        Py_DECREF(sorted_keys);
538
0
        Py_DECREF(dest);
539
0
        return NULL;
540
0
    }
541
11.3k
    num_keys = PyList_GET_SIZE(sorted_keys);
542
543
67.0k
    for (key_i = 0; key_i < num_keys; key_i++) {
544
55.6k
        k = PyList_GET_ITEM(sorted_keys, key_i);
545
55.6k
        v = PyDict_GetItemWithError(src, k);
546
55.6k
        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
55.6k
        long vi = PyLong_AsLong(v);
555
55.6k
        if (vi == -1 && PyErr_Occurred()) {
556
0
            Py_DECREF(sorted_keys);
557
0
            Py_DECREF(dest);
558
0
            return NULL;
559
0
        }
560
55.6k
        if (SYMBOL_TO_SCOPE(vi) == scope_type || vi & flag) {
561
1.94k
            PyObject *item = PyLong_FromSsize_t(i);
562
1.94k
            if (item == NULL) {
563
0
                Py_DECREF(sorted_keys);
564
0
                Py_DECREF(dest);
565
0
                return NULL;
566
0
            }
567
1.94k
            i++;
568
1.94k
            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.94k
            Py_DECREF(item);
575
1.94k
        }
576
55.6k
    }
577
11.3k
    Py_DECREF(sorted_keys);
578
11.3k
    return dest;
579
11.3k
}
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.68k
{
586
5.68k
    struct compiler_unit *u;
587
5.68k
    u = (struct compiler_unit *)PyMem_Calloc(1, sizeof(struct compiler_unit));
588
5.68k
    if (!u) {
589
0
        PyErr_NoMemory();
590
0
        return ERROR;
591
0
    }
592
5.68k
    u->u_scope_type = scope_type;
593
5.68k
    if (umd != NULL) {
594
4.07k
        u->u_metadata = *umd;
595
4.07k
    }
596
1.61k
    else {
597
1.61k
        u->u_metadata.u_argcount = 0;
598
1.61k
        u->u_metadata.u_posonlyargcount = 0;
599
1.61k
        u->u_metadata.u_kwonlyargcount = 0;
600
1.61k
    }
601
5.68k
    u->u_ste = _PySymtable_Lookup(c->c_st, key);
602
5.68k
    if (!u->u_ste) {
603
0
        compiler_unit_free(u);
604
0
        return ERROR;
605
0
    }
606
5.68k
    u->u_metadata.u_name = Py_NewRef(name);
607
5.68k
    u->u_metadata.u_varnames = list2dict(u->u_ste->ste_varnames);
608
5.68k
    if (!u->u_metadata.u_varnames) {
609
0
        compiler_unit_free(u);
610
0
        return ERROR;
611
0
    }
612
5.68k
    u->u_metadata.u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, DEF_COMP_CELL, 0);
613
5.68k
    if (!u->u_metadata.u_cellvars) {
614
0
        compiler_unit_free(u);
615
0
        return ERROR;
616
0
    }
617
5.68k
    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.68k
    if (u->u_ste->ste_needs_classdict) {
628
        /* Cook up an implicit __classdict__ cell. */
629
416
        Py_ssize_t res;
630
416
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS);
631
416
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__classdict__));
632
416
        if (res < 0) {
633
0
            compiler_unit_free(u);
634
0
            return ERROR;
635
0
        }
636
416
    }
637
5.68k
    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.68k
    u->u_metadata.u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
649
5.68k
                               PyDict_GET_SIZE(u->u_metadata.u_cellvars));
650
5.68k
    if (!u->u_metadata.u_freevars) {
651
0
        compiler_unit_free(u);
652
0
        return ERROR;
653
0
    }
654
655
5.68k
    u->u_metadata.u_fasthidden = PyDict_New();
656
5.68k
    if (!u->u_metadata.u_fasthidden) {
657
0
        compiler_unit_free(u);
658
0
        return ERROR;
659
0
    }
660
661
5.68k
    u->u_nfblocks = 0;
662
5.68k
    u->u_in_inlined_comp = 0;
663
5.68k
    u->u_metadata.u_firstlineno = lineno;
664
5.68k
    u->u_metadata.u_consts = PyDict_New();
665
5.68k
    if (!u->u_metadata.u_consts) {
666
0
        compiler_unit_free(u);
667
0
        return ERROR;
668
0
    }
669
5.68k
    u->u_metadata.u_names = PyDict_New();
670
5.68k
    if (!u->u_metadata.u_names) {
671
0
        compiler_unit_free(u);
672
0
        return ERROR;
673
0
    }
674
675
5.68k
    u->u_deferred_annotations = NULL;
676
5.68k
    u->u_conditional_annotation_indices = NULL;
677
5.68k
    u->u_next_conditional_annotation_index = 0;
678
5.68k
    if (scope_type == COMPILE_SCOPE_CLASS) {
679
755
        u->u_static_attributes = PySet_New(0);
680
755
        if (!u->u_static_attributes) {
681
0
            compiler_unit_free(u);
682
0
            return ERROR;
683
0
        }
684
755
    }
685
4.93k
    else {
686
4.93k
        u->u_static_attributes = NULL;
687
4.93k
    }
688
689
5.68k
    u->u_instr_sequence = (instr_sequence*)_PyInstructionSequence_New();
690
5.68k
    if (!u->u_instr_sequence) {
691
0
        compiler_unit_free(u);
692
0
        return ERROR;
693
0
    }
694
5.68k
    u->u_stashed_instr_sequence = NULL;
695
696
    /* Push the old compiler_unit on the stack. */
697
5.68k
    if (c->u) {
698
4.82k
        PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
699
4.82k
        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.82k
        Py_DECREF(capsule);
705
4.82k
        if (private == NULL) {
706
4.07k
            private = c->u->u_private;
707
4.07k
        }
708
4.82k
    }
709
710
5.68k
    u->u_private = Py_XNewRef(private);
711
712
5.68k
    c->u = u;
713
5.68k
    if (scope_type != COMPILE_SCOPE_MODULE) {
714
4.82k
        RETURN_IF_ERROR(compiler_set_qualname(c));
715
4.82k
    }
716
5.68k
    return SUCCESS;
717
5.68k
}
718
719
void
720
_PyCompile_ExitScope(compiler *c)
721
5.68k
{
722
    // Don't call PySequence_DelItem() with an exception raised
723
5.68k
    PyObject *exc = PyErr_GetRaisedException();
724
725
5.68k
    instr_sequence *nested_seq = NULL;
726
5.68k
    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.68k
    compiler_unit_free(c->u);
731
    /* Restore c->u to the parent unit. */
732
5.68k
    Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
733
5.68k
    if (n >= 0) {
734
4.82k
        PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
735
4.82k
        c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
736
4.82k
        assert(c->u);
737
        /* we are deleting from a list so this really shouldn't fail */
738
4.82k
        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.82k
        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.82k
    }
749
859
    else {
750
859
        c->u = NULL;
751
859
    }
752
5.68k
    Py_XDECREF(nested_seq);
753
754
5.68k
    PyErr_SetRaisedException(exc);
755
5.68k
}
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.70k
{
798
3.70k
    if (c->u->u_nfblocks == 0) {
799
3.06k
        return NULL;
800
3.06k
    }
801
643
    return &c->u->u_fblock[c->u->u_nfblocks - 1];
802
3.70k
}
803
804
bool
805
_PyCompile_InExceptionHandler(compiler *c)
806
902
{
807
907
    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
885
    return false;
822
902
}
823
824
void
825
_PyCompile_DeferredAnnotations(compiler *c,
826
                               PyObject **deferred_annotations,
827
                               PyObject **conditional_annotation_indices)
828
1.36k
{
829
1.36k
    *deferred_annotations = Py_XNewRef(c->u->u_deferred_annotations);
830
1.36k
    *conditional_annotation_indices = Py_XNewRef(c->u->u_conditional_annotation_indices);
831
1.36k
}
832
833
static location
834
start_location(asdl_stmt_seq *stmts)
835
608
{
836
608
    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
606
        stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
843
606
        return SRC_LOCATION_FROM_AST(st);
844
606
    }
845
2
    return (const _Py_SourceLocation){1, 1, 0, 0};
846
608
}
847
848
static int
849
compiler_codegen(compiler *c, mod_ty mod)
850
859
{
851
859
    RETURN_IF_ERROR(_PyCodegen_EnterAnonymousScope(c, mod));
852
859
    assert(c->u->u_scope_type == COMPILE_SCOPE_MODULE);
853
859
    switch (mod->kind) {
854
608
    case Module_kind: {
855
608
        asdl_stmt_seq *stmts = mod->v.Module.body;
856
608
        RETURN_IF_ERROR(_PyCodegen_Module(c, start_location(stmts), stmts, false));
857
608
        break;
858
608
    }
859
608
    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
251
    case Expression_kind: {
866
251
        RETURN_IF_ERROR(_PyCodegen_Expression(c, mod->v.Expression.body));
867
251
        break;
868
251
    }
869
251
    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
251
    }}
875
859
    return SUCCESS;
876
859
}
877
878
static PyCodeObject *
879
compiler_mod(compiler *c, mod_ty mod)
880
859
{
881
859
    PyCodeObject *co = NULL;
882
859
    int addNone = mod->kind != Expression_kind;
883
859
    if (compiler_codegen(c, mod) < 0) {
884
0
        goto finally;
885
0
    }
886
859
    co = _PyCompile_OptimizeAndAssemble(c, addNone);
887
859
finally:
888
859
    _PyCompile_ExitScope(c);
889
859
    return co;
890
859
}
891
892
int
893
_PyCompile_GetRefType(compiler *c, PyObject *name)
894
1.21k
{
895
1.21k
    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.11k
    PySTEntryObject *ste = c->u->u_ste;
902
1.11k
    int scope = _PyST_GetScope(ste, name);
903
1.11k
    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.11k
    return scope;
916
1.11k
}
917
918
static int
919
dict_lookup_arg(PyObject *dict, PyObject *name)
920
1.61k
{
921
1.61k
    PyObject *v = PyDict_GetItemWithError(dict, name);
922
1.61k
    if (v == NULL) {
923
0
        return ERROR;
924
0
    }
925
1.61k
    return PyLong_AsLong(v);
926
1.61k
}
927
928
int
929
_PyCompile_LookupCellvar(compiler *c, PyObject *name)
930
452
{
931
452
    assert(c->u->u_metadata.u_cellvars);
932
452
    return dict_lookup_arg(c->u->u_metadata.u_cellvars, name);
933
452
}
934
935
int
936
_PyCompile_LookupArg(compiler *c, PyCodeObject *co, PyObject *name)
937
1.16k
{
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.16k
    int reftype = _PyCompile_GetRefType(c, name);
945
1.16k
    if (reftype == -1) {
946
0
        return ERROR;
947
0
    }
948
1.16k
    int arg;
949
1.16k
    if (reftype == CELL) {
950
1.15k
        arg = dict_lookup_arg(c->u->u_metadata.u_cellvars, name);
951
1.15k
    }
952
9
    else {
953
9
        arg = dict_lookup_arg(c->u->u_metadata.u_freevars, name);
954
9
    }
955
1.16k
    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.16k
    return arg;
972
1.16k
}
973
974
PyObject *
975
_PyCompile_StaticAttributesAsTuple(compiler *c)
976
755
{
977
755
    assert(c->u->u_static_attributes);
978
755
    PyObject *static_attributes_unsorted = PySequence_List(c->u->u_static_attributes);
979
755
    if (static_attributes_unsorted == NULL) {
980
0
        return NULL;
981
0
    }
982
755
    if (PyList_Sort(static_attributes_unsorted) != 0) {
983
0
        Py_DECREF(static_attributes_unsorted);
984
0
        return NULL;
985
0
    }
986
755
    PyObject *static_attributes = PySequence_Tuple(static_attributes_unsorted);
987
755
    Py_DECREF(static_attributes_unsorted);
988
755
    return static_attributes;
989
755
}
990
991
int
992
_PyCompile_ResolveNameop(compiler *c, PyObject *mangled, int scope,
993
                          _PyCompile_optype *optype, Py_ssize_t *arg)
994
58.0k
{
995
58.0k
    PyObject *dict = c->u->u_metadata.u_names;
996
58.0k
    *optype = COMPILE_OP_NAME;
997
998
58.0k
    assert(scope >= 0);
999
58.0k
    switch (scope) {
1000
2.38k
    case FREE:
1001
2.38k
        dict = c->u->u_metadata.u_freevars;
1002
2.38k
        *optype = COMPILE_OP_DEREF;
1003
2.38k
        break;
1004
648
    case CELL:
1005
648
        dict = c->u->u_metadata.u_cellvars;
1006
648
        *optype = COMPILE_OP_DEREF;
1007
648
        break;
1008
42.0k
    case LOCAL:
1009
42.0k
        if (_PyST_IsFunctionLike(c->u->u_ste)) {
1010
35.3k
            *optype = COMPILE_OP_FAST;
1011
35.3k
        }
1012
6.75k
        else {
1013
6.75k
            PyObject *item;
1014
6.75k
            RETURN_IF_ERROR(PyDict_GetItemRef(c->u->u_metadata.u_fasthidden, mangled,
1015
6.75k
                                              &item));
1016
6.75k
            if (item == Py_True) {
1017
10
                *optype = COMPILE_OP_FAST;
1018
10
            }
1019
6.75k
            Py_XDECREF(item);
1020
6.75k
        }
1021
42.0k
        break;
1022
42.0k
    case GLOBAL_IMPLICIT:
1023
8.42k
        if (_PyST_IsFunctionLike(c->u->u_ste)) {
1024
7.94k
            *optype = COMPILE_OP_GLOBAL;
1025
7.94k
        }
1026
8.42k
        break;
1027
28
    case GLOBAL_EXPLICIT:
1028
28
        *optype = COMPILE_OP_GLOBAL;
1029
28
        break;
1030
4.47k
    default:
1031
        /* scope can be 0 */
1032
4.47k
        break;
1033
58.0k
    }
1034
58.0k
    if (*optype != COMPILE_OP_FAST) {
1035
22.7k
        *arg = _PyCompile_DictAddObj(dict, mangled);
1036
22.7k
        RETURN_IF_ERROR(*arg);
1037
22.7k
    }
1038
58.0k
    return SUCCESS;
1039
58.0k
}
1040
1041
int
1042
_PyCompile_TweakInlinedComprehensionScopes(compiler *c, location loc,
1043
                                            PySTEntryObject *entry,
1044
                                            _PyCompile_InlinedComprehensionState *state)
1045
55
{
1046
55
    int in_class_block = (c->u->u_ste->ste_type == ClassBlock) && !c->u->u_in_inlined_comp;
1047
55
    c->u->u_in_inlined_comp++;
1048
1049
55
    PyObject *k, *v;
1050
55
    Py_ssize_t pos = 0;
1051
226
    while (PyDict_Next(entry->ste_symbols, &pos, &k, &v)) {
1052
171
        long symbol = PyLong_AsLong(v);
1053
171
        assert(symbol >= 0 || PyErr_Occurred());
1054
171
        RETURN_IF_ERROR(symbol);
1055
171
        long scope = SYMBOL_TO_SCOPE(symbol);
1056
1057
171
        long outsymbol = _PyST_GetSymbol(c->u->u_ste, k);
1058
171
        RETURN_IF_ERROR(outsymbol);
1059
171
        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
171
        if ((scope != outsc && scope != FREE && !(scope == CELL && outsc == FREE))
1070
116
                || in_class_block) {
1071
56
            if (state->temp_symbols == NULL) {
1072
55
                state->temp_symbols = PyDict_New();
1073
55
                if (state->temp_symbols == NULL) {
1074
0
                    return ERROR;
1075
0
                }
1076
55
            }
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
56
            if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v) < 0) {
1081
0
                return ERROR;
1082
0
            }
1083
56
            PyObject *outv = PyLong_FromLong(outsymbol);
1084
56
            if (outv == NULL) {
1085
0
                return ERROR;
1086
0
            }
1087
56
            int res = PyDict_SetItem(state->temp_symbols, k, outv);
1088
56
            Py_DECREF(outv);
1089
56
            RETURN_IF_ERROR(res);
1090
56
        }
1091
        // locals handling for names bound in comprehension (DEF_LOCAL |
1092
        // DEF_NONLOCAL occurs in assignment expression to nonlocal)
1093
171
        if ((symbol & DEF_LOCAL && !(symbol & DEF_NONLOCAL)) || in_class_block) {
1094
66
            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
                        Py_XDECREF(orig);
1104
0
                        return ERROR;
1105
0
                    }
1106
5
                    if (state->fast_hidden == NULL) {
1107
4
                        state->fast_hidden = PySet_New(NULL);
1108
4
                        if (state->fast_hidden == NULL) {
1109
0
                            Py_XDECREF(orig);
1110
0
                            return ERROR;
1111
0
                        }
1112
4
                    }
1113
5
                    if (PySet_Add(state->fast_hidden, k) < 0) {
1114
0
                        Py_XDECREF(orig);
1115
0
                        return ERROR;
1116
0
                    }
1117
5
                }
1118
5
                Py_XDECREF(orig);
1119
5
            }
1120
66
        }
1121
171
    }
1122
55
    return SUCCESS;
1123
55
}
1124
1125
int
1126
_PyCompile_RevertInlinedComprehensionScopes(compiler *c, location loc,
1127
                                             _PyCompile_InlinedComprehensionState *state)
1128
55
{
1129
55
    c->u->u_in_inlined_comp--;
1130
55
    if (state->temp_symbols) {
1131
55
        PyObject *k, *v;
1132
55
        Py_ssize_t pos = 0;
1133
111
        while (PyDict_Next(state->temp_symbols, &pos, &k, &v)) {
1134
56
            if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v)) {
1135
0
                return ERROR;
1136
0
            }
1137
56
        }
1138
55
        Py_CLEAR(state->temp_symbols);
1139
55
    }
1140
55
    if (state->fast_hidden) {
1141
9
        while (PySet_Size(state->fast_hidden) > 0) {
1142
5
            PyObject *k = PySet_Pop(state->fast_hidden);
1143
5
            if (k == NULL) {
1144
0
                return ERROR;
1145
0
            }
1146
            // we set to False instead of clearing, so we can track which names
1147
            // were temporarily fast-locals and should use CO_FAST_HIDDEN
1148
5
            if (PyDict_SetItem(c->u->u_metadata.u_fasthidden, k, Py_False)) {
1149
0
                Py_DECREF(k);
1150
0
                return ERROR;
1151
0
            }
1152
5
            Py_DECREF(k);
1153
5
        }
1154
4
        Py_CLEAR(state->fast_hidden);
1155
4
    }
1156
55
    return SUCCESS;
1157
55
}
1158
1159
void
1160
_PyCompile_EnterConditionalBlock(struct _PyCompiler *c)
1161
4.18k
{
1162
4.18k
    c->u->u_in_conditional_block++;
1163
4.18k
}
1164
1165
void
1166
_PyCompile_LeaveConditionalBlock(struct _PyCompiler *c)
1167
4.18k
{
1168
4.18k
    assert(c->u->u_in_conditional_block > 0);
1169
4.18k
    c->u->u_in_conditional_block--;
1170
4.18k
}
1171
1172
int
1173
_PyCompile_AddDeferredAnnotation(compiler *c, stmt_ty s,
1174
                                 PyObject **conditional_annotation_index)
1175
12
{
1176
12
    if (c->u->u_deferred_annotations == NULL) {
1177
6
        c->u->u_deferred_annotations = PyList_New(0);
1178
6
        if (c->u->u_deferred_annotations == NULL) {
1179
0
            return ERROR;
1180
0
        }
1181
6
    }
1182
12
    if (c->u->u_conditional_annotation_indices == NULL) {
1183
6
        c->u->u_conditional_annotation_indices = PyList_New(0);
1184
6
        if (c->u->u_conditional_annotation_indices == NULL) {
1185
0
            return ERROR;
1186
0
        }
1187
6
    }
1188
12
    PyObject *ptr = PyLong_FromVoidPtr((void *)s);
1189
12
    if (ptr == NULL) {
1190
0
        return ERROR;
1191
0
    }
1192
12
    if (PyList_Append(c->u->u_deferred_annotations, ptr) < 0) {
1193
0
        Py_DECREF(ptr);
1194
0
        return ERROR;
1195
0
    }
1196
12
    Py_DECREF(ptr);
1197
12
    PyObject *index;
1198
12
    if (c->u->u_scope_type == COMPILE_SCOPE_MODULE || c->u->u_in_conditional_block) {
1199
0
        index = PyLong_FromLong(c->u->u_next_conditional_annotation_index);
1200
0
        if (index == NULL) {
1201
0
            return ERROR;
1202
0
        }
1203
0
        *conditional_annotation_index = Py_NewRef(index);
1204
0
        c->u->u_next_conditional_annotation_index++;
1205
0
    }
1206
12
    else {
1207
12
        index = PyLong_FromLong(-1);
1208
12
        if (index == NULL) {
1209
0
            return ERROR;
1210
0
        }
1211
12
    }
1212
12
    int rc = PyList_Append(c->u->u_conditional_annotation_indices, index);
1213
12
    Py_DECREF(index);
1214
12
    RETURN_IF_ERROR(rc);
1215
12
    return SUCCESS;
1216
12
}
1217
1218
/* Raises a SyntaxError and returns ERROR.
1219
 * If something goes wrong, a different exception may be raised.
1220
 */
1221
int
1222
_PyCompile_Error(compiler *c, location loc, const char *format, ...)
1223
0
{
1224
0
    va_list vargs;
1225
0
    va_start(vargs, format);
1226
0
    PyObject *msg = PyUnicode_FromFormatV(format, vargs);
1227
0
    va_end(vargs);
1228
0
    if (msg == NULL) {
1229
0
        return ERROR;
1230
0
    }
1231
0
    _PyErr_RaiseSyntaxError(msg, c->c_filename, loc.lineno, loc.col_offset + 1,
1232
0
                            loc.end_lineno, loc.end_col_offset + 1);
1233
0
    Py_DECREF(msg);
1234
0
    return ERROR;
1235
0
}
1236
1237
/* Emits a SyntaxWarning and returns 0 on success.
1238
   If a SyntaxWarning raised as error, replaces it with a SyntaxError
1239
   and returns -1.
1240
*/
1241
int
1242
_PyCompile_Warn(compiler *c, location loc, const char *format, ...)
1243
0
{
1244
0
    if (c->c_disable_warning) {
1245
0
        return 0;
1246
0
    }
1247
0
    va_list vargs;
1248
0
    va_start(vargs, format);
1249
0
    PyObject *msg = PyUnicode_FromFormatV(format, vargs);
1250
0
    va_end(vargs);
1251
0
    if (msg == NULL) {
1252
0
        return ERROR;
1253
0
    }
1254
0
    int ret = _PyErr_EmitSyntaxWarning(msg, c->c_filename, loc.lineno, loc.col_offset + 1,
1255
0
                                       loc.end_lineno, loc.end_col_offset + 1,
1256
0
                                       c->c_module);
1257
0
    Py_DECREF(msg);
1258
0
    return ret;
1259
0
}
1260
1261
PyObject *
1262
_PyCompile_Mangle(compiler *c, PyObject *name)
1263
12
{
1264
12
    return _Py_Mangle(c->u->u_private, name);
1265
12
}
1266
1267
PyObject *
1268
_PyCompile_MaybeMangle(compiler *c, PyObject *name)
1269
80.0k
{
1270
80.0k
    return _Py_MaybeMangle(c->u->u_private, c->u->u_ste, name);
1271
80.0k
}
1272
1273
instr_sequence *
1274
_PyCompile_InstrSequence(compiler *c)
1275
270k
{
1276
270k
    return c->u->u_instr_sequence;
1277
270k
}
1278
1279
int
1280
_PyCompile_StartAnnotationSetup(struct _PyCompiler *c)
1281
0
{
1282
0
    instr_sequence *new_seq = (instr_sequence *)_PyInstructionSequence_New();
1283
0
    if (new_seq == NULL) {
1284
0
        return ERROR;
1285
0
    }
1286
0
    assert(c->u->u_stashed_instr_sequence == NULL);
1287
0
    c->u->u_stashed_instr_sequence = c->u->u_instr_sequence;
1288
0
    c->u->u_instr_sequence = new_seq;
1289
0
    return SUCCESS;
1290
0
}
1291
1292
int
1293
_PyCompile_EndAnnotationSetup(struct _PyCompiler *c)
1294
0
{
1295
0
    assert(c->u->u_stashed_instr_sequence != NULL);
1296
0
    instr_sequence *parent_seq = c->u->u_stashed_instr_sequence;
1297
0
    instr_sequence *anno_seq = c->u->u_instr_sequence;
1298
0
    c->u->u_stashed_instr_sequence = NULL;
1299
0
    c->u->u_instr_sequence = parent_seq;
1300
0
    if (_PyInstructionSequence_SetAnnotationsCode(parent_seq, anno_seq) == ERROR) {
1301
0
        Py_DECREF(anno_seq);
1302
0
        return ERROR;
1303
0
    }
1304
0
    return SUCCESS;
1305
0
}
1306
1307
1308
int
1309
_PyCompile_FutureFeatures(compiler *c)
1310
2.82k
{
1311
2.82k
    return c->c_future.ff_features;
1312
2.82k
}
1313
1314
struct symtable *
1315
_PyCompile_Symtable(compiler *c)
1316
9.20k
{
1317
9.20k
    return c->c_st;
1318
9.20k
}
1319
1320
PySTEntryObject *
1321
_PyCompile_SymtableEntry(compiler *c)
1322
93.0k
{
1323
93.0k
    return c->u->u_ste;
1324
93.0k
}
1325
1326
int
1327
_PyCompile_OptimizationLevel(compiler *c)
1328
89
{
1329
89
    return c->c_optimize;
1330
89
}
1331
1332
int
1333
_PyCompile_IsInteractiveTopLevel(compiler *c)
1334
4.16k
{
1335
4.16k
    assert(c->c_stack != NULL);
1336
4.16k
    assert(PyList_CheckExact(c->c_stack));
1337
4.16k
    bool is_nested_scope = PyList_GET_SIZE(c->c_stack) > 0;
1338
4.16k
    return c->c_interactive && !is_nested_scope;
1339
4.16k
}
1340
1341
int
1342
_PyCompile_ScopeType(compiler *c)
1343
942
{
1344
942
    return c->u->u_scope_type;
1345
942
}
1346
1347
int
1348
_PyCompile_IsInInlinedComp(compiler *c)
1349
1.20k
{
1350
1.20k
    return c->u->u_in_inlined_comp;
1351
1.20k
}
1352
1353
PyObject *
1354
_PyCompile_Qualname(compiler *c)
1355
755
{
1356
755
    assert(c->u->u_metadata.u_qualname);
1357
755
    return c->u->u_metadata.u_qualname;
1358
755
}
1359
1360
_PyCompile_CodeUnitMetadata *
1361
_PyCompile_Metadata(compiler *c)
1362
57.2k
{
1363
57.2k
    return &c->u->u_metadata;
1364
57.2k
}
1365
1366
// Merge *obj* with constant cache, without recursion.
1367
int
1368
_PyCompile_ConstCacheMergeOne(PyObject *const_cache, PyObject **obj)
1369
35.2k
{
1370
35.2k
    PyObject *key = const_cache_insert(const_cache, *obj, false);
1371
35.2k
    if (key == NULL) {
1372
0
        return ERROR;
1373
0
    }
1374
35.2k
    if (PyTuple_CheckExact(key)) {
1375
35.1k
        PyObject *item = PyTuple_GET_ITEM(key, 1);
1376
35.1k
        Py_SETREF(*obj, Py_NewRef(item));
1377
35.1k
        Py_DECREF(key);
1378
35.1k
    }
1379
125
    else {
1380
125
        Py_SETREF(*obj, key);
1381
125
    }
1382
35.2k
    return SUCCESS;
1383
35.2k
}
1384
1385
static PyObject *
1386
consts_dict_keys_inorder(PyObject *dict)
1387
5.68k
{
1388
5.68k
    PyObject *consts, *k, *v;
1389
5.68k
    Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
1390
1391
5.68k
    consts = PyList_New(size);   /* PyCode_Optimize() requires a list */
1392
5.68k
    if (consts == NULL)
1393
0
        return NULL;
1394
38.4k
    while (PyDict_Next(dict, &pos, &k, &v)) {
1395
32.7k
        assert(PyLong_CheckExact(v));
1396
32.7k
        i = PyLong_AsLong(v);
1397
        /* The keys of the dictionary can be tuples wrapping a constant.
1398
         * (see _PyCompile_DictAddObj and _PyCode_ConstantKey). In that case
1399
         * the object we want is always second. */
1400
32.7k
        if (PyTuple_CheckExact(k)) {
1401
2.59k
            k = PyTuple_GET_ITEM(k, 1);
1402
2.59k
        }
1403
32.7k
        assert(i < size);
1404
32.7k
        assert(i >= 0);
1405
32.7k
        PyList_SET_ITEM(consts, i, Py_NewRef(k));
1406
32.7k
    }
1407
5.68k
    return consts;
1408
5.68k
}
1409
1410
static int
1411
compute_code_flags(compiler *c)
1412
5.68k
{
1413
5.68k
    PySTEntryObject *ste = c->u->u_ste;
1414
5.68k
    int flags = 0;
1415
5.68k
    if (_PyST_IsFunctionLike(ste)) {
1416
4.07k
        flags |= CO_NEWLOCALS | CO_OPTIMIZED;
1417
4.07k
        if (ste->ste_nested)
1418
1.17k
            flags |= CO_NESTED;
1419
4.07k
        if (ste->ste_generator && !ste->ste_coroutine)
1420
115
            flags |= CO_GENERATOR;
1421
4.07k
        if (ste->ste_generator && ste->ste_coroutine)
1422
0
            flags |= CO_ASYNC_GENERATOR;
1423
4.07k
        if (ste->ste_varargs)
1424
117
            flags |= CO_VARARGS;
1425
4.07k
        if (ste->ste_varkeywords)
1426
106
            flags |= CO_VARKEYWORDS;
1427
4.07k
        if (ste->ste_has_docstring)
1428
579
            flags |= CO_HAS_DOCSTRING;
1429
4.07k
        if (ste->ste_method)
1430
1.82k
            flags |= CO_METHOD;
1431
4.07k
    }
1432
1433
5.68k
    if (ste->ste_coroutine && !ste->ste_generator) {
1434
135
        flags |= CO_COROUTINE;
1435
135
    }
1436
1437
    /* (Only) inherit compilerflags in PyCF_MASK */
1438
5.68k
    flags |= (c->c_flags.cf_flags & PyCF_MASK);
1439
1440
5.68k
    return flags;
1441
5.68k
}
1442
1443
static PyCodeObject *
1444
optimize_and_assemble_code_unit(struct compiler_unit *u, PyObject *const_cache,
1445
                                int code_flags, PyObject *filename)
1446
5.68k
{
1447
5.68k
    cfg_builder *g = NULL;
1448
5.68k
    instr_sequence optimized_instrs;
1449
5.68k
    memset(&optimized_instrs, 0, sizeof(instr_sequence));
1450
1451
5.68k
    PyCodeObject *co = NULL;
1452
5.68k
    PyObject *consts = consts_dict_keys_inorder(u->u_metadata.u_consts);
1453
5.68k
    if (consts == NULL) {
1454
0
        goto error;
1455
0
    }
1456
5.68k
    g = _PyCfg_FromInstructionSequence(u->u_instr_sequence);
1457
5.68k
    if (g == NULL) {
1458
0
        goto error;
1459
0
    }
1460
5.68k
    int nlocals = (int)PyDict_GET_SIZE(u->u_metadata.u_varnames);
1461
5.68k
    int nparams = (int)PyList_GET_SIZE(u->u_ste->ste_varnames);
1462
5.68k
    assert(u->u_metadata.u_firstlineno);
1463
1464
5.68k
    if (_PyCfg_OptimizeCodeUnit(g, consts, const_cache, nlocals,
1465
5.68k
                                nparams, u->u_metadata.u_firstlineno) < 0) {
1466
0
        goto error;
1467
0
    }
1468
1469
5.68k
    int stackdepth;
1470
5.68k
    int nlocalsplus;
1471
5.68k
    if (_PyCfg_OptimizedCfgToInstructionSequence(g, &u->u_metadata,
1472
5.68k
                                                 &stackdepth, &nlocalsplus,
1473
5.68k
                                                 &optimized_instrs) < 0) {
1474
0
        goto error;
1475
0
    }
1476
1477
    /** Assembly **/
1478
5.68k
    co = _PyAssemble_MakeCodeObject(&u->u_metadata, const_cache, consts,
1479
5.68k
                                    stackdepth, &optimized_instrs, nlocalsplus,
1480
5.68k
                                    code_flags, filename);
1481
1482
5.68k
error:
1483
5.68k
    Py_XDECREF(consts);
1484
5.68k
    PyInstructionSequence_Fini(&optimized_instrs);
1485
5.68k
    _PyCfgBuilder_Free(g);
1486
5.68k
    return co;
1487
5.68k
}
1488
1489
1490
PyCodeObject *
1491
_PyCompile_OptimizeAndAssemble(compiler *c, int addNone)
1492
5.68k
{
1493
5.68k
    struct compiler_unit *u = c->u;
1494
5.68k
    PyObject *const_cache = c->c_const_cache;
1495
5.68k
    PyObject *filename = c->c_filename;
1496
1497
5.68k
    int code_flags = compute_code_flags(c);
1498
5.68k
    if (code_flags < 0) {
1499
0
        return NULL;
1500
0
    }
1501
1502
5.68k
    if (_PyCodegen_AddReturnAtEnd(c, addNone) < 0) {
1503
0
        return NULL;
1504
0
    }
1505
1506
5.68k
    return optimize_and_assemble_code_unit(u, const_cache, code_flags, filename);
1507
5.68k
}
1508
1509
PyCodeObject *
1510
_PyAST_Compile(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
1511
               int optimize, PyArena *arena, PyObject *module)
1512
859
{
1513
859
    assert(!PyErr_Occurred());
1514
859
    compiler *c = new_compiler(mod, filename, pflags, optimize, arena, module);
1515
859
    if (c == NULL) {
1516
0
        return NULL;
1517
0
    }
1518
1519
859
    PyCodeObject *co = compiler_mod(c, mod);
1520
859
    compiler_free(c);
1521
859
    assert(co || PyErr_Occurred());
1522
859
    return co;
1523
859
}
1524
1525
int
1526
_PyCompile_AstPreprocess(mod_ty mod, PyObject *filename, PyCompilerFlags *cf,
1527
                         int optimize, PyArena *arena, int no_const_folding,
1528
                         PyObject *module)
1529
6.13k
{
1530
6.13k
    _PyFutureFeatures future;
1531
6.13k
    if (!_PyFuture_FromAST(mod, filename, &future)) {
1532
23
        return -1;
1533
23
    }
1534
6.10k
    int flags = future.ff_features | cf->cf_flags;
1535
6.10k
    if (optimize == -1) {
1536
6.10k
        optimize = _Py_GetConfig()->optimization_level;
1537
6.10k
    }
1538
6.10k
    if (!_PyAST_Preprocess(mod, arena, filename, optimize, flags,
1539
6.10k
                           no_const_folding, 0, module))
1540
0
    {
1541
0
        return -1;
1542
0
    }
1543
6.10k
    return 0;
1544
6.10k
}
1545
1546
// C implementation of inspect.cleandoc()
1547
//
1548
// Difference from inspect.cleandoc():
1549
// - Do not remove leading and trailing blank lines to keep lineno.
1550
PyObject *
1551
_PyCompile_CleanDoc(PyObject *doc)
1552
817
{
1553
817
    doc = PyObject_CallMethod(doc, "expandtabs", NULL);
1554
817
    if (doc == NULL) {
1555
0
        return NULL;
1556
0
    }
1557
1558
817
    Py_ssize_t doc_size;
1559
817
    const char *doc_utf8 = PyUnicode_AsUTF8AndSize(doc, &doc_size);
1560
817
    if (doc_utf8 == NULL) {
1561
0
        Py_DECREF(doc);
1562
0
        return NULL;
1563
0
    }
1564
817
    const char *p = doc_utf8;
1565
817
    const char *pend = p + doc_size;
1566
1567
    // First pass: find minimum indentation of any non-blank lines
1568
    // after first line.
1569
39.6k
    while (p < pend && *p++ != '\n') {
1570
38.8k
    }
1571
1572
817
    Py_ssize_t margin = PY_SSIZE_T_MAX;
1573
5.18k
    while (p < pend) {
1574
4.36k
        const char *s = p;
1575
26.3k
        while (*p == ' ') p++;
1576
4.36k
        if (p < pend && *p != '\n') {
1577
2.89k
            margin = Py_MIN(margin, p - s);
1578
2.89k
        }
1579
145k
        while (p < pend && *p++ != '\n') {
1580
141k
        }
1581
4.36k
    }
1582
817
    if (margin == PY_SSIZE_T_MAX) {
1583
350
        margin = 0;
1584
350
    }
1585
1586
    // Second pass: write cleandoc into buff.
1587
1588
    // copy first line without leading spaces.
1589
817
    p = doc_utf8;
1590
903
    while (*p == ' ') {
1591
86
        p++;
1592
86
    }
1593
817
    if (p == doc_utf8 && margin == 0 ) {
1594
        // doc is already clean.
1595
302
        return doc;
1596
302
    }
1597
1598
515
    char *buff = PyMem_Malloc(doc_size);
1599
515
    if (buff == NULL){
1600
0
        Py_DECREF(doc);
1601
0
        PyErr_NoMemory();
1602
0
        return NULL;
1603
0
    }
1604
1605
515
    char *w = buff;
1606
1607
25.8k
    while (p < pend) {
1608
25.8k
        int ch = *w++ = *p++;
1609
25.8k
        if (ch == '\n') {
1610
514
            break;
1611
514
        }
1612
25.8k
    }
1613
1614
    // copy subsequent lines without margin.
1615
4.66k
    while (p < pend) {
1616
23.2k
        for (Py_ssize_t i = 0; i < margin; i++, p++) {
1617
20.0k
            if (*p != ' ') {
1618
912
                assert(*p == '\n' || *p == '\0');
1619
912
                break;
1620
912
            }
1621
20.0k
        }
1622
141k
        while (p < pend) {
1623
140k
            int ch = *w++ = *p++;
1624
140k
            if (ch == '\n') {
1625
3.71k
                break;
1626
3.71k
            }
1627
140k
        }
1628
4.14k
    }
1629
1630
515
    Py_DECREF(doc);
1631
515
    PyObject *res = PyUnicode_FromStringAndSize(buff, w - buff);
1632
515
    PyMem_Free(buff);
1633
515
    return res;
1634
515
}
1635
1636
/* Access to compiler optimizations for unit tests.
1637
 *
1638
 * _PyCompile_CodeGen takes an AST, applies code-gen and
1639
 * returns the unoptimized CFG as an instruction list.
1640
 *
1641
 */
1642
PyObject *
1643
_PyCompile_CodeGen(PyObject *ast, PyObject *filename, PyCompilerFlags *pflags,
1644
                   int optimize, int compile_mode)
1645
0
{
1646
0
    PyObject *res = NULL;
1647
0
    PyObject *metadata = NULL;
1648
1649
0
    if (!PyAST_Check(ast)) {
1650
0
        PyErr_SetString(PyExc_TypeError, "expected an AST");
1651
0
        return NULL;
1652
0
    }
1653
1654
0
    PyArena *arena = _PyArena_New();
1655
0
    if (arena == NULL) {
1656
0
        return NULL;
1657
0
    }
1658
1659
0
    mod_ty mod = PyAST_obj2mod(ast, arena, compile_mode);
1660
0
    if (mod == NULL || !_PyAST_Validate(mod)) {
1661
0
        _PyArena_Free(arena);
1662
0
        return NULL;
1663
0
    }
1664
1665
0
    compiler *c = new_compiler(mod, filename, pflags, optimize, arena, NULL);
1666
0
    if (c == NULL) {
1667
0
        _PyArena_Free(arena);
1668
0
        return NULL;
1669
0
    }
1670
0
    c->c_save_nested_seqs = true;
1671
1672
0
    metadata = PyDict_New();
1673
0
    if (metadata == NULL) {
1674
0
        return NULL;
1675
0
    }
1676
1677
0
    if (compiler_codegen(c, mod) < 0) {
1678
0
        goto finally;
1679
0
    }
1680
1681
0
    _PyCompile_CodeUnitMetadata *umd = &c->u->u_metadata;
1682
1683
0
#define SET_METADATA_INT(key, value) do { \
1684
0
        PyObject *v = PyLong_FromLong((long)value); \
1685
0
        if (v == NULL) goto finally; \
1686
0
        int res = PyDict_SetItemString(metadata, key, v); \
1687
0
        Py_XDECREF(v); \
1688
0
        if (res < 0) goto finally; \
1689
0
    } while (0);
1690
1691
0
    SET_METADATA_INT("argcount", umd->u_argcount);
1692
0
    SET_METADATA_INT("posonlyargcount", umd->u_posonlyargcount);
1693
0
    SET_METADATA_INT("kwonlyargcount", umd->u_kwonlyargcount);
1694
0
#undef SET_METADATA_INT
1695
1696
0
    int addNone = mod->kind != Expression_kind;
1697
0
    if (_PyCodegen_AddReturnAtEnd(c, addNone) < 0) {
1698
0
        goto finally;
1699
0
    }
1700
1701
0
    if (_PyInstructionSequence_ApplyLabelMap(_PyCompile_InstrSequence(c)) < 0) {
1702
0
        return NULL;
1703
0
    }
1704
    /* Allocate a copy of the instruction sequence on the heap */
1705
0
    res = _PyTuple_FromPair((PyObject *)_PyCompile_InstrSequence(c), metadata);
1706
1707
0
finally:
1708
0
    Py_XDECREF(metadata);
1709
0
    _PyCompile_ExitScope(c);
1710
0
    compiler_free(c);
1711
0
    _PyArena_Free(arena);
1712
0
    return res;
1713
0
}
1714
1715
int _PyCfg_JumpLabelsToTargets(cfg_builder *g);
1716
1717
PyCodeObject *
1718
_PyCompile_Assemble(_PyCompile_CodeUnitMetadata *umd, PyObject *filename,
1719
                    PyObject *seq)
1720
0
{
1721
0
    if (!_PyInstructionSequence_Check(seq)) {
1722
0
        PyErr_SetString(PyExc_TypeError, "expected an instruction sequence");
1723
0
        return NULL;
1724
0
    }
1725
0
    cfg_builder *g = NULL;
1726
0
    PyCodeObject *co = NULL;
1727
0
    instr_sequence optimized_instrs;
1728
0
    memset(&optimized_instrs, 0, sizeof(instr_sequence));
1729
1730
0
    PyObject *const_cache = PyDict_New();
1731
0
    if (const_cache == NULL) {
1732
0
        return NULL;
1733
0
    }
1734
1735
0
    g = _PyCfg_FromInstructionSequence((instr_sequence*)seq);
1736
0
    if (g == NULL) {
1737
0
        goto error;
1738
0
    }
1739
1740
0
    if (_PyCfg_JumpLabelsToTargets(g) < 0) {
1741
0
        goto error;
1742
0
    }
1743
1744
0
    int code_flags = 0;
1745
0
    int stackdepth, nlocalsplus;
1746
0
    if (_PyCfg_OptimizedCfgToInstructionSequence(g, umd,
1747
0
                                                 &stackdepth, &nlocalsplus,
1748
0
                                                 &optimized_instrs) < 0) {
1749
0
        goto error;
1750
0
    }
1751
1752
0
    PyObject *consts = consts_dict_keys_inorder(umd->u_consts);
1753
0
    if (consts == NULL) {
1754
0
        goto error;
1755
0
    }
1756
0
    co = _PyAssemble_MakeCodeObject(umd, const_cache,
1757
0
                                    consts, stackdepth, &optimized_instrs,
1758
0
                                    nlocalsplus, code_flags, filename);
1759
0
    Py_DECREF(consts);
1760
1761
0
error:
1762
0
    Py_DECREF(const_cache);
1763
0
    _PyCfgBuilder_Free(g);
1764
0
    PyInstructionSequence_Fini(&optimized_instrs);
1765
0
    return co;
1766
0
}
1767
1768
/* Retained for API compatibility.
1769
 * Optimization is now done in _PyCfg_OptimizeCodeUnit */
1770
1771
PyObject *
1772
PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
1773
                PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
1774
0
{
1775
0
    return Py_NewRef(code);
1776
0
}