Coverage Report

Created: 2026-04-20 06:11

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
121k
#define SUCCESS 0
37
0
#define ERROR -1
38
39
#define RETURN_IF_ERROR(X)  \
40
39.9k
    do {                    \
41
39.9k
        if ((X) == -1) {    \
42
0
            return ERROR;   \
43
0
        }                   \
44
39.9k
    } 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
856
{
116
856
    PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
117
118
856
    c->c_const_cache = PyDict_New();
119
856
    if (!c->c_const_cache) {
120
0
        return ERROR;
121
0
    }
122
123
856
    c->c_stack = PyList_New(0);
124
856
    if (!c->c_stack) {
125
0
        return ERROR;
126
0
    }
127
128
856
    c->c_filename = Py_NewRef(filename);
129
856
    if (!_PyFuture_FromAST(mod, filename, &c->c_future)) {
130
0
        return ERROR;
131
0
    }
132
856
    c->c_module = Py_XNewRef(module);
133
856
    if (!flags) {
134
108
        flags = &local_flags;
135
108
    }
136
856
    int merged = c->c_future.ff_features | flags->cf_flags;
137
856
    c->c_future.ff_features = merged;
138
856
    flags->cf_flags = merged;
139
856
    c->c_flags = *flags;
140
856
    c->c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
141
856
    c->c_save_nested_seqs = false;
142
143
856
    if (!_PyAST_Preprocess(mod, arena, filename, c->c_optimize, merged,
144
856
                           0, 1, module))
145
0
    {
146
0
        return ERROR;
147
0
    }
148
856
    c->c_st = _PySymtable_Build(mod, filename, &c->c_future);
149
856
    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
856
    return SUCCESS;
156
856
}
157
158
static void
159
compiler_free(compiler *c)
160
856
{
161
856
    if (c->c_st) {
162
856
        _PySymtable_Free(c->c_st);
163
856
    }
164
856
    Py_XDECREF(c->c_filename);
165
856
    Py_XDECREF(c->c_module);
166
856
    Py_XDECREF(c->c_const_cache);
167
856
    Py_XDECREF(c->c_stack);
168
856
    PyMem_Free(c);
169
856
}
170
171
static compiler*
172
new_compiler(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
173
             int optimize, PyArena *arena, PyObject *module)
174
856
{
175
856
    compiler *c = PyMem_Calloc(1, sizeof(compiler));
176
856
    if (c == NULL) {
177
0
        return NULL;
178
0
    }
179
856
    if (compiler_setup(c, mod, filename, pflags, optimize, arena, module) < 0) {
180
0
        compiler_free(c);
181
0
        return NULL;
182
0
    }
183
856
    return c;
184
856
}
185
186
static void
187
compiler_unit_free(struct compiler_unit *u)
188
5.64k
{
189
5.64k
    Py_CLEAR(u->u_instr_sequence);
190
5.64k
    Py_CLEAR(u->u_stashed_instr_sequence);
191
5.64k
    Py_CLEAR(u->u_ste);
192
5.64k
    Py_CLEAR(u->u_metadata.u_name);
193
5.64k
    Py_CLEAR(u->u_metadata.u_qualname);
194
5.64k
    Py_CLEAR(u->u_metadata.u_consts);
195
5.64k
    Py_CLEAR(u->u_metadata.u_names);
196
5.64k
    Py_CLEAR(u->u_metadata.u_varnames);
197
5.64k
    Py_CLEAR(u->u_metadata.u_freevars);
198
5.64k
    Py_CLEAR(u->u_metadata.u_cellvars);
199
5.64k
    Py_CLEAR(u->u_metadata.u_fasthidden);
200
5.64k
    Py_CLEAR(u->u_private);
201
5.64k
    Py_CLEAR(u->u_static_attributes);
202
5.64k
    Py_CLEAR(u->u_deferred_annotations);
203
5.64k
    Py_CLEAR(u->u_conditional_annotation_indices);
204
5.64k
    PyMem_Free(u);
205
5.64k
}
206
207
13.9k
#define CAPSULE_NAME "compile.c compiler unit"
208
209
int
210
_PyCompile_MaybeAddStaticAttributeToClass(compiler *c, expr_ty e)
211
13.7k
{
212
13.7k
    assert(e->kind == Attribute_kind);
213
13.7k
    expr_ty attr_value = e->v.Attribute.value;
214
13.7k
    if (attr_value->kind != Name_kind ||
215
13.1k
        e->v.Attribute.ctx != Store ||
216
1.34k
        !_PyUnicode_EqualToASCIIString(attr_value->v.Name.id, "self"))
217
12.6k
    {
218
12.6k
        return SUCCESS;
219
12.6k
    }
220
1.15k
    Py_ssize_t stack_size = PyList_GET_SIZE(c->c_stack);
221
1.50k
    for (Py_ssize_t i = stack_size - 1; i >= 0; i--) {
222
1.33k
        PyObject *capsule = PyList_GET_ITEM(c->c_stack, i);
223
1.33k
        struct compiler_unit *u = (struct compiler_unit *)PyCapsule_GetPointer(
224
1.33k
                                                              capsule, CAPSULE_NAME);
225
1.33k
        assert(u);
226
1.33k
        if (u->u_scope_type == COMPILE_SCOPE_CLASS) {
227
981
            assert(u->u_static_attributes);
228
981
            RETURN_IF_ERROR(PySet_Add(u->u_static_attributes, e->v.Attribute.attr));
229
981
            break;
230
981
        }
231
1.33k
    }
232
1.15k
    return SUCCESS;
233
1.15k
}
234
235
static int
236
compiler_set_qualname(compiler *c)
237
4.78k
{
238
4.78k
    Py_ssize_t stack_size;
239
4.78k
    struct compiler_unit *u = c->u;
240
4.78k
    PyObject *name, *base;
241
242
4.78k
    base = NULL;
243
4.78k
    stack_size = PyList_GET_SIZE(c->c_stack);
244
4.78k
    assert(stack_size >= 1);
245
4.78k
    if (stack_size > 1) {
246
3.00k
        int scope, force_global = 0;
247
3.00k
        struct compiler_unit *parent;
248
3.00k
        PyObject *mangled, *capsule;
249
250
3.00k
        capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
251
3.00k
        parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
252
3.00k
        assert(parent);
253
3.00k
        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.00k
        if (u->u_scope_type == COMPILE_SCOPE_FUNCTION
268
251
            || u->u_scope_type == COMPILE_SCOPE_ASYNC_FUNCTION
269
2.87k
            || u->u_scope_type == COMPILE_SCOPE_CLASS) {
270
2.87k
            assert(u->u_metadata.u_name);
271
2.87k
            mangled = _Py_Mangle(parent->u_private, u->u_metadata.u_name);
272
2.87k
            if (!mangled) {
273
0
                return ERROR;
274
0
            }
275
276
2.87k
            scope = _PyST_GetScope(parent->u_ste, mangled);
277
2.87k
            Py_DECREF(mangled);
278
2.87k
            RETURN_IF_ERROR(scope);
279
2.87k
            assert(scope != GLOBAL_IMPLICIT);
280
2.87k
            if (scope == GLOBAL_EXPLICIT)
281
0
                force_global = 1;
282
2.87k
        }
283
284
3.00k
        if (!force_global) {
285
3.00k
            if (parent->u_scope_type == COMPILE_SCOPE_FUNCTION
286
1.85k
                || parent->u_scope_type == COMPILE_SCOPE_ASYNC_FUNCTION
287
1.83k
                || 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.83k
            else {
297
1.83k
                base = Py_NewRef(parent->u_metadata.u_qualname);
298
1.83k
            }
299
3.00k
        }
300
3.00k
        if (u->u_ste->ste_function_name != NULL) {
301
21
            PyObject *tmp = base;
302
21
            base = PyUnicode_FromFormat("%U.%U",
303
21
                base,
304
21
                u->u_ste->ste_function_name);
305
21
            Py_DECREF(tmp);
306
21
            if (base == NULL) {
307
0
                return ERROR;
308
0
            }
309
21
        }
310
3.00k
    }
311
1.78k
    else if (u->u_ste->ste_function_name != NULL) {
312
19
        base = Py_NewRef(u->u_ste->ste_function_name);
313
19
    }
314
315
4.78k
    if (base != NULL) {
316
3.02k
        name = PyUnicode_Concat(base, _Py_LATIN1_CHR('.'));
317
3.02k
        Py_DECREF(base);
318
3.02k
        if (name == NULL) {
319
0
            return ERROR;
320
0
        }
321
3.02k
        PyUnicode_Append(&name, u->u_metadata.u_name);
322
3.02k
        if (name == NULL) {
323
0
            return ERROR;
324
0
        }
325
3.02k
    }
326
1.76k
    else {
327
1.76k
        name = Py_NewRef(u->u_metadata.u_name);
328
1.76k
    }
329
4.78k
    u->u_metadata.u_qualname = name;
330
331
4.78k
    return SUCCESS;
332
4.78k
}
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
83.6k
{
340
83.6k
    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
83.6k
    if (o == Py_None || o == Py_Ellipsis) {
344
9.92k
        return o;
345
9.92k
    }
346
347
73.6k
    PyObject *key = _PyCode_ConstantKey(o);
348
73.6k
    if (key == NULL) {
349
0
        return NULL;
350
0
    }
351
352
73.6k
    PyObject *t;
353
73.6k
    int res = PyDict_SetDefaultRef(const_cache, key, key, &t);
354
73.6k
    if (res != 0) {
355
        // o was not inserted into const_cache. t is either the existing value
356
        // or NULL (on error).
357
26.3k
        Py_DECREF(key);
358
26.3k
        return t;
359
26.3k
    }
360
47.3k
    Py_DECREF(t);
361
362
47.3k
    if (!recursive) {
363
25.1k
        return key;
364
25.1k
    }
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
22.2k
    if (PyTuple_CheckExact(o)) {
370
1.00k
        Py_ssize_t len = PyTuple_GET_SIZE(o);
371
3.41k
        for (Py_ssize_t i = 0; i < len; i++) {
372
2.41k
            PyObject *item = PyTuple_GET_ITEM(o, i);
373
2.41k
            PyObject *u = const_cache_insert(const_cache, item, recursive);
374
2.41k
            if (u == NULL) {
375
0
                Py_DECREF(key);
376
0
                return NULL;
377
0
            }
378
379
            // See _PyCode_ConstantKey()
380
2.41k
            PyObject *v;  // borrowed
381
2.41k
            if (PyTuple_CheckExact(u)) {
382
0
                v = PyTuple_GET_ITEM(u, 1);
383
0
            }
384
2.41k
            else {
385
2.41k
                v = u;
386
2.41k
            }
387
2.41k
            if (v != item) {
388
112
                PyTuple_SET_ITEM(o, i, Py_NewRef(v));
389
112
                Py_DECREF(item);
390
112
            }
391
392
2.41k
            Py_DECREF(u);
393
2.41k
        }
394
1.00k
    }
395
21.1k
    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
22.2k
    return key;
447
22.2k
}
448
449
static PyObject*
450
merge_consts_recursive(PyObject *const_cache, PyObject *o)
451
46.1k
{
452
46.1k
    return const_cache_insert(const_cache, o, true);
453
46.1k
}
454
455
Py_ssize_t
456
_PyCompile_DictAddObj(PyObject *dict, PyObject *o)
457
125k
{
458
125k
    PyObject *v;
459
125k
    Py_ssize_t arg;
460
461
125k
    if (PyDict_GetItemRef(dict, o, &v) < 0) {
462
0
        return ERROR;
463
0
    }
464
125k
    if (!v) {
465
65.6k
        arg = PyDict_GET_SIZE(dict);
466
65.6k
        v = PyLong_FromSsize_t(arg);
467
65.6k
        if (!v) {
468
0
            return ERROR;
469
0
        }
470
65.6k
        if (PyDict_SetItem(dict, o, v) < 0) {
471
0
            Py_DECREF(v);
472
0
            return ERROR;
473
0
        }
474
65.6k
    }
475
59.7k
    else
476
59.7k
        arg = PyLong_AsLong(v);
477
125k
    Py_DECREF(v);
478
125k
    return arg;
479
125k
}
480
481
Py_ssize_t
482
_PyCompile_AddConst(compiler *c, PyObject *o)
483
46.1k
{
484
46.1k
    PyObject *key = merge_consts_recursive(c->c_const_cache, o);
485
46.1k
    if (key == NULL) {
486
0
        return ERROR;
487
0
    }
488
489
46.1k
    Py_ssize_t arg = _PyCompile_DictAddObj(c->u->u_metadata.u_consts, key);
490
46.1k
    Py_DECREF(key);
491
46.1k
    return arg;
492
46.1k
}
493
494
static PyObject *
495
list2dict(PyObject *list)
496
5.64k
{
497
5.64k
    Py_ssize_t i, n;
498
5.64k
    PyObject *v, *k;
499
5.64k
    PyObject *dict = PyDict_New();
500
5.64k
    if (!dict) return NULL;
501
502
5.64k
    n = PyList_Size(list);
503
16.9k
    for (i = 0; i < n; i++) {
504
11.3k
        v = PyLong_FromSsize_t(i);
505
11.3k
        if (!v) {
506
0
            Py_DECREF(dict);
507
0
            return NULL;
508
0
        }
509
11.3k
        k = PyList_GET_ITEM(list, i);
510
11.3k
        if (PyDict_SetItem(dict, k, v) < 0) {
511
0
            Py_DECREF(v);
512
0
            Py_DECREF(dict);
513
0
            return NULL;
514
0
        }
515
11.3k
        Py_DECREF(v);
516
11.3k
    }
517
5.64k
    return dict;
518
5.64k
}
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
11.2k
{
531
11.2k
    Py_ssize_t i = offset, num_keys, key_i;
532
11.2k
    PyObject *k, *v, *dest = PyDict_New();
533
11.2k
    PyObject *sorted_keys;
534
535
11.2k
    assert(offset >= 0);
536
11.2k
    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
11.2k
    sorted_keys = PyDict_Keys(src);
545
11.2k
    if (sorted_keys == NULL) {
546
0
        Py_DECREF(dest);
547
0
        return NULL;
548
0
    }
549
11.2k
    if (PyList_Sort(sorted_keys) != 0) {
550
0
        Py_DECREF(sorted_keys);
551
0
        Py_DECREF(dest);
552
0
        return NULL;
553
0
    }
554
11.2k
    num_keys = PyList_GET_SIZE(sorted_keys);
555
556
66.2k
    for (key_i = 0; key_i < num_keys; key_i++) {
557
54.9k
        k = PyList_GET_ITEM(sorted_keys, key_i);
558
54.9k
        v = PyDict_GetItemWithError(src, k);
559
54.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
54.9k
        long vi = PyLong_AsLong(v);
568
54.9k
        if (vi == -1 && PyErr_Occurred()) {
569
0
            Py_DECREF(sorted_keys);
570
0
            Py_DECREF(dest);
571
0
            return NULL;
572
0
        }
573
54.9k
        if (SYMBOL_TO_SCOPE(vi) == scope_type || vi & flag) {
574
1.94k
            PyObject *item = PyLong_FromSsize_t(i);
575
1.94k
            if (item == NULL) {
576
0
                Py_DECREF(sorted_keys);
577
0
                Py_DECREF(dest);
578
0
                return NULL;
579
0
            }
580
1.94k
            i++;
581
1.94k
            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.94k
            Py_DECREF(item);
588
1.94k
        }
589
54.9k
    }
590
11.2k
    Py_DECREF(sorted_keys);
591
11.2k
    return dest;
592
11.2k
}
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.64k
{
599
5.64k
    struct compiler_unit *u;
600
5.64k
    u = (struct compiler_unit *)PyMem_Calloc(1, sizeof(struct compiler_unit));
601
5.64k
    if (!u) {
602
0
        PyErr_NoMemory();
603
0
        return ERROR;
604
0
    }
605
5.64k
    u->u_scope_type = scope_type;
606
5.64k
    if (umd != NULL) {
607
4.04k
        u->u_metadata = *umd;
608
4.04k
    }
609
1.59k
    else {
610
1.59k
        u->u_metadata.u_argcount = 0;
611
1.59k
        u->u_metadata.u_posonlyargcount = 0;
612
1.59k
        u->u_metadata.u_kwonlyargcount = 0;
613
1.59k
    }
614
5.64k
    u->u_ste = _PySymtable_Lookup(c->c_st, key);
615
5.64k
    if (!u->u_ste) {
616
0
        compiler_unit_free(u);
617
0
        return ERROR;
618
0
    }
619
5.64k
    u->u_metadata.u_name = Py_NewRef(name);
620
5.64k
    u->u_metadata.u_varnames = list2dict(u->u_ste->ste_varnames);
621
5.64k
    if (!u->u_metadata.u_varnames) {
622
0
        compiler_unit_free(u);
623
0
        return ERROR;
624
0
    }
625
5.64k
    u->u_metadata.u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, DEF_COMP_CELL, 0);
626
5.64k
    if (!u->u_metadata.u_cellvars) {
627
0
        compiler_unit_free(u);
628
0
        return ERROR;
629
0
    }
630
5.64k
    if (u->u_ste->ste_needs_class_closure) {
631
        /* Cook up an implicit __class__ cell. */
632
36
        Py_ssize_t res;
633
36
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS);
634
36
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__class__));
635
36
        if (res < 0) {
636
0
            compiler_unit_free(u);
637
0
            return ERROR;
638
0
        }
639
36
    }
640
5.64k
    if (u->u_ste->ste_needs_classdict) {
641
        /* Cook up an implicit __classdict__ cell. */
642
406
        Py_ssize_t res;
643
406
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS);
644
406
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__classdict__));
645
406
        if (res < 0) {
646
0
            compiler_unit_free(u);
647
0
            return ERROR;
648
0
        }
649
406
    }
650
5.64k
    if (u->u_ste->ste_has_conditional_annotations) {
651
        /* Cook up an implicit __conditional_annotations__ cell */
652
0
        Py_ssize_t res;
653
0
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS || u->u_scope_type == COMPILE_SCOPE_MODULE);
654
0
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__conditional_annotations__));
655
0
        if (res < 0) {
656
0
            compiler_unit_free(u);
657
0
            return ERROR;
658
0
        }
659
0
    }
660
661
5.64k
    u->u_metadata.u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
662
5.64k
                               PyDict_GET_SIZE(u->u_metadata.u_cellvars));
663
5.64k
    if (!u->u_metadata.u_freevars) {
664
0
        compiler_unit_free(u);
665
0
        return ERROR;
666
0
    }
667
668
5.64k
    u->u_metadata.u_fasthidden = PyDict_New();
669
5.64k
    if (!u->u_metadata.u_fasthidden) {
670
0
        compiler_unit_free(u);
671
0
        return ERROR;
672
0
    }
673
674
5.64k
    u->u_nfblocks = 0;
675
5.64k
    u->u_in_inlined_comp = 0;
676
5.64k
    u->u_metadata.u_firstlineno = lineno;
677
5.64k
    u->u_metadata.u_consts = PyDict_New();
678
5.64k
    if (!u->u_metadata.u_consts) {
679
0
        compiler_unit_free(u);
680
0
        return ERROR;
681
0
    }
682
5.64k
    u->u_metadata.u_names = PyDict_New();
683
5.64k
    if (!u->u_metadata.u_names) {
684
0
        compiler_unit_free(u);
685
0
        return ERROR;
686
0
    }
687
688
5.64k
    u->u_deferred_annotations = NULL;
689
5.64k
    u->u_conditional_annotation_indices = NULL;
690
5.64k
    u->u_next_conditional_annotation_index = 0;
691
5.64k
    if (scope_type == COMPILE_SCOPE_CLASS) {
692
741
        u->u_static_attributes = PySet_New(0);
693
741
        if (!u->u_static_attributes) {
694
0
            compiler_unit_free(u);
695
0
            return ERROR;
696
0
        }
697
741
    }
698
4.90k
    else {
699
4.90k
        u->u_static_attributes = NULL;
700
4.90k
    }
701
702
5.64k
    u->u_instr_sequence = (instr_sequence*)_PyInstructionSequence_New();
703
5.64k
    if (!u->u_instr_sequence) {
704
0
        compiler_unit_free(u);
705
0
        return ERROR;
706
0
    }
707
5.64k
    u->u_stashed_instr_sequence = NULL;
708
709
    /* Push the old compiler_unit on the stack. */
710
5.64k
    if (c->u) {
711
4.78k
        PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
712
4.78k
        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.78k
        Py_DECREF(capsule);
718
4.78k
        if (private == NULL) {
719
4.04k
            private = c->u->u_private;
720
4.04k
        }
721
4.78k
    }
722
723
5.64k
    u->u_private = Py_XNewRef(private);
724
725
5.64k
    c->u = u;
726
5.64k
    if (scope_type != COMPILE_SCOPE_MODULE) {
727
4.78k
        RETURN_IF_ERROR(compiler_set_qualname(c));
728
4.78k
    }
729
5.64k
    return SUCCESS;
730
5.64k
}
731
732
void
733
_PyCompile_ExitScope(compiler *c)
734
5.64k
{
735
    // Don't call PySequence_DelItem() with an exception raised
736
5.64k
    PyObject *exc = PyErr_GetRaisedException();
737
738
5.64k
    instr_sequence *nested_seq = NULL;
739
5.64k
    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.64k
    compiler_unit_free(c->u);
744
    /* Restore c->u to the parent unit. */
745
5.64k
    Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
746
5.64k
    if (n >= 0) {
747
4.78k
        PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
748
4.78k
        c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
749
4.78k
        assert(c->u);
750
        /* we are deleting from a list so this really shouldn't fail */
751
4.78k
        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.78k
        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.78k
    }
762
856
    else {
763
856
        c->u = NULL;
764
856
    }
765
5.64k
    Py_XDECREF(nested_seq);
766
767
5.64k
    PyErr_SetRaisedException(exc);
768
5.64k
}
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.56k
{
779
2.56k
    fblockinfo *f;
780
2.56k
    if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
781
0
        return _PyCompile_Error(c, loc, "too many statically nested blocks");
782
0
    }
783
2.56k
    f = &c->u->u_fblock[c->u->u_nfblocks++];
784
2.56k
    f->fb_type = t;
785
2.56k
    f->fb_block = block_label;
786
2.56k
    f->fb_loc = loc;
787
2.56k
    f->fb_exit = exit;
788
2.56k
    f->fb_datum = datum;
789
2.56k
    if (t == COMPILE_FBLOCK_FINALLY_END) {
790
89
        c->c_disable_warning++;
791
89
    }
792
2.56k
    return SUCCESS;
793
2.56k
}
794
795
void
796
_PyCompile_PopFBlock(compiler *c, fblocktype t, jump_target_label block_label)
797
2.56k
{
798
2.56k
    struct compiler_unit *u = c->u;
799
2.56k
    assert(u->u_nfblocks > 0);
800
2.56k
    u->u_nfblocks--;
801
2.56k
    assert(u->u_fblock[u->u_nfblocks].fb_type == t);
802
2.56k
    assert(SAME_JUMP_TARGET_LABEL(u->u_fblock[u->u_nfblocks].fb_block, block_label));
803
2.56k
    if (t == COMPILE_FBLOCK_FINALLY_END) {
804
89
        c->c_disable_warning--;
805
89
    }
806
2.56k
}
807
808
fblockinfo *
809
_PyCompile_TopFBlock(compiler *c)
810
3.68k
{
811
3.68k
    if (c->u->u_nfblocks == 0) {
812
3.04k
        return NULL;
813
3.04k
    }
814
643
    return &c->u->u_fblock[c->u->u_nfblocks - 1];
815
3.68k
}
816
817
bool
818
_PyCompile_InExceptionHandler(compiler *c)
819
898
{
820
903
    for (Py_ssize_t i = 0; i < c->u->u_nfblocks; i++) {
821
22
        fblockinfo *block = &c->u->u_fblock[i];
822
22
        switch (block->fb_type) {
823
14
            case COMPILE_FBLOCK_TRY_EXCEPT:
824
14
            case COMPILE_FBLOCK_FINALLY_TRY:
825
14
            case COMPILE_FBLOCK_FINALLY_END:
826
17
            case COMPILE_FBLOCK_EXCEPTION_HANDLER:
827
17
            case COMPILE_FBLOCK_EXCEPTION_GROUP_HANDLER:
828
17
            case COMPILE_FBLOCK_HANDLER_CLEANUP:
829
17
                return true;
830
5
            default:
831
5
                break;
832
22
        }
833
22
    }
834
881
    return false;
835
898
}
836
837
void
838
_PyCompile_DeferredAnnotations(compiler *c,
839
                               PyObject **deferred_annotations,
840
                               PyObject **conditional_annotation_indices)
841
1.34k
{
842
1.34k
    *deferred_annotations = Py_XNewRef(c->u->u_deferred_annotations);
843
1.34k
    *conditional_annotation_indices = Py_XNewRef(c->u->u_conditional_annotation_indices);
844
1.34k
}
845
846
static location
847
start_location(asdl_stmt_seq *stmts)
848
605
{
849
605
    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
603
        stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
856
603
        return SRC_LOCATION_FROM_AST(st);
857
603
    }
858
2
    return (const _Py_SourceLocation){1, 1, 0, 0};
859
605
}
860
861
static int
862
compiler_codegen(compiler *c, mod_ty mod)
863
856
{
864
856
    RETURN_IF_ERROR(_PyCodegen_EnterAnonymousScope(c, mod));
865
856
    assert(c->u->u_scope_type == COMPILE_SCOPE_MODULE);
866
856
    switch (mod->kind) {
867
605
    case Module_kind: {
868
605
        asdl_stmt_seq *stmts = mod->v.Module.body;
869
605
        RETURN_IF_ERROR(_PyCodegen_Module(c, start_location(stmts), stmts, false));
870
605
        break;
871
605
    }
872
605
    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
251
    case Expression_kind: {
879
251
        RETURN_IF_ERROR(_PyCodegen_Expression(c, mod->v.Expression.body));
880
251
        break;
881
251
    }
882
251
    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
251
    }}
888
856
    return SUCCESS;
889
856
}
890
891
static PyCodeObject *
892
compiler_mod(compiler *c, mod_ty mod)
893
856
{
894
856
    PyCodeObject *co = NULL;
895
856
    int addNone = mod->kind != Expression_kind;
896
856
    if (compiler_codegen(c, mod) < 0) {
897
0
        goto finally;
898
0
    }
899
856
    co = _PyCompile_OptimizeAndAssemble(c, addNone);
900
856
finally:
901
856
    _PyCompile_ExitScope(c);
902
856
    return co;
903
856
}
904
905
int
906
_PyCompile_GetRefType(compiler *c, PyObject *name)
907
1.21k
{
908
1.21k
    if (c->u->u_scope_type == COMPILE_SCOPE_CLASS &&
909
101
        (_PyUnicode_EqualToASCIIString(name, "__class__") ||
910
29
         _PyUnicode_EqualToASCIIString(name, "__classdict__") ||
911
96
         _PyUnicode_EqualToASCIIString(name, "__conditional_annotations__"))) {
912
96
        return CELL;
913
96
    }
914
1.11k
    PySTEntryObject *ste = c->u->u_ste;
915
1.11k
    int scope = _PyST_GetScope(ste, name);
916
1.11k
    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
1.11k
    return scope;
929
1.11k
}
930
931
static int
932
dict_lookup_arg(PyObject *dict, PyObject *name)
933
1.60k
{
934
1.60k
    PyObject *v = PyDict_GetItemWithError(dict, name);
935
1.60k
    if (v == NULL) {
936
0
        return ERROR;
937
0
    }
938
1.60k
    return PyLong_AsLong(v);
939
1.60k
}
940
941
int
942
_PyCompile_LookupCellvar(compiler *c, PyObject *name)
943
442
{
944
442
    assert(c->u->u_metadata.u_cellvars);
945
442
    return dict_lookup_arg(c->u->u_metadata.u_cellvars, name);
946
442
}
947
948
int
949
_PyCompile_LookupArg(compiler *c, PyCodeObject *co, PyObject *name)
950
1.16k
{
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
1.16k
    int reftype = _PyCompile_GetRefType(c, name);
958
1.16k
    if (reftype == -1) {
959
0
        return ERROR;
960
0
    }
961
1.16k
    int arg;
962
1.16k
    if (reftype == CELL) {
963
1.15k
        arg = dict_lookup_arg(c->u->u_metadata.u_cellvars, name);
964
1.15k
    }
965
9
    else {
966
9
        arg = dict_lookup_arg(c->u->u_metadata.u_freevars, name);
967
9
    }
968
1.16k
    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
1.16k
    return arg;
985
1.16k
}
986
987
PyObject *
988
_PyCompile_StaticAttributesAsTuple(compiler *c)
989
741
{
990
741
    assert(c->u->u_static_attributes);
991
741
    PyObject *static_attributes_unsorted = PySequence_List(c->u->u_static_attributes);
992
741
    if (static_attributes_unsorted == NULL) {
993
0
        return NULL;
994
0
    }
995
741
    if (PyList_Sort(static_attributes_unsorted) != 0) {
996
0
        Py_DECREF(static_attributes_unsorted);
997
0
        return NULL;
998
0
    }
999
741
    PyObject *static_attributes = PySequence_Tuple(static_attributes_unsorted);
1000
741
    Py_DECREF(static_attributes_unsorted);
1001
741
    return static_attributes;
1002
741
}
1003
1004
int
1005
_PyCompile_ResolveNameop(compiler *c, PyObject *mangled, int scope,
1006
                          _PyCompile_optype *optype, Py_ssize_t *arg)
1007
57.7k
{
1008
57.7k
    PyObject *dict = c->u->u_metadata.u_names;
1009
57.7k
    *optype = COMPILE_OP_NAME;
1010
1011
57.7k
    assert(scope >= 0);
1012
57.7k
    switch (scope) {
1013
2.38k
    case FREE:
1014
2.38k
        dict = c->u->u_metadata.u_freevars;
1015
2.38k
        *optype = COMPILE_OP_DEREF;
1016
2.38k
        break;
1017
648
    case CELL:
1018
648
        dict = c->u->u_metadata.u_cellvars;
1019
648
        *optype = COMPILE_OP_DEREF;
1020
648
        break;
1021
41.9k
    case LOCAL:
1022
41.9k
        if (_PyST_IsFunctionLike(c->u->u_ste)) {
1023
35.2k
            *optype = COMPILE_OP_FAST;
1024
35.2k
        }
1025
6.69k
        else {
1026
6.69k
            PyObject *item;
1027
6.69k
            RETURN_IF_ERROR(PyDict_GetItemRef(c->u->u_metadata.u_fasthidden, mangled,
1028
6.69k
                                              &item));
1029
6.69k
            if (item == Py_True) {
1030
10
                *optype = COMPILE_OP_FAST;
1031
10
            }
1032
6.69k
            Py_XDECREF(item);
1033
6.69k
        }
1034
41.9k
        break;
1035
41.9k
    case GLOBAL_IMPLICIT:
1036
8.35k
        if (_PyST_IsFunctionLike(c->u->u_ste)) {
1037
7.87k
            *optype = COMPILE_OP_GLOBAL;
1038
7.87k
        }
1039
8.35k
        break;
1040
28
    case GLOBAL_EXPLICIT:
1041
28
        *optype = COMPILE_OP_GLOBAL;
1042
28
        break;
1043
4.38k
    default:
1044
        /* scope can be 0 */
1045
4.38k
        break;
1046
57.7k
    }
1047
57.7k
    if (*optype != COMPILE_OP_FAST) {
1048
22.4k
        *arg = _PyCompile_DictAddObj(dict, mangled);
1049
22.4k
        RETURN_IF_ERROR(*arg);
1050
22.4k
    }
1051
57.7k
    return SUCCESS;
1052
57.7k
}
1053
1054
int
1055
_PyCompile_TweakInlinedComprehensionScopes(compiler *c, location loc,
1056
                                            PySTEntryObject *entry,
1057
                                            _PyCompile_InlinedComprehensionState *state)
1058
55
{
1059
55
    int in_class_block = (c->u->u_ste->ste_type == ClassBlock) && !c->u->u_in_inlined_comp;
1060
55
    c->u->u_in_inlined_comp++;
1061
1062
55
    PyObject *k, *v;
1063
55
    Py_ssize_t pos = 0;
1064
226
    while (PyDict_Next(entry->ste_symbols, &pos, &k, &v)) {
1065
171
        long symbol = PyLong_AsLong(v);
1066
171
        assert(symbol >= 0 || PyErr_Occurred());
1067
171
        RETURN_IF_ERROR(symbol);
1068
171
        long scope = SYMBOL_TO_SCOPE(symbol);
1069
1070
171
        long outsymbol = _PyST_GetSymbol(c->u->u_ste, k);
1071
171
        RETURN_IF_ERROR(outsymbol);
1072
171
        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
171
        if ((scope != outsc && scope != FREE && !(scope == CELL && outsc == FREE))
1083
116
                || in_class_block) {
1084
56
            if (state->temp_symbols == NULL) {
1085
55
                state->temp_symbols = PyDict_New();
1086
55
                if (state->temp_symbols == NULL) {
1087
0
                    return ERROR;
1088
0
                }
1089
55
            }
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
56
            if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v) < 0) {
1094
0
                return ERROR;
1095
0
            }
1096
56
            PyObject *outv = PyLong_FromLong(outsymbol);
1097
56
            if (outv == NULL) {
1098
0
                return ERROR;
1099
0
            }
1100
56
            int res = PyDict_SetItem(state->temp_symbols, k, outv);
1101
56
            Py_DECREF(outv);
1102
56
            RETURN_IF_ERROR(res);
1103
56
        }
1104
        // locals handling for names bound in comprehension (DEF_LOCAL |
1105
        // DEF_NONLOCAL occurs in assignment expression to nonlocal)
1106
171
        if ((symbol & DEF_LOCAL && !(symbol & DEF_NONLOCAL)) || in_class_block) {
1107
66
            if (!_PyST_IsFunctionLike(c->u->u_ste)) {
1108
                // non-function scope: override this name to use fast locals
1109
5
                PyObject *orig;
1110
5
                if (PyDict_GetItemRef(c->u->u_metadata.u_fasthidden, k, &orig) < 0) {
1111
0
                    return ERROR;
1112
0
                }
1113
5
                assert(orig == NULL || orig == Py_True || orig == Py_False);
1114
5
                if (orig != Py_True) {
1115
5
                    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
5
                    if (state->fast_hidden == NULL) {
1120
4
                        state->fast_hidden = PySet_New(NULL);
1121
4
                        if (state->fast_hidden == NULL) {
1122
0
                            Py_XDECREF(orig);
1123
0
                            return ERROR;
1124
0
                        }
1125
4
                    }
1126
5
                    if (PySet_Add(state->fast_hidden, k) < 0) {
1127
0
                        Py_XDECREF(orig);
1128
0
                        return ERROR;
1129
0
                    }
1130
5
                }
1131
5
                Py_XDECREF(orig);
1132
5
            }
1133
66
        }
1134
171
    }
1135
55
    return SUCCESS;
1136
55
}
1137
1138
int
1139
_PyCompile_RevertInlinedComprehensionScopes(compiler *c, location loc,
1140
                                             _PyCompile_InlinedComprehensionState *state)
1141
55
{
1142
55
    c->u->u_in_inlined_comp--;
1143
55
    if (state->temp_symbols) {
1144
55
        PyObject *k, *v;
1145
55
        Py_ssize_t pos = 0;
1146
111
        while (PyDict_Next(state->temp_symbols, &pos, &k, &v)) {
1147
56
            if (PyDict_SetItem(c->u->u_ste->ste_symbols, k, v)) {
1148
0
                return ERROR;
1149
0
            }
1150
56
        }
1151
55
        Py_CLEAR(state->temp_symbols);
1152
55
    }
1153
55
    if (state->fast_hidden) {
1154
9
        while (PySet_Size(state->fast_hidden) > 0) {
1155
5
            PyObject *k = PySet_Pop(state->fast_hidden);
1156
5
            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
5
            if (PyDict_SetItem(c->u->u_metadata.u_fasthidden, k, Py_False)) {
1162
0
                Py_DECREF(k);
1163
0
                return ERROR;
1164
0
            }
1165
5
            Py_DECREF(k);
1166
5
        }
1167
4
        Py_CLEAR(state->fast_hidden);
1168
4
    }
1169
55
    return SUCCESS;
1170
55
}
1171
1172
void
1173
_PyCompile_EnterConditionalBlock(struct _PyCompiler *c)
1174
4.17k
{
1175
4.17k
    c->u->u_in_conditional_block++;
1176
4.17k
}
1177
1178
void
1179
_PyCompile_LeaveConditionalBlock(struct _PyCompiler *c)
1180
4.17k
{
1181
4.17k
    assert(c->u->u_in_conditional_block > 0);
1182
4.17k
    c->u->u_in_conditional_block--;
1183
4.17k
}
1184
1185
int
1186
_PyCompile_AddDeferredAnnotation(compiler *c, stmt_ty s,
1187
                                 PyObject **conditional_annotation_index)
1188
12
{
1189
12
    if (c->u->u_deferred_annotations == NULL) {
1190
6
        c->u->u_deferred_annotations = PyList_New(0);
1191
6
        if (c->u->u_deferred_annotations == NULL) {
1192
0
            return ERROR;
1193
0
        }
1194
6
    }
1195
12
    if (c->u->u_conditional_annotation_indices == NULL) {
1196
6
        c->u->u_conditional_annotation_indices = PyList_New(0);
1197
6
        if (c->u->u_conditional_annotation_indices == NULL) {
1198
0
            return ERROR;
1199
0
        }
1200
6
    }
1201
12
    PyObject *ptr = PyLong_FromVoidPtr((void *)s);
1202
12
    if (ptr == NULL) {
1203
0
        return ERROR;
1204
0
    }
1205
12
    if (PyList_Append(c->u->u_deferred_annotations, ptr) < 0) {
1206
0
        Py_DECREF(ptr);
1207
0
        return ERROR;
1208
0
    }
1209
12
    Py_DECREF(ptr);
1210
12
    PyObject *index;
1211
12
    if (c->u->u_scope_type == COMPILE_SCOPE_MODULE || c->u->u_in_conditional_block) {
1212
0
        index = PyLong_FromLong(c->u->u_next_conditional_annotation_index);
1213
0
        if (index == NULL) {
1214
0
            return ERROR;
1215
0
        }
1216
0
        *conditional_annotation_index = Py_NewRef(index);
1217
0
        c->u->u_next_conditional_annotation_index++;
1218
0
    }
1219
12
    else {
1220
12
        index = PyLong_FromLong(-1);
1221
12
        if (index == NULL) {
1222
0
            return ERROR;
1223
0
        }
1224
12
    }
1225
12
    int rc = PyList_Append(c->u->u_conditional_annotation_indices, index);
1226
12
    Py_DECREF(index);
1227
12
    RETURN_IF_ERROR(rc);
1228
12
    return SUCCESS;
1229
12
}
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
12
{
1277
12
    return _Py_Mangle(c->u->u_private, name);
1278
12
}
1279
1280
PyObject *
1281
_PyCompile_MaybeMangle(compiler *c, PyObject *name)
1282
79.7k
{
1283
79.7k
    return _Py_MaybeMangle(c->u->u_private, c->u->u_ste, name);
1284
79.7k
}
1285
1286
instr_sequence *
1287
_PyCompile_InstrSequence(compiler *c)
1288
268k
{
1289
268k
    return c->u->u_instr_sequence;
1290
268k
}
1291
1292
int
1293
_PyCompile_StartAnnotationSetup(struct _PyCompiler *c)
1294
0
{
1295
0
    instr_sequence *new_seq = (instr_sequence *)_PyInstructionSequence_New();
1296
0
    if (new_seq == NULL) {
1297
0
        return ERROR;
1298
0
    }
1299
0
    assert(c->u->u_stashed_instr_sequence == NULL);
1300
0
    c->u->u_stashed_instr_sequence = c->u->u_instr_sequence;
1301
0
    c->u->u_instr_sequence = new_seq;
1302
0
    return SUCCESS;
1303
0
}
1304
1305
int
1306
_PyCompile_EndAnnotationSetup(struct _PyCompiler *c)
1307
0
{
1308
0
    assert(c->u->u_stashed_instr_sequence != NULL);
1309
0
    instr_sequence *parent_seq = c->u->u_stashed_instr_sequence;
1310
0
    instr_sequence *anno_seq = c->u->u_instr_sequence;
1311
0
    c->u->u_stashed_instr_sequence = NULL;
1312
0
    c->u->u_instr_sequence = parent_seq;
1313
0
    if (_PyInstructionSequence_SetAnnotationsCode(parent_seq, anno_seq) == ERROR) {
1314
0
        Py_DECREF(anno_seq);
1315
0
        return ERROR;
1316
0
    }
1317
0
    return SUCCESS;
1318
0
}
1319
1320
1321
int
1322
_PyCompile_FutureFeatures(compiler *c)
1323
2.79k
{
1324
2.79k
    return c->c_future.ff_features;
1325
2.79k
}
1326
1327
struct symtable *
1328
_PyCompile_Symtable(compiler *c)
1329
9.17k
{
1330
9.17k
    return c->c_st;
1331
9.17k
}
1332
1333
PySTEntryObject *
1334
_PyCompile_SymtableEntry(compiler *c)
1335
92.5k
{
1336
92.5k
    return c->u->u_ste;
1337
92.5k
}
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
4.16k
{
1348
4.16k
    assert(c->c_stack != NULL);
1349
4.16k
    assert(PyList_CheckExact(c->c_stack));
1350
4.16k
    bool is_nested_scope = PyList_GET_SIZE(c->c_stack) > 0;
1351
4.16k
    return c->c_interactive && !is_nested_scope;
1352
4.16k
}
1353
1354
int
1355
_PyCompile_ScopeType(compiler *c)
1356
938
{
1357
938
    return c->u->u_scope_type;
1358
938
}
1359
1360
int
1361
_PyCompile_IsInInlinedComp(compiler *c)
1362
1.19k
{
1363
1.19k
    return c->u->u_in_inlined_comp;
1364
1.19k
}
1365
1366
PyObject *
1367
_PyCompile_Qualname(compiler *c)
1368
741
{
1369
741
    assert(c->u->u_metadata.u_qualname);
1370
741
    return c->u->u_metadata.u_qualname;
1371
741
}
1372
1373
_PyCompile_CodeUnitMetadata *
1374
_PyCompile_Metadata(compiler *c)
1375
57.1k
{
1376
57.1k
    return &c->u->u_metadata;
1377
57.1k
}
1378
1379
// Merge *obj* with constant cache, without recursion.
1380
int
1381
_PyCompile_ConstCacheMergeOne(PyObject *const_cache, PyObject **obj)
1382
34.9k
{
1383
34.9k
    PyObject *key = const_cache_insert(const_cache, *obj, false);
1384
34.9k
    if (key == NULL) {
1385
0
        return ERROR;
1386
0
    }
1387
34.9k
    if (PyTuple_CheckExact(key)) {
1388
34.8k
        PyObject *item = PyTuple_GET_ITEM(key, 1);
1389
34.8k
        Py_SETREF(*obj, Py_NewRef(item));
1390
34.8k
        Py_DECREF(key);
1391
34.8k
    }
1392
123
    else {
1393
123
        Py_SETREF(*obj, key);
1394
123
    }
1395
34.9k
    return SUCCESS;
1396
34.9k
}
1397
1398
static PyObject *
1399
consts_dict_keys_inorder(PyObject *dict)
1400
5.64k
{
1401
5.64k
    PyObject *consts, *k, *v;
1402
5.64k
    Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
1403
1404
5.64k
    consts = PyList_New(size);   /* PyCode_Optimize() requires a list */
1405
5.64k
    if (consts == NULL)
1406
0
        return NULL;
1407
37.9k
    while (PyDict_Next(dict, &pos, &k, &v)) {
1408
32.2k
        assert(PyLong_CheckExact(v));
1409
32.2k
        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
32.2k
        if (PyTuple_CheckExact(k)) {
1414
2.57k
            k = PyTuple_GET_ITEM(k, 1);
1415
2.57k
        }
1416
32.2k
        assert(i < size);
1417
32.2k
        assert(i >= 0);
1418
32.2k
        PyList_SET_ITEM(consts, i, Py_NewRef(k));
1419
32.2k
    }
1420
5.64k
    return consts;
1421
5.64k
}
1422
1423
static int
1424
compute_code_flags(compiler *c)
1425
5.64k
{
1426
5.64k
    PySTEntryObject *ste = c->u->u_ste;
1427
5.64k
    int flags = 0;
1428
5.64k
    if (_PyST_IsFunctionLike(ste)) {
1429
4.04k
        flags |= CO_NEWLOCALS | CO_OPTIMIZED;
1430
4.04k
        if (ste->ste_nested)
1431
1.17k
            flags |= CO_NESTED;
1432
4.04k
        if (ste->ste_generator && !ste->ste_coroutine)
1433
115
            flags |= CO_GENERATOR;
1434
4.04k
        if (ste->ste_generator && ste->ste_coroutine)
1435
0
            flags |= CO_ASYNC_GENERATOR;
1436
4.04k
        if (ste->ste_varargs)
1437
117
            flags |= CO_VARARGS;
1438
4.04k
        if (ste->ste_varkeywords)
1439
106
            flags |= CO_VARKEYWORDS;
1440
4.04k
        if (ste->ste_has_docstring)
1441
579
            flags |= CO_HAS_DOCSTRING;
1442
4.04k
        if (ste->ste_method)
1443
1.80k
            flags |= CO_METHOD;
1444
4.04k
    }
1445
1446
5.64k
    if (ste->ste_coroutine && !ste->ste_generator) {
1447
135
        flags |= CO_COROUTINE;
1448
135
    }
1449
1450
    /* (Only) inherit compilerflags in PyCF_MASK */
1451
5.64k
    flags |= (c->c_flags.cf_flags & PyCF_MASK);
1452
1453
5.64k
    return flags;
1454
5.64k
}
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.64k
{
1460
5.64k
    cfg_builder *g = NULL;
1461
5.64k
    instr_sequence optimized_instrs;
1462
5.64k
    memset(&optimized_instrs, 0, sizeof(instr_sequence));
1463
1464
5.64k
    PyCodeObject *co = NULL;
1465
5.64k
    PyObject *consts = consts_dict_keys_inorder(u->u_metadata.u_consts);
1466
5.64k
    if (consts == NULL) {
1467
0
        goto error;
1468
0
    }
1469
5.64k
    g = _PyCfg_FromInstructionSequence(u->u_instr_sequence);
1470
5.64k
    if (g == NULL) {
1471
0
        goto error;
1472
0
    }
1473
5.64k
    int nlocals = (int)PyDict_GET_SIZE(u->u_metadata.u_varnames);
1474
5.64k
    int nparams = (int)PyList_GET_SIZE(u->u_ste->ste_varnames);
1475
5.64k
    assert(u->u_metadata.u_firstlineno);
1476
1477
5.64k
    if (_PyCfg_OptimizeCodeUnit(g, consts, const_cache, nlocals,
1478
5.64k
                                nparams, u->u_metadata.u_firstlineno) < 0) {
1479
0
        goto error;
1480
0
    }
1481
1482
5.64k
    int stackdepth;
1483
5.64k
    int nlocalsplus;
1484
5.64k
    if (_PyCfg_OptimizedCfgToInstructionSequence(g, &u->u_metadata,
1485
5.64k
                                                 &stackdepth, &nlocalsplus,
1486
5.64k
                                                 &optimized_instrs) < 0) {
1487
0
        goto error;
1488
0
    }
1489
1490
    /** Assembly **/
1491
5.64k
    co = _PyAssemble_MakeCodeObject(&u->u_metadata, const_cache, consts,
1492
5.64k
                                    stackdepth, &optimized_instrs, nlocalsplus,
1493
5.64k
                                    code_flags, filename);
1494
1495
5.64k
error:
1496
5.64k
    Py_XDECREF(consts);
1497
5.64k
    PyInstructionSequence_Fini(&optimized_instrs);
1498
5.64k
    _PyCfgBuilder_Free(g);
1499
5.64k
    return co;
1500
5.64k
}
1501
1502
1503
PyCodeObject *
1504
_PyCompile_OptimizeAndAssemble(compiler *c, int addNone)
1505
5.64k
{
1506
5.64k
    struct compiler_unit *u = c->u;
1507
5.64k
    PyObject *const_cache = c->c_const_cache;
1508
5.64k
    PyObject *filename = c->c_filename;
1509
1510
5.64k
    int code_flags = compute_code_flags(c);
1511
5.64k
    if (code_flags < 0) {
1512
0
        return NULL;
1513
0
    }
1514
1515
5.64k
    if (_PyCodegen_AddReturnAtEnd(c, addNone) < 0) {
1516
0
        return NULL;
1517
0
    }
1518
1519
5.64k
    return optimize_and_assemble_code_unit(u, const_cache, code_flags, filename);
1520
5.64k
}
1521
1522
PyCodeObject *
1523
_PyAST_Compile(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
1524
               int optimize, PyArena *arena, PyObject *module)
1525
856
{
1526
856
    assert(!PyErr_Occurred());
1527
856
    compiler *c = new_compiler(mod, filename, pflags, optimize, arena, module);
1528
856
    if (c == NULL) {
1529
0
        return NULL;
1530
0
    }
1531
1532
856
    PyCodeObject *co = compiler_mod(c, mod);
1533
856
    compiler_free(c);
1534
856
    assert(co || PyErr_Occurred());
1535
856
    return co;
1536
856
}
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.43k
{
1543
6.43k
    _PyFutureFeatures future;
1544
6.43k
    if (!_PyFuture_FromAST(mod, filename, &future)) {
1545
21
        return -1;
1546
21
    }
1547
6.41k
    int flags = future.ff_features | cf->cf_flags;
1548
6.41k
    if (optimize == -1) {
1549
6.41k
        optimize = _Py_GetConfig()->optimization_level;
1550
6.41k
    }
1551
6.41k
    if (!_PyAST_Preprocess(mod, arena, filename, optimize, flags,
1552
6.41k
                           no_const_folding, 0, module))
1553
0
    {
1554
0
        return -1;
1555
0
    }
1556
6.41k
    return 0;
1557
6.41k
}
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
814
{
1566
814
    doc = PyObject_CallMethod(doc, "expandtabs", NULL);
1567
814
    if (doc == NULL) {
1568
0
        return NULL;
1569
0
    }
1570
1571
814
    Py_ssize_t doc_size;
1572
814
    const char *doc_utf8 = PyUnicode_AsUTF8AndSize(doc, &doc_size);
1573
814
    if (doc_utf8 == NULL) {
1574
0
        Py_DECREF(doc);
1575
0
        return NULL;
1576
0
    }
1577
814
    const char *p = doc_utf8;
1578
814
    const char *pend = p + doc_size;
1579
1580
    // First pass: find minimum indentation of any non-blank lines
1581
    // after first line.
1582
39.3k
    while (p < pend && *p++ != '\n') {
1583
38.5k
    }
1584
1585
814
    Py_ssize_t margin = PY_SSIZE_T_MAX;
1586
5.17k
    while (p < pend) {
1587
4.36k
        const char *s = p;
1588
26.3k
        while (*p == ' ') p++;
1589
4.36k
        if (p < pend && *p != '\n') {
1590
2.88k
            margin = Py_MIN(margin, p - s);
1591
2.88k
        }
1592
145k
        while (p < pend && *p++ != '\n') {
1593
141k
        }
1594
4.36k
    }
1595
814
    if (margin == PY_SSIZE_T_MAX) {
1596
348
        margin = 0;
1597
348
    }
1598
1599
    // Second pass: write cleandoc into buff.
1600
1601
    // copy first line without leading spaces.
1602
814
    p = doc_utf8;
1603
897
    while (*p == ' ') {
1604
83
        p++;
1605
83
    }
1606
814
    if (p == doc_utf8 && margin == 0 ) {
1607
        // doc is already clean.
1608
302
        return doc;
1609
302
    }
1610
1611
512
    char *buff = PyMem_Malloc(doc_size);
1612
512
    if (buff == NULL){
1613
0
        Py_DECREF(doc);
1614
0
        PyErr_NoMemory();
1615
0
        return NULL;
1616
0
    }
1617
1618
512
    char *w = buff;
1619
1620
25.6k
    while (p < pend) {
1621
25.6k
        int ch = *w++ = *p++;
1622
25.6k
        if (ch == '\n') {
1623
511
            break;
1624
511
        }
1625
25.6k
    }
1626
1627
    // copy subsequent lines without margin.
1628
4.65k
    while (p < pend) {
1629
23.2k
        for (Py_ssize_t i = 0; i < margin; i++, p++) {
1630
20.0k
            if (*p != ' ') {
1631
912
                assert(*p == '\n' || *p == '\0');
1632
912
                break;
1633
912
            }
1634
20.0k
        }
1635
141k
        while (p < pend) {
1636
140k
            int ch = *w++ = *p++;
1637
140k
            if (ch == '\n') {
1638
3.71k
                break;
1639
3.71k
            }
1640
140k
        }
1641
4.14k
    }
1642
1643
512
    Py_DECREF(doc);
1644
512
    PyObject *res = PyUnicode_FromStringAndSize(buff, w - buff);
1645
512
    PyMem_Free(buff);
1646
512
    return res;
1647
512
}
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
1662
0
    if (!PyAST_Check(ast)) {
1663
0
        PyErr_SetString(PyExc_TypeError, "expected an AST");
1664
0
        return NULL;
1665
0
    }
1666
1667
0
    PyArena *arena = _PyArena_New();
1668
0
    if (arena == NULL) {
1669
0
        return NULL;
1670
0
    }
1671
1672
0
    mod_ty mod = PyAST_obj2mod(ast, arena, compile_mode);
1673
0
    if (mod == NULL || !_PyAST_Validate(mod)) {
1674
0
        _PyArena_Free(arena);
1675
0
        return NULL;
1676
0
    }
1677
1678
0
    compiler *c = new_compiler(mod, filename, pflags, optimize, arena, NULL);
1679
0
    if (c == NULL) {
1680
0
        _PyArena_Free(arena);
1681
0
        return NULL;
1682
0
    }
1683
0
    c->c_save_nested_seqs = true;
1684
1685
0
    metadata = PyDict_New();
1686
0
    if (metadata == NULL) {
1687
0
        return NULL;
1688
0
    }
1689
1690
0
    if (compiler_codegen(c, mod) < 0) {
1691
0
        goto finally;
1692
0
    }
1693
1694
0
    _PyCompile_CodeUnitMetadata *umd = &c->u->u_metadata;
1695
1696
0
#define SET_METADATA_INT(key, value) do { \
1697
0
        PyObject *v = PyLong_FromLong((long)value); \
1698
0
        if (v == NULL) goto finally; \
1699
0
        int res = PyDict_SetItemString(metadata, key, v); \
1700
0
        Py_XDECREF(v); \
1701
0
        if (res < 0) goto finally; \
1702
0
    } while (0);
1703
1704
0
    SET_METADATA_INT("argcount", umd->u_argcount);
1705
0
    SET_METADATA_INT("posonlyargcount", umd->u_posonlyargcount);
1706
0
    SET_METADATA_INT("kwonlyargcount", umd->u_kwonlyargcount);
1707
0
#undef SET_METADATA_INT
1708
1709
0
    int addNone = mod->kind != Expression_kind;
1710
0
    if (_PyCodegen_AddReturnAtEnd(c, addNone) < 0) {
1711
0
        goto finally;
1712
0
    }
1713
1714
0
    if (_PyInstructionSequence_ApplyLabelMap(_PyCompile_InstrSequence(c)) < 0) {
1715
0
        return NULL;
1716
0
    }
1717
    /* Allocate a copy of the instruction sequence on the heap */
1718
0
    res = _PyTuple_FromPair((PyObject *)_PyCompile_InstrSequence(c), metadata);
1719
1720
0
finally:
1721
0
    Py_XDECREF(metadata);
1722
0
    _PyCompile_ExitScope(c);
1723
0
    compiler_free(c);
1724
0
    _PyArena_Free(arena);
1725
0
    return res;
1726
0
}
1727
1728
int _PyCfg_JumpLabelsToTargets(cfg_builder *g);
1729
1730
PyCodeObject *
1731
_PyCompile_Assemble(_PyCompile_CodeUnitMetadata *umd, PyObject *filename,
1732
                    PyObject *seq)
1733
0
{
1734
0
    if (!_PyInstructionSequence_Check(seq)) {
1735
0
        PyErr_SetString(PyExc_TypeError, "expected an instruction sequence");
1736
0
        return NULL;
1737
0
    }
1738
0
    cfg_builder *g = NULL;
1739
0
    PyCodeObject *co = NULL;
1740
0
    instr_sequence optimized_instrs;
1741
0
    memset(&optimized_instrs, 0, sizeof(instr_sequence));
1742
1743
0
    PyObject *const_cache = PyDict_New();
1744
0
    if (const_cache == NULL) {
1745
0
        return NULL;
1746
0
    }
1747
1748
0
    g = _PyCfg_FromInstructionSequence((instr_sequence*)seq);
1749
0
    if (g == NULL) {
1750
0
        goto error;
1751
0
    }
1752
1753
0
    if (_PyCfg_JumpLabelsToTargets(g) < 0) {
1754
0
        goto error;
1755
0
    }
1756
1757
0
    int code_flags = 0;
1758
0
    int stackdepth, nlocalsplus;
1759
0
    if (_PyCfg_OptimizedCfgToInstructionSequence(g, umd,
1760
0
                                                 &stackdepth, &nlocalsplus,
1761
0
                                                 &optimized_instrs) < 0) {
1762
0
        goto error;
1763
0
    }
1764
1765
0
    PyObject *consts = consts_dict_keys_inorder(umd->u_consts);
1766
0
    if (consts == NULL) {
1767
0
        goto error;
1768
0
    }
1769
0
    co = _PyAssemble_MakeCodeObject(umd, const_cache,
1770
0
                                    consts, stackdepth, &optimized_instrs,
1771
0
                                    nlocalsplus, code_flags, filename);
1772
0
    Py_DECREF(consts);
1773
1774
0
error:
1775
0
    Py_DECREF(const_cache);
1776
0
    _PyCfgBuilder_Free(g);
1777
0
    PyInstructionSequence_Fini(&optimized_instrs);
1778
0
    return co;
1779
0
}
1780
1781
/* Retained for API compatibility.
1782
 * Optimization is now done in _PyCfg_OptimizeCodeUnit */
1783
1784
PyObject *
1785
PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
1786
                PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
1787
0
{
1788
0
    return Py_NewRef(code);
1789
0
}