Coverage Report

Created: 2026-06-21 06:15

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