Coverage Report

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