Coverage Report

Created: 2026-10-31 06:21

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
56.8k
#define SUCCESS 0
37
1
#define ERROR -1
38
39
#define RETURN_IF_ERROR(X)  \
40
96.5k
    do {                    \
41
96.5k
        if ((X) == -1) {    \
42
0
            return ERROR;   \
43
0
        }                   \
44
96.5k
    } 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
705
{
115
705
    PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
116
117
705
    c->c_const_cache = PyDict_New();
118
705
    if (!c->c_const_cache) {
119
0
        return ERROR;
120
0
    }
121
122
705
    c->c_stack = PyList_New(0);
123
705
    if (!c->c_stack) {
124
0
        return ERROR;
125
0
    }
126
127
705
    c->c_filename = Py_NewRef(filename);
128
705
    if (!_PyFuture_FromAST(mod, filename, &c->c_future)) {
129
0
        return ERROR;
130
0
    }
131
705
    c->c_module = Py_XNewRef(module);
132
705
    if (!flags) {
133
111
        flags = &local_flags;
134
111
    }
135
705
    int merged = c->c_future.ff_features | flags->cf_flags;
136
705
    c->c_future.ff_features = merged;
137
705
    flags->cf_flags = merged;
138
705
    c->c_flags = *flags;
139
705
    c->c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
140
705
    c->c_save_nested_seqs = false;
141
142
705
    if (!_PyAST_Preprocess(mod, arena, filename, c->c_optimize, merged,
143
705
                           0, 1, module))
144
0
    {
145
0
        return ERROR;
146
0
    }
147
705
    c->c_st = _PySymtable_Build(mod, filename, &c->c_future);
148
705
    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
705
    return SUCCESS;
155
705
}
156
157
static void
158
compiler_free(compiler *c)
159
705
{
160
705
    if (c->c_st) {
161
705
        _PySymtable_Free(c->c_st);
162
705
    }
163
705
    Py_XDECREF(c->c_filename);
164
705
    Py_XDECREF(c->c_module);
165
705
    Py_XDECREF(c->c_const_cache);
166
705
    Py_XDECREF(c->c_stack);
167
705
    PyMem_Free(c);
168
705
}
169
170
static compiler*
171
new_compiler(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
172
             int optimize, PyArena *arena, PyObject *module)
173
705
{
174
705
    compiler *c = PyMem_Calloc(1, sizeof(compiler));
175
705
    if (c == NULL) {
176
0
        PyErr_NoMemory();
177
0
        return NULL;
178
0
    }
179
705
    if (compiler_setup(c, mod, filename, pflags, optimize, arena, module) < 0) {
180
0
        compiler_free(c);
181
0
        return NULL;
182
0
    }
183
705
    return c;
184
705
}
185
186
static void
187
compiler_unit_free(struct compiler_unit *u)
188
4.00k
{
189
4.00k
    Py_CLEAR(u->u_instr_sequence);
190
4.00k
    Py_CLEAR(u->u_stashed_instr_sequence);
191
4.00k
    Py_CLEAR(u->u_ste);
192
4.00k
    Py_CLEAR(u->u_metadata.u_name);
193
4.00k
    Py_CLEAR(u->u_metadata.u_qualname);
194
4.00k
    Py_CLEAR(u->u_metadata.u_consts);
195
4.00k
    Py_CLEAR(u->u_metadata.u_names);
196
4.00k
    Py_CLEAR(u->u_metadata.u_varnames);
197
4.00k
    Py_CLEAR(u->u_metadata.u_freevars);
198
4.00k
    Py_CLEAR(u->u_metadata.u_cellvars);
199
4.00k
    Py_CLEAR(u->u_metadata.u_fasthidden);
200
4.00k
    Py_CLEAR(u->u_private);
201
4.00k
    Py_CLEAR(u->u_static_attributes);
202
4.00k
    Py_CLEAR(u->u_deferred_annotations);
203
4.00k
    Py_CLEAR(u->u_conditional_annotation_indices);
204
4.00k
    PyMem_Free(u);
205
4.00k
}
206
207
9.13k
#define CAPSULE_NAME "compile.c compiler unit"
208
209
int
210
_PyCompile_MaybeAddStaticAttributeToClass(compiler *c, expr_ty e)
211
7.75k
{
212
7.75k
    assert(e->kind == Attribute_kind);
213
7.75k
    expr_ty attr_value = e->v.Attribute.value;
214
7.75k
    if (attr_value->kind != Name_kind ||
215
7.32k
        e->v.Attribute.ctx != Store ||
216
660
        !_PyUnicode_EqualToASCIIString(attr_value->v.Name.id, "self"))
217
7.20k
    {
218
7.20k
        return SUCCESS;
219
7.20k
    }
220
554
    Py_ssize_t stack_size = PyList_GET_SIZE(c->c_stack);
221
906
    for (Py_ssize_t i = stack_size - 1; i >= 0; i--) {
222
730
        PyObject *capsule = PyList_GET_ITEM(c->c_stack, i);
223
730
        struct compiler_unit *u = (struct compiler_unit *)PyCapsule_GetPointer(
224
730
                                                              capsule, CAPSULE_NAME);
225
730
        assert(u);
226
730
        if (u->u_scope_type == COMPILE_SCOPE_CLASS) {
227
378
            assert(u->u_static_attributes);
228
378
            RETURN_IF_ERROR(PySet_Add(u->u_static_attributes, e->v.Attribute.attr));
229
378
            break;
230
378
        }
231
730
    }
232
554
    return SUCCESS;
233
554
}
234
235
int
236
_PyCompile_SetQualname(compiler *c)
237
4.00k
{
238
4.00k
    Py_ssize_t stack_size;
239
4.00k
    struct compiler_unit *u = c->u;
240
4.00k
    PyObject *name, *base;
241
242
4.00k
    if (u->u_scope_type == COMPILE_SCOPE_MODULE) {
243
705
        return SUCCESS;
244
705
    }
245
246
3.29k
    base = NULL;
247
3.29k
    stack_size = PyList_GET_SIZE(c->c_stack);
248
3.29k
    assert(stack_size >= 1);
249
3.29k
    if (stack_size > 1) {
250
1.80k
        int scope, force_global = 0;
251
1.80k
        struct compiler_unit *parent;
252
1.80k
        PyObject *mangled, *capsule;
253
254
1.80k
        capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
255
1.80k
        parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
256
1.80k
        assert(parent);
257
1.80k
        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.80k
        if (u->u_scope_type == COMPILE_SCOPE_FUNCTION
272
92
            || u->u_scope_type == COMPILE_SCOPE_ASYNC_FUNCTION
273
1.71k
            || u->u_scope_type == COMPILE_SCOPE_CLASS) {
274
1.71k
            assert(u->u_metadata.u_name);
275
1.71k
            mangled = _Py_Mangle(parent->u_private, u->u_metadata.u_name);
276
1.71k
            if (!mangled) {
277
0
                return ERROR;
278
0
            }
279
280
1.71k
            scope = _PyST_GetScope(parent->u_ste, mangled);
281
1.71k
            Py_DECREF(mangled);
282
1.71k
            RETURN_IF_ERROR(scope);
283
1.71k
            assert(scope != GLOBAL_IMPLICIT);
284
1.71k
            if (scope == GLOBAL_EXPLICIT)
285
0
                force_global = 1;
286
1.71k
        }
287
288
1.80k
        if (!force_global) {
289
1.80k
            if (parent->u_scope_type == COMPILE_SCOPE_FUNCTION
290
1.01k
                || parent->u_scope_type == COMPILE_SCOPE_ASYNC_FUNCTION
291
1.01k
                || parent->u_scope_type == COMPILE_SCOPE_LAMBDA)
292
787
            {
293
787
                _Py_DECLARE_STR(dot_locals, ".<locals>");
294
787
                base = PyUnicode_Concat(parent->u_metadata.u_qualname,
295
787
                                        &_Py_STR(dot_locals));
296
787
                if (base == NULL) {
297
0
                    return ERROR;
298
0
                }
299
787
            }
300
1.01k
            else {
301
1.01k
                base = Py_NewRef(parent->u_metadata.u_qualname);
302
1.01k
            }
303
1.80k
        }
304
1.80k
        if (u->u_ste->ste_function_name != NULL) {
305
13
            PyObject *tmp = base;
306
13
            base = PyUnicode_FromFormat("%U.%U",
307
13
                base,
308
13
                u->u_ste->ste_function_name);
309
13
            Py_DECREF(tmp);
310
13
            if (base == NULL) {
311
0
                return ERROR;
312
0
            }
313
13
        }
314
1.80k
    }
315
1.49k
    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.29k
    if (base != NULL) {
320
1.82k
        name = PyUnicode_Concat(base, _Py_LATIN1_CHR('.'));
321
1.82k
        Py_DECREF(base);
322
1.82k
        if (name == NULL) {
323
0
            return ERROR;
324
0
        }
325
1.82k
        PyUnicode_Append(&name, u->u_metadata.u_name);
326
1.82k
        if (name == NULL) {
327
0
            return ERROR;
328
0
        }
329
1.82k
    }
330
1.47k
    else {
331
1.47k
        name = Py_NewRef(u->u_metadata.u_name);
332
1.47k
    }
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.29k
    if (!_PyCode_ShouldInternString(name)) {
339
1.99k
        _PyUnicode_InternMortal(_PyInterpreterState_GET(), &name);
340
1.99k
    }
341
3.29k
    u->u_metadata.u_qualname = name;
342
343
3.29k
    return SUCCESS;
344
3.29k
}
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
67.2k
{
352
67.2k
    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
67.2k
    if (o == Py_None || o == Py_Ellipsis) {
356
6.15k
        return o;
357
6.15k
    }
358
359
61.1k
    PyObject *key = _PyCode_ConstantKey(o);
360
61.1k
    if (key == NULL) {
361
0
        return NULL;
362
0
    }
363
364
61.1k
    PyObject *t;
365
61.1k
    int res = PyDict_SetDefaultRef(const_cache, key, key, &t);
366
61.1k
    if (res != 0) {
367
        // o was not inserted into const_cache. t is either the existing value
368
        // or NULL (on error).
369
24.1k
        Py_DECREF(key);
370
24.1k
        return t;
371
24.1k
    }
372
37.0k
    Py_DECREF(t);
373
374
37.0k
    if (!recursive) {
375
17.9k
        return key;
376
17.9k
    }
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
19.0k
    if (PyTuple_CheckExact(o)) {
382
950
        Py_ssize_t len = PyTuple_GET_SIZE(o);
383
3.29k
        for (Py_ssize_t i = 0; i < len; i++) {
384
2.34k
            PyObject *item = PyTuple_GET_ITEM(o, i);
385
2.34k
            PyObject *u = const_cache_insert(const_cache, item, recursive);
386
2.34k
            if (u == NULL) {
387
0
                Py_DECREF(key);
388
0
                return NULL;
389
0
            }
390
391
            // See _PyCode_ConstantKey()
392
2.34k
            PyObject *v;  // borrowed
393
2.34k
            if (PyTuple_CheckExact(u)) {
394
0
                v = PyTuple_GET_ITEM(u, 1);
395
0
            }
396
2.34k
            else {
397
2.34k
                v = u;
398
2.34k
            }
399
2.34k
            if (v != item) {
400
55
                PyTuple_SET_ITEM(o, i, Py_NewRef(v));
401
55
                Py_DECREF(item);
402
55
            }
403
404
2.34k
            Py_DECREF(u);
405
2.34k
        }
406
950
    }
407
18.1k
    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
19.0k
    return key;
459
19.0k
}
460
461
static PyObject*
462
merge_consts_recursive(PyObject *const_cache, PyObject *o)
463
38.7k
{
464
38.7k
    return const_cache_insert(const_cache, o, true);
465
38.7k
}
466
467
Py_ssize_t
468
_PyCompile_DictAddObj(PyObject *dict, PyObject *o)
469
89.0k
{
470
89.0k
    PyObject *v;
471
89.0k
    Py_ssize_t arg;
472
473
89.0k
    if (PyDict_GetItemRef(dict, o, &v) < 0) {
474
0
        return ERROR;
475
0
    }
476
89.0k
    if (!v) {
477
47.5k
        arg = PyDict_GET_SIZE(dict);
478
47.5k
        v = PyLong_FromSsize_t(arg);
479
47.5k
        if (!v) {
480
0
            return ERROR;
481
0
        }
482
47.5k
        if (PyDict_SetItem(dict, o, v) < 0) {
483
0
            Py_DECREF(v);
484
0
            return ERROR;
485
0
        }
486
47.5k
    }
487
41.5k
    else
488
41.5k
        arg = PyLong_AsLong(v);
489
89.0k
    Py_DECREF(v);
490
89.0k
    return arg;
491
89.0k
}
492
493
Py_ssize_t
494
_PyCompile_AddConst(compiler *c, PyObject *o)
495
38.7k
{
496
38.7k
    PyObject *key = merge_consts_recursive(c->c_const_cache, o);
497
38.7k
    if (key == NULL) {
498
0
        return ERROR;
499
0
    }
500
501
38.7k
    Py_ssize_t arg = _PyCompile_DictAddObj(c->u->u_metadata.u_consts, key);
502
38.7k
    Py_DECREF(key);
503
38.7k
    return arg;
504
38.7k
}
505
506
static PyObject *
507
list2dict(PyObject *list)
508
8.00k
{
509
8.00k
    Py_ssize_t i, n;
510
8.00k
    PyObject *v, *k;
511
8.00k
    PyObject *dict = PyDict_New();
512
8.00k
    if (!dict) return NULL;
513
514
8.00k
    n = PyList_Size(list);
515
15.4k
    for (i = 0; i < n; i++) {
516
7.42k
        v = PyLong_FromSsize_t(i);
517
7.42k
        if (!v) {
518
0
            Py_DECREF(dict);
519
0
            return NULL;
520
0
        }
521
7.42k
        k = PyList_GET_ITEM(list, i);
522
7.42k
        if (PyDict_SetItem(dict, k, v) < 0) {
523
0
            Py_DECREF(v);
524
0
            Py_DECREF(dict);
525
0
            return NULL;
526
0
        }
527
7.42k
        Py_DECREF(v);
528
7.42k
    }
529
8.00k
    return dict;
530
8.00k
}
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.00k
{
543
4.00k
    Py_ssize_t i = offset, num_keys, key_i;
544
4.00k
    PyObject *k, *v, *dest = PyDict_New();
545
4.00k
    PyObject *sorted_keys;
546
547
4.00k
    assert(offset >= 0);
548
4.00k
    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.00k
    sorted_keys = PyDict_Keys(src);
557
4.00k
    if (sorted_keys == NULL) {
558
0
        Py_DECREF(dest);
559
0
        return NULL;
560
0
    }
561
4.00k
    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.00k
    num_keys = PyList_GET_SIZE(sorted_keys);
567
568
22.3k
    for (key_i = 0; key_i < num_keys; key_i++) {
569
18.3k
        k = PyList_GET_ITEM(sorted_keys, key_i);
570
18.3k
        v = PyDict_GetItemWithError(src, k);
571
18.3k
        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
18.3k
        long vi = PyLong_AsLong(v);
580
18.3k
        if (vi == -1 && PyErr_Occurred()) {
581
0
            Py_DECREF(sorted_keys);
582
0
            Py_DECREF(dest);
583
0
            return NULL;
584
0
        }
585
18.3k
        if (SYMBOL_TO_SCOPE(vi) == scope_type || vi & flag) {
586
702
            PyObject *item = PyLong_FromSsize_t(i);
587
702
            if (item == NULL) {
588
0
                Py_DECREF(sorted_keys);
589
0
                Py_DECREF(dest);
590
0
                return NULL;
591
0
            }
592
702
            i++;
593
702
            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
702
            Py_DECREF(item);
600
702
        }
601
18.3k
    }
602
4.00k
    Py_DECREF(sorted_keys);
603
4.00k
    return dest;
604
4.00k
}
605
606
static int
607
add_cell_names_from_symbols(PyObject *symbols, PyObject *names)
608
4.03k
{
609
4.03k
    Py_ssize_t pos = 0;
610
4.03k
    PyObject *k, *v;
611
22.4k
    while (PyDict_Next(symbols, &pos, &k, &v)) {
612
18.3k
        long flags = PyLong_AsLong(v);
613
18.3k
        if (flags == -1 && PyErr_Occurred()) {
614
0
            return ERROR;
615
0
        }
616
18.3k
        if (SYMBOL_TO_SCOPE(flags) == CELL) {
617
495
            if (PySet_Add(names, k) < 0) {
618
0
                return ERROR;
619
0
            }
620
495
        }
621
18.3k
    }
622
4.03k
    return SUCCESS;
623
4.03k
}
624
625
static int
626
add_inlined_comprehension_cell_names(PySTEntryObject *ste, PyObject *names)
627
4.03k
{
628
9.67k
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(ste->ste_children); i++) {
629
5.63k
        PySTEntryObject *child =
630
5.63k
            (PySTEntryObject *)PyList_GET_ITEM(ste->ste_children, i);
631
5.63k
        if (child->ste_type != InlinedComprehensionBlock) {
632
5.60k
            continue;
633
5.60k
        }
634
35
        if (add_cell_names_from_symbols(child->ste_symbols, names) < 0) {
635
0
            return ERROR;
636
0
        }
637
35
        if (add_inlined_comprehension_cell_names(child, names) < 0) {
638
0
            return ERROR;
639
0
        }
640
35
    }
641
4.03k
    return SUCCESS;
642
4.03k
}
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.00k
{
649
4.00k
    PyObject *names = PySet_New(NULL);
650
4.00k
    if (names == NULL) {
651
0
        return NULL;
652
0
    }
653
4.00k
    if (add_cell_names_from_symbols(ste->ste_symbols, names) < 0) {
654
0
        Py_DECREF(names);
655
0
        return NULL;
656
0
    }
657
4.00k
    if (add_inlined_comprehension_cell_names(ste, names) < 0) {
658
0
        Py_DECREF(names);
659
0
        return NULL;
660
0
    }
661
4.00k
    PyObject *sorted = PySequence_List(names);
662
4.00k
    Py_DECREF(names);
663
4.00k
    if (sorted == NULL) {
664
0
        return NULL;
665
0
    }
666
4.00k
    if (PyList_Sort(sorted) < 0) {
667
0
        Py_DECREF(sorted);
668
0
        return NULL;
669
0
    }
670
4.00k
    PyObject *cellvars = list2dict(sorted);
671
4.00k
    Py_DECREF(sorted);
672
4.00k
    return cellvars;
673
4.00k
}
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.00k
{
680
4.00k
    struct compiler_unit *u;
681
4.00k
    u = (struct compiler_unit *)PyMem_Calloc(1, sizeof(struct compiler_unit));
682
4.00k
    if (!u) {
683
0
        PyErr_NoMemory();
684
0
        return ERROR;
685
0
    }
686
4.00k
    u->u_scope_type = scope_type;
687
4.00k
    if (umd != NULL) {
688
2.63k
        u->u_metadata = *umd;
689
2.63k
    }
690
1.36k
    else {
691
1.36k
        u->u_metadata.u_argcount = 0;
692
1.36k
        u->u_metadata.u_posonlyargcount = 0;
693
1.36k
        u->u_metadata.u_kwonlyargcount = 0;
694
1.36k
    }
695
4.00k
    u->u_ste = _PySymtable_Lookup(c->c_st, key);
696
4.00k
    if (!u->u_ste) {
697
0
        compiler_unit_free(u);
698
0
        return ERROR;
699
0
    }
700
4.00k
    u->u_metadata.u_name = Py_NewRef(name);
701
4.00k
    u->u_metadata.u_varnames = list2dict(u->u_ste->ste_varnames);
702
4.00k
    if (!u->u_metadata.u_varnames) {
703
0
        compiler_unit_free(u);
704
0
        return ERROR;
705
0
    }
706
4.00k
    u->u_metadata.u_cellvars = compiler_cellvars(u->u_ste);
707
4.00k
    if (!u->u_metadata.u_cellvars) {
708
0
        compiler_unit_free(u);
709
0
        return ERROR;
710
0
    }
711
4.00k
    if (u->u_ste->ste_needs_class_closure) {
712
        /* Cook up an implicit __class__ cell. */
713
8
        Py_ssize_t res;
714
8
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS);
715
8
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__class__));
716
8
        if (res < 0) {
717
0
            compiler_unit_free(u);
718
0
            return ERROR;
719
0
        }
720
8
    }
721
4.00k
    if (u->u_ste->ste_needs_classdict) {
722
        /* Cook up an implicit __classdict__ cell. */
723
341
        Py_ssize_t res;
724
341
        assert(u->u_scope_type == COMPILE_SCOPE_CLASS);
725
341
        res = _PyCompile_DictAddObj(u->u_metadata.u_cellvars, &_Py_ID(__classdict__));
726
341
        if (res < 0) {
727
0
            compiler_unit_free(u);
728
0
            return ERROR;
729
0
        }
730
341
    }
731
4.00k
    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.00k
    u->u_metadata.u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
743
4.00k
                               PyDict_GET_SIZE(u->u_metadata.u_cellvars));
744
4.00k
    if (!u->u_metadata.u_freevars) {
745
0
        compiler_unit_free(u);
746
0
        return ERROR;
747
0
    }
748
749
4.00k
    if (scope_type == COMPILE_SCOPE_MODULE || scope_type == COMPILE_SCOPE_CLASS) {
750
1.36k
        u->u_metadata.u_fasthidden = PySet_New(NULL);
751
1.36k
        if (!u->u_metadata.u_fasthidden) {
752
0
            compiler_unit_free(u);
753
0
            return ERROR;
754
0
        }
755
1.36k
    }
756
2.63k
    else {
757
2.63k
        u->u_metadata.u_fasthidden = NULL;
758
2.63k
    }
759
760
4.00k
    u->u_nfblocks = 0;
761
4.00k
    u->u_metadata.u_firstlineno = lineno;
762
4.00k
    u->u_metadata.u_consts = PyDict_New();
763
4.00k
    if (!u->u_metadata.u_consts) {
764
0
        compiler_unit_free(u);
765
0
        return ERROR;
766
0
    }
767
4.00k
    u->u_metadata.u_names = PyDict_New();
768
4.00k
    if (!u->u_metadata.u_names) {
769
0
        compiler_unit_free(u);
770
0
        return ERROR;
771
0
    }
772
773
4.00k
    u->u_deferred_annotations = NULL;
774
4.00k
    u->u_conditional_annotation_indices = NULL;
775
4.00k
    u->u_next_conditional_annotation_index = 0;
776
4.00k
    if (scope_type == COMPILE_SCOPE_CLASS) {
777
660
        u->u_static_attributes = PySet_New(0);
778
660
        if (!u->u_static_attributes) {
779
0
            compiler_unit_free(u);
780
0
            return ERROR;
781
0
        }
782
660
    }
783
3.34k
    else {
784
3.34k
        u->u_static_attributes = NULL;
785
3.34k
    }
786
787
4.00k
    u->u_instr_sequence = (instr_sequence*)_PyInstructionSequence_New();
788
4.00k
    if (!u->u_instr_sequence) {
789
0
        compiler_unit_free(u);
790
0
        return ERROR;
791
0
    }
792
4.00k
    u->u_stashed_instr_sequence = NULL;
793
794
    /* Push the old compiler_unit on the stack. */
795
4.00k
    if (c->u) {
796
3.29k
        PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
797
3.29k
        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.29k
        Py_DECREF(capsule);
803
3.29k
        if (private == NULL) {
804
2.63k
            private = c->u->u_private;
805
2.63k
        }
806
3.29k
    }
807
808
4.00k
    u->u_private = Py_XNewRef(private);
809
810
4.00k
    c->u = u;
811
4.00k
    return SUCCESS;
812
4.00k
}
813
814
void
815
_PyCompile_ExitScope(compiler *c)
816
4.00k
{
817
    // Don't call PySequence_DelItem() with an exception raised
818
4.00k
    PyObject *exc = PyErr_GetRaisedException();
819
820
4.00k
    instr_sequence *nested_seq = NULL;
821
4.00k
    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.00k
    compiler_unit_free(c->u);
826
    /* Restore c->u to the parent unit. */
827
4.00k
    Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
828
4.00k
    if (n >= 0) {
829
3.29k
        PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
830
3.29k
        c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
831
3.29k
        assert(c->u);
832
        /* we are deleting from a list so this really shouldn't fail */
833
3.29k
        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.29k
        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.29k
    }
844
705
    else {
845
705
        c->u = NULL;
846
705
    }
847
4.00k
    Py_XDECREF(nested_seq);
848
849
4.00k
    PyErr_SetRaisedException(exc);
850
4.00k
}
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.29k
{
861
1.29k
    fblockinfo *f;
862
1.29k
    if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
863
0
        return _PyCompile_Error(c, loc, "too many statically nested blocks");
864
0
    }
865
1.29k
    f = &c->u->u_fblock[c->u->u_nfblocks++];
866
1.29k
    f->fb_type = t;
867
1.29k
    f->fb_block = block_label;
868
1.29k
    f->fb_loc = loc;
869
1.29k
    f->fb_exit = exit;
870
1.29k
    f->fb_datum = datum;
871
1.29k
    if (t == COMPILE_FBLOCK_FINALLY_END) {
872
29
        c->c_disable_warning++;
873
29
    }
874
1.29k
    return SUCCESS;
875
1.29k
}
876
877
void
878
_PyCompile_PopFBlock(compiler *c, fblocktype t, jump_target_label block_label)
879
1.29k
{
880
1.29k
    struct compiler_unit *u = c->u;
881
1.29k
    assert(u->u_nfblocks > 0);
882
1.29k
    u->u_nfblocks--;
883
1.29k
    assert(u->u_fblock[u->u_nfblocks].fb_type == t);
884
1.29k
    assert(SAME_JUMP_TARGET_LABEL(u->u_fblock[u->u_nfblocks].fb_block, block_label));
885
1.29k
    if (t == COMPILE_FBLOCK_FINALLY_END) {
886
29
        c->c_disable_warning--;
887
29
    }
888
1.29k
}
889
890
fblockinfo *
891
_PyCompile_TopFBlock(compiler *c)
892
2.41k
{
893
2.41k
    if (c->u->u_nfblocks == 0) {
894
2.10k
        return NULL;
895
2.10k
    }
896
306
    return &c->u->u_fblock[c->u->u_nfblocks - 1];
897
2.41k
}
898
899
bool
900
_PyCompile_InExceptionHandler(compiler *c)
901
828
{
902
830
    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
818
    return false;
917
828
}
918
919
void
920
_PyCompile_DeferredAnnotations(compiler *c,
921
                               PyObject **deferred_annotations,
922
                               PyObject **conditional_annotation_indices)
923
1.19k
{
924
1.19k
    *deferred_annotations = Py_XNewRef(c->u->u_deferred_annotations);
925
1.19k
    *conditional_annotation_indices = Py_XNewRef(c->u->u_conditional_annotation_indices);
926
1.19k
}
927
928
static location
929
start_location(asdl_stmt_seq *stmts)
930
533
{
931
533
    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
532
        stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
938
532
        return SRC_LOCATION_FROM_AST(st);
939
532
    }
940
1
    return (const _Py_SourceLocation){1, 1, 0, 0};
941
533
}
942
943
static int
944
compiler_codegen(compiler *c, mod_ty mod)
945
705
{
946
705
    RETURN_IF_ERROR(_PyCodegen_EnterAnonymousScope(c, mod));
947
705
    assert(c->u->u_scope_type == COMPILE_SCOPE_MODULE);
948
705
    switch (mod->kind) {
949
533
    case Module_kind: {
950
533
        asdl_stmt_seq *stmts = mod->v.Module.body;
951
533
        RETURN_IF_ERROR(_PyCodegen_Module(c, start_location(stmts), stmts, false));
952
533
        break;
953
533
    }
954
533
    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
172
    case Expression_kind: {
961
172
        RETURN_IF_ERROR(_PyCodegen_Expression(c, mod->v.Expression.body));
962
172
        break;
963
172
    }
964
172
    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
172
    }}
970
705
    return SUCCESS;
971
705
}
972
973
static PyCodeObject *
974
compiler_mod(compiler *c, mod_ty mod)
975
705
{
976
705
    PyCodeObject *co = NULL;
977
705
    int addNone = mod->kind != Expression_kind;
978
705
    assert(c->u == NULL);
979
705
    if (compiler_codegen(c, mod) < 0) {
980
0
        goto finally;
981
0
    }
982
705
    co = _PyCompile_OptimizeAndAssemble(c, addNone);
983
705
finally:
984
705
    if (c->u != NULL) {
985
705
        _PyCompile_ExitScope(c);
986
705
    }
987
705
    return co;
988
705
}
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
37.9k
{
1002
37.9k
    int scope = _PyST_GetScope(*ste, name);
1003
37.9k
    RETURN_IF_ERROR(scope);
1004
37.9k
    while ((*ste)->ste_type == InlinedComprehensionBlock &&
1005
129
           (scope == FREE || scope == 0)) {
1006
23
        PySTEntryObject *parent = (*ste)->ste_parent;
1007
23
        assert(parent != NULL);
1008
23
        if (parent->ste_type == ClassBlock) {
1009
0
            if (_PyST_IsClassClosureName(name)) {
1010
0
                return GLOBAL_IMPLICIT;
1011
0
            }
1012
0
            break;
1013
0
        }
1014
23
        *ste = parent;
1015
23
        scope = _PyST_GetScope(*ste, name);
1016
23
        RETURN_IF_ERROR(scope);
1017
23
    }
1018
37.9k
    return scope;
1019
37.9k
}
1020
1021
int
1022
_PyCompile_GetRefType(compiler *c, PyObject *name)
1023
706
{
1024
706
    if (c->u->u_scope_type == COMPILE_SCOPE_CLASS && _PyST_IsClassClosureName(name)) {
1025
49
        return CELL;
1026
49
    }
1027
657
    PySTEntryObject *ste = c->u->u_ste;
1028
657
    int scope = compiler_resolve_inlined_free(&ste, name);
1029
657
    RETURN_IF_ERROR(scope);
1030
657
    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
657
    return scope;
1043
657
}
1044
1045
static int
1046
dict_lookup_arg(PyObject *dict, PyObject *name)
1047
1.05k
{
1048
1.05k
    PyObject *v = PyDict_GetItemWithError(dict, name);
1049
1.05k
    if (v == NULL) {
1050
0
        return ERROR;
1051
0
    }
1052
1.05k
    return PyLong_AsLong(v);
1053
1.05k
}
1054
1055
int
1056
_PyCompile_LookupCellvar(compiler *c, PyObject *name)
1057
349
{
1058
349
    assert(c->u->u_metadata.u_cellvars);
1059
349
    return dict_lookup_arg(c->u->u_metadata.u_cellvars, name);
1060
349
}
1061
1062
int
1063
_PyCompile_LookupArg(compiler *c, PyCodeObject *co, PyObject *name)
1064
702
{
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
702
    int reftype = _PyCompile_GetRefType(c, name);
1072
702
    if (reftype == -1) {
1073
0
        return ERROR;
1074
0
    }
1075
702
    int arg;
1076
702
    if (reftype == CELL) {
1077
696
        arg = dict_lookup_arg(c->u->u_metadata.u_cellvars, name);
1078
696
    }
1079
6
    else {
1080
6
        arg = dict_lookup_arg(c->u->u_metadata.u_freevars, name);
1081
6
    }
1082
702
    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
702
    return arg;
1099
702
}
1100
1101
PyObject *
1102
_PyCompile_StaticAttributesAsTuple(compiler *c)
1103
660
{
1104
660
    assert(c->u->u_static_attributes);
1105
660
    PyObject *static_attributes_unsorted = PySequence_List(c->u->u_static_attributes);
1106
660
    if (static_attributes_unsorted == NULL) {
1107
0
        return NULL;
1108
0
    }
1109
660
    if (PyList_Sort(static_attributes_unsorted) != 0) {
1110
0
        Py_DECREF(static_attributes_unsorted);
1111
0
        return NULL;
1112
0
    }
1113
660
    PyObject *static_attributes = PySequence_Tuple(static_attributes_unsorted);
1114
660
    Py_DECREF(static_attributes_unsorted);
1115
660
    return static_attributes;
1116
660
}
1117
1118
int
1119
_PyCompile_ResolveNameop(compiler *c, PyObject *mangled,
1120
                          _PyCompile_optype *optype, Py_ssize_t *arg)
1121
37.2k
{
1122
37.2k
    PyObject *dict = c->u->u_metadata.u_names;
1123
37.2k
    *optype = COMPILE_OP_NAME;
1124
1125
37.2k
    PySTEntryObject *ste = c->u->u_ste;
1126
37.2k
    assert(ste != NULL);
1127
1128
37.2k
    int scope = compiler_resolve_inlined_free(&ste, mangled);
1129
37.2k
    RETURN_IF_ERROR(scope);
1130
1131
37.2k
    switch (scope) {
1132
1.20k
    case FREE:
1133
1.20k
        dict = c->u->u_metadata.u_freevars;
1134
1.20k
        *optype = COMPILE_OP_DEREF;
1135
1.20k
        break;
1136
324
    case CELL:
1137
324
        dict = c->u->u_metadata.u_cellvars;
1138
324
        *optype = COMPILE_OP_DEREF;
1139
324
        break;
1140
25.9k
    case LOCAL:
1141
        /* Inlined comprehensions isolate their locals as FAST, even when
1142
         * nested in class or module scope. */
1143
25.9k
        if (_PyST_IsFunctionLike(ste) || ste->ste_type == InlinedComprehensionBlock) {
1144
20.1k
            *optype = COMPILE_OP_FAST;
1145
20.1k
        }
1146
25.9k
        break;
1147
5.92k
    case GLOBAL_IMPLICIT: {
1148
        /* Opcode depends on the enclosing non-inlined scope. */
1149
5.92k
        PySTEntryObject *enclosing = ste;
1150
5.93k
        while (enclosing->ste_parent != NULL) {
1151
16
            assert(enclosing->ste_type == InlinedComprehensionBlock);
1152
16
            enclosing = enclosing->ste_parent;
1153
16
        }
1154
5.92k
        if (_PyST_IsFunctionLike(enclosing)) {
1155
5.43k
            *optype = COMPILE_OP_GLOBAL;
1156
5.43k
        }
1157
5.92k
        break;
1158
0
    }
1159
11
    case GLOBAL_EXPLICIT:
1160
11
        *optype = COMPILE_OP_GLOBAL;
1161
11
        break;
1162
3.82k
    default:
1163
        /* scope can be 0 */
1164
3.82k
        break;
1165
37.2k
    }
1166
    /* XXX Handle __doc__ and the like better */
1167
37.2k
    assert(scope || PyUnicode_READ_CHAR(mangled, 0) == '_');
1168
37.2k
    if (*optype != COMPILE_OP_FAST) {
1169
17.0k
        *arg = _PyCompile_DictAddObj(dict, mangled);
1170
17.0k
        RETURN_IF_ERROR(*arg);
1171
17.0k
    }
1172
37.2k
    return scope;
1173
37.2k
}
1174
1175
int
1176
_PyCompile_EnterInlinedComprehensionScope(compiler *c, PySTEntryObject *entry,
1177
                                          _PyCompile_InlinedComprehensionState *state)
1178
35
{
1179
35
    assert(state->saved_ste == NULL);
1180
35
    state->saved_ste = c->u->u_ste;
1181
35
    c->u->u_ste = (PySTEntryObject *)Py_NewRef(entry);
1182
35
    return SUCCESS;
1183
35
}
1184
1185
int
1186
_PyCompile_ExitInlinedComprehensionScope(compiler *c,
1187
                                        _PyCompile_InlinedComprehensionState *state)
1188
35
{
1189
35
    assert(state->saved_ste != NULL);
1190
35
    Py_DECREF(c->u->u_ste);
1191
35
    c->u->u_ste = state->saved_ste;
1192
35
    state->saved_ste = NULL;
1193
35
    return SUCCESS;
1194
35
}
1195
1196
void
1197
_PyCompile_EnterConditionalBlock(struct _PyCompiler *c)
1198
2.20k
{
1199
2.20k
    c->u->u_in_conditional_block++;
1200
2.20k
}
1201
1202
void
1203
_PyCompile_LeaveConditionalBlock(struct _PyCompiler *c)
1204
2.20k
{
1205
2.20k
    assert(c->u->u_in_conditional_block > 0);
1206
2.20k
    c->u->u_in_conditional_block--;
1207
2.20k
}
1208
1209
int
1210
_PyCompile_AddDeferredAnnotation(compiler *c, stmt_ty s,
1211
                                 PyObject **conditional_annotation_index)
1212
183
{
1213
183
    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
183
    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
183
    PyObject *ptr = PyLong_FromVoidPtr((void *)s);
1226
183
    if (ptr == NULL) {
1227
0
        return ERROR;
1228
0
    }
1229
183
    if (PyList_Append(c->u->u_deferred_annotations, ptr) < 0) {
1230
0
        Py_DECREF(ptr);
1231
0
        return ERROR;
1232
0
    }
1233
183
    Py_DECREF(ptr);
1234
183
    PyObject *index;
1235
183
    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
182
    else {
1244
182
        index = PyLong_FromLong(-1);
1245
182
        if (index == NULL) {
1246
0
            return ERROR;
1247
0
        }
1248
182
    }
1249
183
    int rc = PyList_Append(c->u->u_conditional_annotation_indices, index);
1250
183
    Py_DECREF(index);
1251
183
    RETURN_IF_ERROR(rc);
1252
183
    return SUCCESS;
1253
183
}
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
183
{
1301
183
    return _Py_Mangle(c->u->u_private, name);
1302
183
}
1303
1304
PyObject *
1305
_PyCompile_MaybeMangle(compiler *c, PyObject *name)
1306
50.0k
{
1307
50.0k
    return _Py_MaybeMangle(c->u->u_private, c->u->u_ste, name);
1308
50.0k
}
1309
1310
instr_sequence *
1311
_PyCompile_InstrSequence(compiler *c)
1312
182k
{
1313
182k
    return c->u->u_instr_sequence;
1314
182k
}
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.66k
{
1348
2.66k
    return c->c_future.ff_features;
1349
2.66k
}
1350
1351
struct symtable *
1352
_PyCompile_Symtable(compiler *c)
1353
5.53k
{
1354
5.53k
    return c->c_st;
1355
5.53k
}
1356
1357
PySTEntryObject *
1358
_PyCompile_SymtableEntry(compiler *c)
1359
22.9k
{
1360
22.9k
    return c->u->u_ste;
1361
22.9k
}
1362
1363
int
1364
_PyCompile_OptimizationLevel(compiler *c)
1365
49
{
1366
49
    return c->c_optimize;
1367
49
}
1368
1369
int
1370
_PyCompile_IsInteractiveTopLevel(compiler *c)
1371
2.13k
{
1372
2.13k
    assert(c->c_stack != NULL);
1373
2.13k
    assert(PyList_CheckExact(c->c_stack));
1374
2.13k
    bool is_nested_scope = PyList_GET_SIZE(c->c_stack) > 0;
1375
2.13k
    return c->c_interactive && !is_nested_scope;
1376
2.13k
}
1377
1378
int
1379
_PyCompile_ScopeType(compiler *c)
1380
3.96k
{
1381
3.96k
    return c->u->u_scope_type;
1382
3.96k
}
1383
1384
PyObject *
1385
_PyCompile_Qualname(compiler *c)
1386
660
{
1387
660
    assert(c->u->u_metadata.u_qualname);
1388
660
    return c->u->u_metadata.u_qualname;
1389
660
}
1390
1391
_PyCompile_CodeUnitMetadata *
1392
_PyCompile_Metadata(compiler *c)
1393
33.6k
{
1394
33.6k
    return &c->u->u_metadata;
1395
33.6k
}
1396
1397
// Merge *obj* with constant cache, without recursion.
1398
int
1399
_PyCompile_ConstCacheMergeOne(PyObject *const_cache, PyObject **obj)
1400
26.0k
{
1401
26.0k
    PyObject *key = const_cache_insert(const_cache, *obj, false);
1402
26.0k
    if (key == NULL) {
1403
0
        return ERROR;
1404
0
    }
1405
26.0k
    if (PyTuple_CheckExact(key)) {
1406
24.7k
        PyObject *item = PyTuple_GET_ITEM(key, 1);
1407
24.7k
        Py_SETREF(*obj, Py_NewRef(item));
1408
24.7k
        Py_DECREF(key);
1409
24.7k
    }
1410
1.30k
    else {
1411
1.30k
        Py_SETREF(*obj, key);
1412
1.30k
    }
1413
26.0k
    return SUCCESS;
1414
26.0k
}
1415
1416
static PyObject *
1417
consts_dict_keys_inorder(PyObject *dict)
1418
4.00k
{
1419
4.00k
    PyObject *consts, *k, *v;
1420
4.00k
    Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
1421
1422
4.00k
    consts = PyList_New(size);   /* PyCode_Optimize() requires a list */
1423
4.00k
    if (consts == NULL)
1424
0
        return NULL;
1425
29.0k
    while (PyDict_Next(dict, &pos, &k, &v)) {
1426
25.0k
        assert(PyLong_CheckExact(v));
1427
25.0k
        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.0k
        if (PyTuple_CheckExact(k)) {
1432
2.15k
            k = PyTuple_GET_ITEM(k, 1);
1433
2.15k
        }
1434
25.0k
        assert(i < size);
1435
25.0k
        assert(i >= 0);
1436
25.0k
        PyList_SET_ITEM(consts, i, Py_NewRef(k));
1437
25.0k
    }
1438
4.00k
    return consts;
1439
4.00k
}
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
18.4k
{
1457
18.4k
    if (PyUnicode_CheckExact(o)) {
1458
9.39k
        Py_INCREF(o);
1459
9.39k
        if (_PyCode_ShouldInternString(o)) {
1460
6.83k
            _PyUnicode_InternMortal(_PyInterpreterState_GET(), &o);
1461
6.83k
        }
1462
9.39k
        return o;
1463
9.39k
    }
1464
9.08k
    if (PyTuple_CheckExact(o)) {
1465
1.37k
        Py_ssize_t len = PyTuple_GET_SIZE(o);
1466
4.56k
        for (Py_ssize_t i = 0; i < len; i++) {
1467
3.19k
            PyObject *item = PyTuple_GET_ITEM(o, i);
1468
3.19k
            PyObject *v = intern_constant(const_cache, item);
1469
3.19k
            if (v == NULL) {
1470
0
                return NULL;
1471
0
            }
1472
3.19k
            if (v != item) {
1473
                // intern_constants() makes the same replacement in the
1474
                // tuple if it is not made here.
1475
254
                PyTuple_SET_ITEM(o, i, v);
1476
254
                Py_DECREF(item);
1477
254
            }
1478
2.94k
            else {
1479
2.94k
                Py_DECREF(v);
1480
2.94k
            }
1481
3.19k
        }
1482
1.37k
        return Py_NewRef(o);
1483
1.37k
    }
1484
7.71k
    if (!PyFrozenSet_CheckExact(o) && !PySlice_Check(o)) {
1485
7.54k
        return Py_NewRef(o);
1486
7.54k
    }
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
171
    PyObject *key = const_cache_insert(const_cache, o, false);
1492
171
    if (key == NULL) {
1493
0
        return NULL;
1494
0
    }
1495
171
    assert(PyTuple_CheckExact(key));
1496
171
    assert(PyTuple_GET_SIZE(key) == 2);
1497
171
    o = PyTuple_GET_ITEM(key, 1);
1498
1499
171
    PyObject *items;
1500
171
    if (PyFrozenSet_CheckExact(o)) {
1501
128
        items = PySequence_Tuple(o);
1502
128
    }
1503
43
    else {
1504
43
        PySliceObject *slice = (PySliceObject *)o;
1505
43
        items = PyTuple_Pack(3, slice->start, slice->stop, slice->step);
1506
43
    }
1507
171
    if (items == NULL) {
1508
0
        Py_DECREF(key);
1509
0
        return NULL;
1510
0
    }
1511
171
    bool modified = false;
1512
171
    Py_ssize_t len = PyTuple_GET_SIZE(items);
1513
1.17k
    for (Py_ssize_t i = 0; i < len; i++) {
1514
1.00k
        PyObject *item = PyTuple_GET_ITEM(items, i);
1515
1.00k
        PyObject *v = intern_constant(const_cache, item);
1516
1.00k
        if (v == NULL) {
1517
0
            Py_DECREF(items);
1518
0
            Py_DECREF(key);
1519
0
            return NULL;
1520
0
        }
1521
1.00k
        if (v != item) {
1522
255
            modified = true;
1523
255
        }
1524
1.00k
        PyTuple_SET_ITEM(items, i, v);
1525
1.00k
        Py_DECREF(item);
1526
1.00k
    }
1527
171
    if (modified) {
1528
50
        PyObject *new;
1529
50
        if (PyFrozenSet_CheckExact(o)) {
1530
50
            new = PyFrozenSet_New(items);
1531
50
        }
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
50
        if (new == NULL) {
1538
0
            Py_DECREF(items);
1539
0
            Py_DECREF(key);
1540
0
            return NULL;
1541
0
        }
1542
50
        PyTuple_SET_ITEM(key, 1, new);
1543
50
        Py_DECREF(o);
1544
50
        o = new;
1545
50
    }
1546
171
    Py_DECREF(items);
1547
171
    Py_INCREF(o);
1548
171
    Py_DECREF(key);
1549
171
    return o;
1550
171
}
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.00k
{
1568
4.00k
    assert(PyList_CheckExact(consts));
1569
4.00k
    Py_ssize_t len = PyList_GET_SIZE(consts);
1570
18.2k
    for (Py_ssize_t i = 0; i < len; i++) {
1571
14.2k
        PyObject *item = PyList_GET_ITEM(consts, i);
1572
14.2k
        PyObject *v = intern_constant(const_cache, item);
1573
14.2k
        if (v == NULL) {
1574
0
            return ERROR;
1575
0
        }
1576
14.2k
        PyList_SET_ITEM(consts, i, v);
1577
14.2k
        Py_DECREF(item);
1578
14.2k
    }
1579
4.00k
    return SUCCESS;
1580
4.00k
}
1581
1582
static int
1583
compute_code_flags(compiler *c)
1584
4.00k
{
1585
4.00k
    PySTEntryObject *ste = c->u->u_ste;
1586
4.00k
    int flags = 0;
1587
4.00k
    if (_PyST_IsFunctionLike(ste)) {
1588
2.63k
        flags |= CO_NEWLOCALS | CO_OPTIMIZED;
1589
2.63k
        if (ste->ste_nested)
1590
788
            flags |= CO_NESTED;
1591
2.63k
        if (ste->ste_generator && !ste->ste_coroutine)
1592
80
            flags |= CO_GENERATOR;
1593
2.63k
        if (ste->ste_generator && ste->ste_coroutine)
1594
0
            flags |= CO_ASYNC_GENERATOR;
1595
2.63k
        if (ste->ste_varargs)
1596
35
            flags |= CO_VARARGS;
1597
2.63k
        if (ste->ste_varkeywords)
1598
28
            flags |= CO_VARKEYWORDS;
1599
2.63k
        if (ste->ste_has_docstring)
1600
248
            flags |= CO_HAS_DOCSTRING;
1601
2.63k
        if (ste->ste_method)
1602
987
            flags |= CO_METHOD;
1603
2.63k
    }
1604
1605
4.00k
    if (ste->ste_coroutine && !ste->ste_generator) {
1606
0
        flags |= CO_COROUTINE;
1607
0
    }
1608
1609
    /* (Only) inherit compilerflags in PyCF_MASK */
1610
4.00k
    flags |= (c->c_flags.cf_flags & PyCF_MASK);
1611
1612
4.00k
    return flags;
1613
4.00k
}
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.00k
{
1619
4.00k
    cfg_builder *g = NULL;
1620
4.00k
    instr_sequence optimized_instrs;
1621
4.00k
    memset(&optimized_instrs, 0, sizeof(instr_sequence));
1622
1623
4.00k
    PyCodeObject *co = NULL;
1624
4.00k
    PyObject *consts = consts_dict_keys_inorder(u->u_metadata.u_consts);
1625
4.00k
    if (consts == NULL) {
1626
0
        goto error;
1627
0
    }
1628
4.00k
    g = _PyCfg_FromInstructionSequence(u->u_instr_sequence);
1629
4.00k
    if (g == NULL) {
1630
0
        goto error;
1631
0
    }
1632
4.00k
    int nlocals = (int)PyDict_GET_SIZE(u->u_metadata.u_varnames);
1633
4.00k
    int nparams = (int)PyList_GET_SIZE(u->u_ste->ste_varnames);
1634
4.00k
    assert(u->u_metadata.u_firstlineno);
1635
1636
4.00k
    if (_PyCfg_OptimizeCodeUnit(g, consts, const_cache, nlocals,
1637
4.00k
                                nparams, u->u_metadata.u_firstlineno) < 0) {
1638
0
        goto error;
1639
0
    }
1640
1641
4.00k
    int stackdepth;
1642
4.00k
    int nlocalsplus;
1643
4.00k
    if (_PyCfg_OptimizedCfgToInstructionSequence(g, &u->u_metadata,
1644
4.00k
                                                 &stackdepth, &nlocalsplus,
1645
4.00k
                                                 &optimized_instrs) < 0) {
1646
0
        goto error;
1647
0
    }
1648
1649
4.00k
    if (intern_final_constants(const_cache, consts) < 0) {
1650
0
        goto error;
1651
0
    }
1652
1653
    /** Assembly **/
1654
4.00k
    co = _PyAssemble_MakeCodeObject(&u->u_metadata, const_cache, consts,
1655
4.00k
                                    stackdepth, &optimized_instrs, nlocalsplus,
1656
4.00k
                                    code_flags, filename);
1657
1658
4.00k
error:
1659
4.00k
    Py_XDECREF(consts);
1660
4.00k
    PyInstructionSequence_Fini(&optimized_instrs);
1661
4.00k
    _PyCfgBuilder_Free(g);
1662
4.00k
    return co;
1663
4.00k
}
1664
1665
1666
PyCodeObject *
1667
_PyCompile_OptimizeAndAssemble(compiler *c, int addNone)
1668
4.00k
{
1669
4.00k
    struct compiler_unit *u = c->u;
1670
4.00k
    PyObject *const_cache = c->c_const_cache;
1671
4.00k
    PyObject *filename = c->c_filename;
1672
1673
4.00k
    int code_flags = compute_code_flags(c);
1674
4.00k
    assert(code_flags >= 0);
1675
4.00k
    if (_PyCodegen_AddReturnAtEnd(c, addNone) < 0) {
1676
0
        return NULL;
1677
0
    }
1678
1679
4.00k
    return optimize_and_assemble_code_unit(u, const_cache, code_flags, filename);
1680
4.00k
}
1681
1682
PyCodeObject *
1683
_PyAST_Compile(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
1684
               int optimize, PyArena *arena, PyObject *module)
1685
705
{
1686
705
    assert(!PyErr_Occurred());
1687
705
    compiler *c = new_compiler(mod, filename, pflags, optimize, arena, module);
1688
705
    if (c == NULL) {
1689
0
        return NULL;
1690
0
    }
1691
1692
705
    PyCodeObject *co = compiler_mod(c, mod);
1693
705
    compiler_free(c);
1694
705
    assert(co || PyErr_Occurred());
1695
705
    return co;
1696
705
}
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.59k
{
1703
7.59k
    _PyFutureFeatures future;
1704
7.59k
    if (!_PyFuture_FromAST(mod, filename, &future)) {
1705
111
        return -1;
1706
111
    }
1707
7.48k
    int flags = future.ff_features | cf->cf_flags;
1708
7.48k
    if (optimize == -1) {
1709
7.48k
        optimize = _Py_GetConfig()->optimization_level;
1710
7.48k
    }
1711
7.48k
    if (!_PyAST_Preprocess(mod, arena, filename, optimize, flags,
1712
7.48k
                           no_const_folding, 0, module))
1713
0
    {
1714
0
        return -1;
1715
0
    }
1716
7.48k
    return 0;
1717
7.48k
}
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
398
{
1726
398
    doc = PyObject_CallMethod(doc, "expandtabs", NULL);
1727
398
    if (doc == NULL) {
1728
0
        return NULL;
1729
0
    }
1730
1731
398
    Py_ssize_t doc_size;
1732
398
    const char *doc_utf8 = PyUnicode_AsUTF8AndSize(doc, &doc_size);
1733
398
    if (doc_utf8 == NULL) {
1734
0
        Py_DECREF(doc);
1735
0
        return NULL;
1736
0
    }
1737
398
    const char *p = doc_utf8;
1738
398
    const char *pend = p + doc_size;
1739
1740
    // First pass: find minimum indentation of any non-blank lines
1741
    // after first line.
1742
22.1k
    while (p < pend && *p++ != '\n') {
1743
21.7k
    }
1744
1745
398
    Py_ssize_t margin = PY_SSIZE_T_MAX;
1746
2.53k
    while (p < pend) {
1747
2.13k
        const char *s = p;
1748
12.5k
        while (*p == ' ') p++;
1749
2.13k
        if (p < pend && *p != '\n') {
1750
1.41k
            margin = Py_MIN(margin, p - s);
1751
1.41k
        }
1752
67.9k
        while (p < pend && *p++ != '\n') {
1753
65.8k
        }
1754
2.13k
    }
1755
398
    if (margin == PY_SSIZE_T_MAX) {
1756
182
        margin = 0;
1757
182
    }
1758
1759
    // Second pass: write cleandoc into buff.
1760
1761
    // copy first line without leading spaces.
1762
398
    p = doc_utf8;
1763
485
    while (*p == ' ') {
1764
87
        p++;
1765
87
    }
1766
398
    if (p == doc_utf8 && margin == 0 ) {
1767
        // doc is already clean.
1768
130
        return doc;
1769
130
    }
1770
1771
268
    char *buff = PyMem_Malloc(doc_size);
1772
268
    if (buff == NULL){
1773
0
        Py_DECREF(doc);
1774
0
        PyErr_NoMemory();
1775
0
        return NULL;
1776
0
    }
1777
1778
268
    char *w = buff;
1779
1780
15.7k
    while (p < pend) {
1781
15.7k
        int ch = *w++ = *p++;
1782
15.7k
        if (ch == '\n') {
1783
267
            break;
1784
267
        }
1785
15.7k
    }
1786
1787
    // copy subsequent lines without margin.
1788
2.22k
    while (p < pend) {
1789
10.6k
        for (Py_ssize_t i = 0; i < margin; i++, p++) {
1790
9.08k
            if (*p != ' ') {
1791
399
                assert(*p == '\n' || *p == '\0');
1792
399
                break;
1793
399
            }
1794
9.08k
        }
1795
63.7k
        while (p < pend) {
1796
63.5k
            int ch = *w++ = *p++;
1797
63.5k
            if (ch == '\n') {
1798
1.77k
                break;
1799
1.77k
            }
1800
63.5k
        }
1801
1.95k
    }
1802
1803
268
    Py_DECREF(doc);
1804
268
    PyObject *res = PyUnicode_FromStringAndSize(buff, w - buff);
1805
268
    PyMem_Free(buff);
1806
268
    return res;
1807
268
}
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
}