Coverage Report

Created: 2026-12-01 06:09

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