Coverage Report

Created: 2026-06-09 06:53

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