Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/codegen.c
Line
Count
Source
1
/*
2
 * This file implements the compiler's code generation stage, which
3
 * produces a sequence of pseudo-instructions from an AST.
4
 *
5
 * The primary entry point is _PyCodegen_Module() for modules, and
6
 * _PyCodegen_Expression() for expressions.
7
 *
8
 * CAUTION: The VISIT_* macros abort the current function when they
9
 * encounter a problem. So don't invoke them when there is memory
10
 * which needs to be released. Code blocks are OK, as the compiler
11
 * structure takes care of releasing those.  Use the arena to manage
12
 * objects.
13
 */
14
15
#include "Python.h"
16
#include "opcode.h"
17
#include "pycore_ast.h"           // _PyAST_GetDocString()
18
#define NEED_OPCODE_TABLES
19
#include "pycore_opcode_utils.h"
20
#undef NEED_OPCODE_TABLES
21
#include "pycore_c_array.h"       // _Py_c_array_t
22
#include "pycore_code.h"          // COMPARISON_LESS_THAN
23
#include "pycore_compile.h"
24
#include "pycore_instruction_sequence.h" // _PyInstructionSequence_NewLabel()
25
#include "pycore_intrinsics.h"
26
#include "pycore_long.h"          // _PyLong_GetZero()
27
#include "pycore_object.h"        // _Py_ANNOTATE_FORMAT_VALUE_WITH_FAKE_GLOBALS
28
#include "pycore_pystate.h"       // _Py_GetConfig()
29
#include "pycore_symtable.h"      // PySTEntryObject
30
#include "pycore_unicodeobject.h" // _PyUnicode_EqualToASCIIString
31
#include "pycore_ceval.h"         // SPECIAL___ENTER__
32
#include "pycore_template.h"      // _PyTemplate_Type
33
34
#define NEED_OPCODE_METADATA
35
#include "pycore_opcode_metadata.h" // _PyOpcode_opcode_metadata, _PyOpcode_num_popped/pushed
36
#undef NEED_OPCODE_METADATA
37
38
#include <stdbool.h>
39
40
175
#define COMP_GENEXP   0
41
75
#define COMP_LISTCOMP 1
42
3
#define COMP_SETCOMP  2
43
125
#define COMP_DICTCOMP 3
44
45
#undef SUCCESS
46
#undef ERROR
47
669k
#define SUCCESS 0
48
0
#define ERROR -1
49
50
#define RETURN_IF_ERROR(X)  \
51
400k
    do {                    \
52
400k
        if ((X) == -1) {    \
53
0
            return ERROR;   \
54
0
        }                   \
55
400k
    } while (0)
56
57
#define RETURN_IF_ERROR_IN_SCOPE(C, CALL)   \
58
19.7k
    do {                                    \
59
19.7k
        if ((CALL) < 0) {                   \
60
0
            _PyCompile_ExitScope((C));      \
61
0
            return ERROR;                   \
62
0
        }                                   \
63
19.7k
    } while (0)
64
65
struct _PyCompiler;
66
typedef struct _PyCompiler compiler;
67
68
11.1k
#define INSTR_SEQUENCE(C) _PyCompile_InstrSequence(C)
69
2.35k
#define FUTURE_FEATURES(C) _PyCompile_FutureFeatures(C)
70
3.00k
#define SYMTABLE(C) _PyCompile_Symtable(C)
71
21.6k
#define SYMTABLE_ENTRY(C) _PyCompile_SymtableEntry(C)
72
48
#define OPTIMIZATION_LEVEL(C) _PyCompile_OptimizationLevel(C)
73
2.03k
#define IS_INTERACTIVE_TOP_LEVEL(C) _PyCompile_IsInteractiveTopLevel(C)
74
2.43k
#define SCOPE_TYPE(C) _PyCompile_ScopeType(C)
75
#define QUALNAME(C) _PyCompile_Qualname(C)
76
18.8k
#define METADATA(C) _PyCompile_Metadata(C)
77
78
typedef _PyInstruction instruction;
79
typedef _PyInstructionSequence instr_sequence;
80
typedef _Py_SourceLocation location;
81
typedef _PyJumpTargetLabel jump_target_label;
82
83
typedef _PyCompile_FBlockInfo fblockinfo;
84
85
#define LOCATION(LNO, END_LNO, COL, END_COL) \
86
4.54k
    ((const _Py_SourceLocation){(LNO), (END_LNO), (COL), (END_COL)})
87
88
108k
#define LOC(x) SRC_LOCATION_FROM_AST(x)
89
90
#define CALL_STACK_USE(nargs, nkwds) \
91
6.68k
    ((nargs) + (nkwds) + ((nkwds) != 0))
92
93
#define NEW_JUMP_TARGET_LABEL(C, NAME) \
94
11.0k
    jump_target_label NAME = _PyInstructionSequence_NewLabel(INSTR_SEQUENCE(C)); \
95
11.0k
    if (!IS_JUMP_TARGET_LABEL(NAME)) { \
96
0
        return ERROR; \
97
0
    }
98
99
#define USE_LABEL(C, LBL) \
100
11.0k
    RETURN_IF_ERROR(_PyInstructionSequence_UseLabel(INSTR_SEQUENCE(C), (LBL).id))
101
102
static const int compare_masks[] = {
103
    [Py_LT] = COMPARISON_LESS_THAN,
104
    [Py_LE] = COMPARISON_LESS_THAN | COMPARISON_EQUALS,
105
    [Py_EQ] = COMPARISON_EQUALS,
106
    [Py_NE] = COMPARISON_NOT_EQUALS,
107
    [Py_GT] = COMPARISON_GREATER_THAN,
108
    [Py_GE] = COMPARISON_GREATER_THAN | COMPARISON_EQUALS,
109
};
110
111
112
int
113
8.92k
_Py_CArray_Init(_Py_c_array_t* array, int item_size, int initial_num_entries) {
114
8.92k
    memset(array, 0, sizeof(_Py_c_array_t));
115
8.92k
    array->item_size = item_size;
116
8.92k
    array->initial_num_entries = initial_num_entries;
117
8.92k
    return 0;
118
8.92k
}
119
120
void
121
_Py_CArray_Fini(_Py_c_array_t* array)
122
8.92k
{
123
8.92k
    if (array->array) {
124
979
        PyMem_Free(array->array);
125
979
        array->allocated_entries = 0;
126
979
    }
127
8.92k
}
128
129
int
130
_Py_CArray_EnsureCapacity(_Py_c_array_t *c_array, int idx)
131
464k
{
132
464k
    void *arr = c_array->array;
133
464k
    int alloc = c_array->allocated_entries;
134
464k
    if (arr == NULL) {
135
28.8k
        int new_alloc = c_array->initial_num_entries;
136
28.8k
        if (idx >= new_alloc) {
137
0
            new_alloc = idx + c_array->initial_num_entries;
138
0
        }
139
28.8k
        arr = PyMem_Calloc(new_alloc, c_array->item_size);
140
28.8k
        if (arr == NULL) {
141
0
            PyErr_NoMemory();
142
0
            return ERROR;
143
0
        }
144
28.8k
        alloc = new_alloc;
145
28.8k
    }
146
435k
    else if (idx >= alloc) {
147
4.00k
        size_t oldsize = alloc * c_array->item_size;
148
4.00k
        int new_alloc = alloc << 1;
149
4.00k
        if (idx >= new_alloc) {
150
0
            new_alloc = idx + c_array->initial_num_entries;
151
0
        }
152
4.00k
        size_t newsize = new_alloc * c_array->item_size;
153
154
4.00k
        if (oldsize > (SIZE_MAX >> 1)) {
155
0
            PyErr_NoMemory();
156
0
            return ERROR;
157
0
        }
158
159
4.00k
        assert(newsize > 0);
160
4.00k
        void *tmp = PyMem_Realloc(arr, newsize);
161
4.00k
        if (tmp == NULL) {
162
0
            PyErr_NoMemory();
163
0
            return ERROR;
164
0
        }
165
4.00k
        alloc = new_alloc;
166
4.00k
        arr = tmp;
167
4.00k
        memset((char *)arr + oldsize, 0, newsize - oldsize);
168
4.00k
    }
169
170
464k
    c_array->array = arr;
171
464k
    c_array->allocated_entries = alloc;
172
464k
    return SUCCESS;
173
464k
}
174
175
176
typedef struct {
177
    // A list of strings corresponding to name captures. It is used to track:
178
    // - Repeated name assignments in the same pattern.
179
    // - Different name assignments in alternatives.
180
    // - The order of name assignments in alternatives.
181
    PyObject *stores;
182
    // If 0, any name captures against our subject will raise.
183
    int allow_irrefutable;
184
    // An array of blocks to jump to on failure. Jumping to fail_pop[i] will pop
185
    // i items off of the stack. The end result looks like this (with each block
186
    // falling through to the next):
187
    // fail_pop[4]: POP_TOP
188
    // fail_pop[3]: POP_TOP
189
    // fail_pop[2]: POP_TOP
190
    // fail_pop[1]: POP_TOP
191
    // fail_pop[0]: NOP
192
    jump_target_label *fail_pop;
193
    // The current length of fail_pop.
194
    Py_ssize_t fail_pop_size;
195
    // The number of items on top of the stack that need to *stay* on top of the
196
    // stack. Variable captures go beneath these. All of them will be popped on
197
    // failure.
198
    Py_ssize_t on_top;
199
} pattern_context;
200
201
static int codegen_nameop(compiler *, location, identifier, expr_context_ty);
202
203
static int codegen_visit_stmt(compiler *, stmt_ty);
204
static int codegen_visit_keyword(compiler *, keyword_ty);
205
static int codegen_visit_expr(compiler *, expr_ty);
206
static int codegen_visit_unused_expr(compiler *, expr_ty);
207
static int codegen_augassign(compiler *, stmt_ty);
208
static int codegen_annassign(compiler *, stmt_ty);
209
static int codegen_subscript(compiler *, expr_ty);
210
static int codegen_slice_two_parts(compiler *, expr_ty);
211
static int codegen_slice(compiler *, expr_ty);
212
213
static int codegen_body(compiler *, location, asdl_stmt_seq *, bool);
214
static int codegen_with(compiler *, stmt_ty);
215
static int codegen_async_with(compiler *, stmt_ty);
216
static int codegen_with_inner(compiler *, stmt_ty, int);
217
static int codegen_async_with_inner(compiler *, stmt_ty, int);
218
static int codegen_async_for(compiler *, stmt_ty);
219
static int codegen_call_simple_kw_helper(compiler *c,
220
                                         location loc,
221
                                         asdl_keyword_seq *keywords,
222
                                         Py_ssize_t nkwelts);
223
static int codegen_call_helper_impl(compiler *c, location loc,
224
                                    int n, /* Args already pushed */
225
                                    asdl_expr_seq *args,
226
                                    PyObject *injected_arg,
227
                                    asdl_keyword_seq *keywords);
228
static int codegen_call_helper(compiler *c, location loc,
229
                               int n, asdl_expr_seq *args,
230
                               asdl_keyword_seq *keywords);
231
static int codegen_try_except(compiler *, stmt_ty);
232
static int codegen_try_star_except(compiler *, stmt_ty);
233
234
typedef enum {
235
    ITERABLE_IN_LOCAL = 0,
236
    ITERABLE_ON_STACK = 1,
237
    ITERATOR_ON_STACK = 2,
238
} IterStackPosition;
239
240
static int codegen_sync_comprehension_generator(
241
                                      compiler *c, location loc,
242
                                      asdl_comprehension_seq *generators, int gen_index,
243
                                      int depth,
244
                                      expr_ty elt, expr_ty val, int type,
245
                                      IterStackPosition iter_pos, bool avoid_creation);
246
247
static int codegen_async_comprehension_generator(
248
                                      compiler *c, location loc,
249
                                      asdl_comprehension_seq *generators, int gen_index,
250
                                      int depth,
251
                                      expr_ty elt, expr_ty val, int type,
252
                                      IterStackPosition iter_pos, bool avoid_creation);
253
254
static int codegen_pattern(compiler *, pattern_ty, pattern_context *);
255
static int codegen_match(compiler *, stmt_ty);
256
static int codegen_pattern_subpattern(compiler *,
257
                                      pattern_ty, pattern_context *);
258
static int codegen_make_closure(compiler *c, location loc,
259
                                PyCodeObject *co, Py_ssize_t flags);
260
261
262
/* Add an opcode with an integer argument */
263
static int
264
codegen_addop_i(instr_sequence *seq, int opcode, Py_ssize_t oparg, location loc)
265
113k
{
266
    /* oparg value is unsigned, but a signed C int is usually used to store
267
       it in the C code (like Python/ceval.c).
268
269
       Limit to 32-bit signed C int (rather than INT_MAX) for portability.
270
271
       The argument of a concrete bytecode instruction is limited to 8-bit.
272
       EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
273
274
113k
    int oparg_ = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
275
113k
    assert(!IS_ASSEMBLER_OPCODE(opcode));
276
113k
    return _PyInstructionSequence_Addop(seq, opcode, oparg_, loc);
277
113k
}
278
279
#define ADDOP_I(C, LOC, OP, O) \
280
108k
    RETURN_IF_ERROR(codegen_addop_i(INSTR_SEQUENCE(C), (OP), (O), (LOC)))
281
282
#define ADDOP_I_IN_SCOPE(C, LOC, OP, O) \
283
4.19k
    RETURN_IF_ERROR_IN_SCOPE(C, codegen_addop_i(INSTR_SEQUENCE(C), (OP), (O), (LOC)))
284
285
static int
286
codegen_addop_noarg(instr_sequence *seq, int opcode, location loc)
287
28.0k
{
288
28.0k
    assert(!OPCODE_HAS_ARG(opcode));
289
28.0k
    assert(!IS_ASSEMBLER_OPCODE(opcode));
290
28.0k
    return _PyInstructionSequence_Addop(seq, opcode, 0, loc);
291
28.0k
}
292
293
#define ADDOP(C, LOC, OP) \
294
26.0k
    RETURN_IF_ERROR(codegen_addop_noarg(INSTR_SEQUENCE(C), (OP), (LOC)))
295
296
#define ADDOP_IN_SCOPE(C, LOC, OP) \
297
1.98k
    RETURN_IF_ERROR_IN_SCOPE((C), codegen_addop_noarg(INSTR_SEQUENCE(C), (OP), (LOC)))
298
299
static int
300
codegen_addop_load_const(compiler *c, location loc, PyObject *o)
301
35.2k
{
302
35.2k
    Py_ssize_t arg = _PyCompile_AddConst(c, o);
303
35.2k
    if (arg < 0) {
304
0
        return ERROR;
305
0
    }
306
35.2k
    ADDOP_I(c, loc, LOAD_CONST, arg);
307
35.2k
    return SUCCESS;
308
35.2k
}
309
310
#define ADDOP_LOAD_CONST(C, LOC, O) \
311
30.9k
    RETURN_IF_ERROR(codegen_addop_load_const((C), (LOC), (O)))
312
313
#define ADDOP_LOAD_CONST_IN_SCOPE(C, LOC, O) \
314
1.25k
    RETURN_IF_ERROR_IN_SCOPE((C), codegen_addop_load_const((C), (LOC), (O)))
315
316
static int
317
codegen_addop_load_const_new(compiler *c, location loc, PyObject *o)
318
3.12k
{
319
3.12k
    if (o == NULL) {
320
0
        return ERROR;
321
0
    }
322
3.12k
    int ret = codegen_addop_load_const(c, loc, o);
323
3.12k
    Py_DECREF(o);
324
3.12k
    return ret;
325
3.12k
}
326
327
/* Same as ADDOP_LOAD_CONST, but steals a reference. */
328
#define ADDOP_LOAD_CONST_NEW(C, LOC, O)  \
329
1.86k
    RETURN_IF_ERROR(codegen_addop_load_const_new((C), (LOC), (O)))
330
331
#define ADDOP_LOAD_CONST_NEW_IN_SCOPE(C, LOC, O) \
332
1.25k
    RETURN_IF_ERROR_IN_SCOPE((C), codegen_addop_load_const_new((C), (LOC), (O)))
333
334
static int
335
codegen_addop_o(compiler *c, location loc,
336
                int opcode, PyObject *dict, PyObject *o)
337
18.7k
{
338
18.7k
    Py_ssize_t arg = _PyCompile_DictAddObj(dict, o);
339
18.7k
    RETURN_IF_ERROR(arg);
340
18.7k
    ADDOP_I(c, loc, opcode, arg);
341
18.7k
    return SUCCESS;
342
18.7k
}
343
344
#define ADDOP_N(C, LOC, OP, O, TYPE)                                    \
345
18.4k
    do {                                                                \
346
18.4k
        assert(!OPCODE_HAS_CONST(OP)); /* use ADDOP_LOAD_CONST_NEW */   \
347
18.4k
        int ret = codegen_addop_o((C), (LOC), (OP),                     \
348
18.4k
                                  METADATA(C)->u_ ## TYPE, (O));        \
349
18.4k
        Py_DECREF((O));                                                 \
350
18.4k
        RETURN_IF_ERROR(ret);                                           \
351
18.4k
    } while (0)
352
353
#define ADDOP_N_IN_SCOPE(C, LOC, OP, O, TYPE)                           \
354
316
    do {                                                                \
355
316
        assert(!OPCODE_HAS_CONST(OP)); /* use ADDOP_LOAD_CONST_NEW */   \
356
316
        int ret = codegen_addop_o((C), (LOC), (OP),                     \
357
316
                                  METADATA(C)->u_ ## TYPE, (O));        \
358
316
        Py_DECREF((O));                                                 \
359
316
        RETURN_IF_ERROR_IN_SCOPE((C), ret);                             \
360
316
    } while (0)
361
362
10.7k
#define LOAD_METHOD -1
363
10.9k
#define LOAD_SUPER_METHOD -2
364
10.7k
#define LOAD_ZERO_SUPER_ATTR -3
365
10.7k
#define LOAD_ZERO_SUPER_METHOD -4
366
367
static int
368
codegen_addop_name_custom(compiler *c, location loc, int opcode,
369
                          PyObject *dict, PyObject *o, int shift, int low)
370
11.5k
{
371
11.5k
    PyObject *mangled = _PyCompile_MaybeMangle(c, o);
372
11.5k
    if (!mangled) {
373
0
        return ERROR;
374
0
    }
375
11.5k
    Py_ssize_t arg = _PyCompile_DictAddObj(dict, mangled);
376
11.5k
    Py_DECREF(mangled);
377
11.5k
    if (arg < 0) {
378
0
        return ERROR;
379
0
    }
380
11.5k
    ADDOP_I(c, loc, opcode, (arg << shift) | low);
381
11.5k
    return SUCCESS;
382
11.5k
}
383
384
static int
385
codegen_addop_name(compiler *c, location loc,
386
                   int opcode, PyObject *dict, PyObject *o)
387
10.7k
{
388
10.7k
    int shift = 0, low = 0;
389
10.7k
    if (opcode == LOAD_ATTR) {
390
6.75k
        shift = 1;
391
6.75k
    }
392
10.7k
    if (opcode == LOAD_METHOD) {
393
2.41k
        opcode = LOAD_ATTR;
394
2.41k
        shift = 1;
395
2.41k
        low = 1;
396
2.41k
    }
397
10.7k
    if (opcode == LOAD_SUPER_ATTR) {
398
0
        shift = 2;
399
0
        low = 2;
400
0
    }
401
10.7k
    if (opcode == LOAD_SUPER_METHOD) {
402
131
        opcode = LOAD_SUPER_ATTR;
403
131
        shift = 2;
404
131
        low = 3;
405
131
    }
406
10.7k
    if (opcode == LOAD_ZERO_SUPER_ATTR) {
407
1
        opcode = LOAD_SUPER_ATTR;
408
1
        shift = 2;
409
1
    }
410
10.7k
    if (opcode == LOAD_ZERO_SUPER_METHOD) {
411
2
        opcode = LOAD_SUPER_ATTR;
412
2
        shift = 2;
413
2
        low = 1;
414
2
    }
415
10.7k
    return codegen_addop_name_custom(c, loc, opcode, dict, o, shift, low);
416
10.7k
}
417
418
#define ADDOP_NAME(C, LOC, OP, O, TYPE) \
419
10.7k
    RETURN_IF_ERROR(codegen_addop_name((C), (LOC), (OP), METADATA(C)->u_ ## TYPE, (O)))
420
421
#define ADDOP_NAME_CUSTOM(C, LOC, OP, O, TYPE, SHIFT, LOW) \
422
811
    RETURN_IF_ERROR(codegen_addop_name_custom((C), (LOC), (OP), METADATA(C)->u_ ## TYPE, (O), SHIFT, LOW))
423
424
    static int
425
codegen_addop_j(instr_sequence *seq, location loc,
426
                int opcode, jump_target_label target)
427
5.05k
{
428
5.05k
    assert(IS_JUMP_TARGET_LABEL(target));
429
5.05k
    assert(HAS_TARGET(opcode));
430
5.05k
    assert(!IS_ASSEMBLER_OPCODE(opcode));
431
5.05k
    return _PyInstructionSequence_Addop(seq, opcode, target.id, loc);
432
5.05k
}
433
434
#define ADDOP_JUMP(C, LOC, OP, O) \
435
5.05k
    RETURN_IF_ERROR(codegen_addop_j(INSTR_SEQUENCE(C), (LOC), (OP), (O)))
436
437
#define ADDOP_COMPARE(C, LOC, CMP) \
438
1.87k
    RETURN_IF_ERROR(codegen_addcompare((C), (LOC), (cmpop_ty)(CMP)))
439
440
#define ADDOP_BINARY(C, LOC, BINOP) \
441
481
    RETURN_IF_ERROR(addop_binary((C), (LOC), (BINOP), false))
442
443
#define ADDOP_INPLACE(C, LOC, BINOP) \
444
100
    RETURN_IF_ERROR(addop_binary((C), (LOC), (BINOP), true))
445
446
#define ADD_YIELD_FROM(C, LOC, await) \
447
9
    RETURN_IF_ERROR(codegen_add_yield_from((C), (LOC), (await)))
448
449
#define POP_EXCEPT_AND_RERAISE(C, LOC) \
450
265
    RETURN_IF_ERROR(codegen_pop_except_and_reraise((C), (LOC)))
451
452
#define ADDOP_YIELD(C, LOC) \
453
63
    RETURN_IF_ERROR(codegen_addop_yield((C), (LOC)))
454
455
/* VISIT and VISIT_SEQ takes an ASDL type as their second argument.  They use
456
   the ASDL name to synthesize the name of the C type and the visit function.
457
*/
458
459
#define VISIT(C, TYPE, V) \
460
69.5k
    RETURN_IF_ERROR(codegen_visit_ ## TYPE((C), (V)))
461
462
#define VISIT_IN_SCOPE(C, TYPE, V) \
463
198
    RETURN_IF_ERROR_IN_SCOPE((C), codegen_visit_ ## TYPE((C), (V)))
464
465
#define VISIT_SEQ(C, TYPE, SEQ)                                             \
466
6.82k
    do {                                                                    \
467
6.82k
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */    \
468
18.8k
        for (int _i = 0; _i < asdl_seq_LEN(seq); _i++) {                    \
469
12.0k
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i);           \
470
12.0k
            RETURN_IF_ERROR(codegen_visit_ ## TYPE((C), elt));              \
471
12.0k
        }                                                                   \
472
6.82k
    } while (0)
473
474
#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ)                                    \
475
    do {                                                                    \
476
        asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */    \
477
        for (int _i = 0; _i < asdl_seq_LEN(seq); _i++) {                    \
478
            TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i);           \
479
            if (codegen_visit_ ## TYPE((C), elt) < 0) {                     \
480
                _PyCompile_ExitScope(C);                                    \
481
                return ERROR;                                               \
482
            }                                                               \
483
        }                                                                   \
484
    } while (0)
485
486
#define VISIT_UNUSED(C, TYPE, V) \
487
2.03k
    RETURN_IF_ERROR(codegen_visit_unused_ ## TYPE((C), (V)))
488
489
static int
490
codegen_call_exit_with_nones(compiler *c, location loc)
491
96
{
492
96
    ADDOP_LOAD_CONST(c, loc, Py_None);
493
96
    ADDOP_LOAD_CONST(c, loc, Py_None);
494
96
    ADDOP_LOAD_CONST(c, loc, Py_None);
495
96
    ADDOP_I(c, loc, CALL, 3);
496
96
    return SUCCESS;
497
96
}
498
499
static int
500
codegen_add_yield_from(compiler *c, location loc, int await)
501
9
{
502
9
    NEW_JUMP_TARGET_LABEL(c, send);
503
9
    NEW_JUMP_TARGET_LABEL(c, fail);
504
9
    NEW_JUMP_TARGET_LABEL(c, exit);
505
506
9
    USE_LABEL(c, send);
507
9
    ADDOP_JUMP(c, loc, SEND, exit);
508
    // Set up a virtual try/except to handle when StopIteration is raised during
509
    // a close or throw call. The only way YIELD_VALUE raises if they do!
510
9
    ADDOP_JUMP(c, loc, SETUP_FINALLY, fail);
511
9
    ADDOP_I(c, loc, YIELD_VALUE, 1);
512
9
    ADDOP(c, NO_LOCATION, POP_BLOCK);
513
9
    ADDOP_I(c, loc, RESUME, await ? RESUME_AFTER_AWAIT : RESUME_AFTER_YIELD_FROM);
514
9
    ADDOP_JUMP(c, loc, JUMP_NO_INTERRUPT, send);
515
516
9
    USE_LABEL(c, fail);
517
9
    ADDOP(c, loc, CLEANUP_THROW);
518
519
9
    USE_LABEL(c, exit);
520
9
    ADDOP(c, loc, END_SEND);
521
9
    return SUCCESS;
522
9
}
523
524
static int
525
codegen_pop_except_and_reraise(compiler *c, location loc)
526
265
{
527
    /* Stack contents
528
     * [exc_info, lasti, exc]            COPY        3
529
     * [exc_info, lasti, exc, exc_info]  POP_EXCEPT
530
     * [exc_info, lasti, exc]            RERAISE      1
531
     * (exception_unwind clears the stack)
532
     */
533
534
265
    ADDOP_I(c, loc, COPY, 3);
535
265
    ADDOP(c, loc, POP_EXCEPT);
536
265
    ADDOP_I(c, loc, RERAISE, 1);
537
265
    return SUCCESS;
538
265
}
539
540
/* Unwind a frame block.  If preserve_tos is true, the TOS before
541
 * popping the blocks will be restored afterwards, unless another
542
 * return, break or continue is found. In which case, the TOS will
543
 * be popped.
544
 */
545
static int
546
codegen_unwind_fblock(compiler *c, location *ploc,
547
                      fblockinfo *info, int preserve_tos)
548
249
{
549
249
    switch (info->fb_type) {
550
18
        case COMPILE_FBLOCK_WHILE_LOOP:
551
93
        case COMPILE_FBLOCK_EXCEPTION_HANDLER:
552
93
        case COMPILE_FBLOCK_EXCEPTION_GROUP_HANDLER:
553
93
        case COMPILE_FBLOCK_ASYNC_COMPREHENSION_GENERATOR:
554
93
        case COMPILE_FBLOCK_INLINED_COMPREHENSION:
555
96
        case COMPILE_FBLOCK_STOP_ITERATION:
556
96
            return SUCCESS;
557
558
24
        case COMPILE_FBLOCK_FOR_LOOP:
559
            /* Pop the iterator */
560
24
            if (preserve_tos) {
561
7
                ADDOP_I(c, *ploc, SWAP, 3);
562
7
            }
563
24
            ADDOP(c, *ploc, POP_TOP);
564
24
            ADDOP(c, *ploc, POP_TOP);
565
24
            return SUCCESS;
566
567
0
        case COMPILE_FBLOCK_ASYNC_FOR_LOOP:
568
            /* Pop the iterator */
569
0
            if (preserve_tos) {
570
0
                ADDOP_I(c, *ploc, SWAP, 2);
571
0
            }
572
0
            ADDOP(c, *ploc, POP_TOP);
573
0
            return SUCCESS;
574
575
24
        case COMPILE_FBLOCK_TRY_EXCEPT:
576
24
            ADDOP(c, *ploc, POP_BLOCK);
577
24
            return SUCCESS;
578
579
17
        case COMPILE_FBLOCK_FINALLY_TRY:
580
            /* This POP_BLOCK gets the line number of the unwinding statement */
581
17
            ADDOP(c, *ploc, POP_BLOCK);
582
17
            if (preserve_tos) {
583
11
                RETURN_IF_ERROR(
584
11
                    _PyCompile_PushFBlock(c, *ploc, COMPILE_FBLOCK_POP_VALUE,
585
11
                                          NO_LABEL, NO_LABEL, NULL));
586
11
            }
587
            /* Emit the finally block */
588
17
            VISIT_SEQ(c, stmt, info->fb_datum);
589
17
            if (preserve_tos) {
590
11
                _PyCompile_PopFBlock(c, COMPILE_FBLOCK_POP_VALUE, NO_LABEL);
591
11
            }
592
            /* The finally block should appear to execute after the
593
             * statement causing the unwinding, so make the unwinding
594
             * instruction artificial */
595
17
            *ploc = NO_LOCATION;
596
17
            return SUCCESS;
597
598
0
        case COMPILE_FBLOCK_FINALLY_END:
599
0
            if (preserve_tos) {
600
0
                ADDOP_I(c, *ploc, SWAP, 2);
601
0
            }
602
0
            ADDOP(c, *ploc, POP_TOP); /* exc_value */
603
0
            if (preserve_tos) {
604
0
                ADDOP_I(c, *ploc, SWAP, 2);
605
0
            }
606
0
            ADDOP(c, *ploc, POP_BLOCK);
607
0
            ADDOP(c, *ploc, POP_EXCEPT);
608
0
            return SUCCESS;
609
610
13
        case COMPILE_FBLOCK_WITH:
611
13
        case COMPILE_FBLOCK_ASYNC_WITH:
612
13
            *ploc = info->fb_loc;
613
13
            ADDOP(c, *ploc, POP_BLOCK);
614
13
            if (preserve_tos) {
615
1
                ADDOP_I(c, *ploc, SWAP, 3);
616
1
                ADDOP_I(c, *ploc, SWAP, 2);
617
1
            }
618
13
            RETURN_IF_ERROR(codegen_call_exit_with_nones(c, *ploc));
619
13
            if (info->fb_type == COMPILE_FBLOCK_ASYNC_WITH) {
620
0
                ADDOP_I(c, *ploc, GET_AWAITABLE, 2);
621
0
                ADD_YIELD_FROM(c, *ploc, 1);
622
0
            }
623
13
            ADDOP(c, *ploc, POP_TOP);
624
            /* The exit block should appear to execute after the
625
             * statement causing the unwinding, so make the unwinding
626
             * instruction artificial */
627
13
            *ploc = NO_LOCATION;
628
13
            return SUCCESS;
629
630
75
        case COMPILE_FBLOCK_HANDLER_CLEANUP: {
631
75
            if (info->fb_datum) {
632
11
                ADDOP(c, *ploc, POP_BLOCK);
633
11
            }
634
75
            if (preserve_tos) {
635
14
                ADDOP_I(c, *ploc, SWAP, 2);
636
14
            }
637
75
            ADDOP(c, *ploc, POP_BLOCK);
638
75
            ADDOP(c, *ploc, POP_EXCEPT);
639
75
            if (info->fb_datum) {
640
11
                ADDOP_LOAD_CONST(c, *ploc, Py_None);
641
11
                RETURN_IF_ERROR(codegen_nameop(c, *ploc, info->fb_datum, Store));
642
11
                RETURN_IF_ERROR(codegen_nameop(c, *ploc, info->fb_datum, Del));
643
11
            }
644
75
            return SUCCESS;
645
75
        }
646
0
        case COMPILE_FBLOCK_POP_VALUE: {
647
0
            if (preserve_tos) {
648
0
                ADDOP_I(c, *ploc, SWAP, 2);
649
0
            }
650
0
            ADDOP(c, *ploc, POP_TOP);
651
0
            return SUCCESS;
652
0
        }
653
249
    }
654
249
    Py_UNREACHABLE();
655
249
}
656
657
/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
658
static int
659
codegen_unwind_fblock_stack(compiler *c, location *ploc,
660
                            int preserve_tos, fblockinfo **loop)
661
2.29k
{
662
2.29k
    fblockinfo *top = _PyCompile_TopFBlock(c);
663
2.29k
    if (top == NULL) {
664
2.02k
        return SUCCESS;
665
2.02k
    }
666
268
    if (top->fb_type == COMPILE_FBLOCK_EXCEPTION_GROUP_HANDLER) {
667
0
        return _PyCompile_Error(
668
0
            c, *ploc, "'break', 'continue' and 'return' cannot appear in an except* block");
669
0
    }
670
268
    if (loop != NULL && (top->fb_type == COMPILE_FBLOCK_WHILE_LOOP ||
671
42
                         top->fb_type == COMPILE_FBLOCK_FOR_LOOP ||
672
41
                         top->fb_type == COMPILE_FBLOCK_ASYNC_FOR_LOOP)) {
673
41
        *loop = top;
674
41
        return SUCCESS;
675
41
    }
676
227
    fblockinfo copy = *top;
677
227
    _PyCompile_PopFBlock(c, top->fb_type, top->fb_block);
678
227
    RETURN_IF_ERROR(codegen_unwind_fblock(c, ploc, &copy, preserve_tos));
679
227
    RETURN_IF_ERROR(codegen_unwind_fblock_stack(c, ploc, preserve_tos, loop));
680
227
    RETURN_IF_ERROR(_PyCompile_PushFBlock(c, copy.fb_loc, copy.fb_type, copy.fb_block,
681
227
                          copy.fb_exit, copy.fb_datum));
682
227
    return SUCCESS;
683
227
}
684
685
static int
686
codegen_enter_scope(compiler *c, identifier name, int scope_type,
687
                    void *key, int lineno, PyObject *private,
688
                    _PyCompile_CodeUnitMetadata *umd)
689
3.84k
{
690
3.84k
    RETURN_IF_ERROR(
691
3.84k
        _PyCompile_EnterScope(c, name, scope_type, key, lineno, private, umd));
692
3.84k
    RETURN_IF_ERROR_IN_SCOPE(c, _PyCompile_SetQualname(c));
693
3.84k
    location loc = LOCATION(lineno, lineno, 0, 0);
694
3.84k
    if (scope_type == COMPILE_SCOPE_MODULE) {
695
700
        loc.lineno = 0;
696
700
    }
697
    /* Add the generator prefix instructions. */
698
699
3.84k
    PySTEntryObject *ste = SYMTABLE_ENTRY(c);
700
3.84k
    if (ste->ste_coroutine || ste->ste_generator) {
701
        /* Note that RETURN_GENERATOR + POP_TOP have a net stack effect
702
         * of 0. This is because RETURN_GENERATOR pushes the generator
703
         before returning. */
704
59
        location loc = LOCATION(lineno, lineno, -1, -1);
705
59
        ADDOP_IN_SCOPE(c, loc, RETURN_GENERATOR);
706
59
        ADDOP_IN_SCOPE(c, loc, POP_TOP);
707
59
    }
708
709
3.84k
    ADDOP_I_IN_SCOPE(c, loc, RESUME, RESUME_AT_FUNC_START);
710
3.84k
    if (scope_type == COMPILE_SCOPE_MODULE) {
711
700
        ADDOP_IN_SCOPE(c, loc, ANNOTATIONS_PLACEHOLDER);
712
700
    }
713
3.84k
    return SUCCESS;
714
3.84k
}
715
716
static int
717
codegen_emit_annotations_prologue(compiler *c, location loc)
718
20
{
719
    // if .format > VALUE_WITH_FAKE_GLOBALS: raise NotImplementedError
720
20
    PyObject *value_with_fake_globals = PyLong_FromLong(_Py_ANNOTATE_FORMAT_VALUE_WITH_FAKE_GLOBALS);
721
20
    if (value_with_fake_globals == NULL) {
722
0
        return ERROR;
723
0
    }
724
725
20
    assert(!SYMTABLE_ENTRY(c)->ste_has_docstring);
726
20
    _Py_DECLARE_STR(format, ".format");
727
20
    ADDOP_I(c, loc, LOAD_FAST, 0);
728
20
    ADDOP_LOAD_CONST_NEW(c, loc, value_with_fake_globals);
729
20
    ADDOP_I(c, loc, COMPARE_OP, (Py_GT << 5) | compare_masks[Py_GT]);
730
20
    ADDOP(c, loc, TO_BOOL);
731
20
    NEW_JUMP_TARGET_LABEL(c, body);
732
20
    ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, body);
733
20
    ADDOP_I(c, loc, LOAD_COMMON_CONSTANT, CONSTANT_NOTIMPLEMENTEDERROR);
734
20
    ADDOP_I(c, loc, RAISE_VARARGS, 1);
735
20
    USE_LABEL(c, body);
736
20
    return SUCCESS;
737
20
}
738
739
static int
740
codegen_setup_annotations_scope(compiler *c, location loc,
741
                                void *key, PyObject *name)
742
20
{
743
20
    _PyCompile_CodeUnitMetadata umd = {
744
20
        .u_posonlyargcount = 1,
745
20
    };
746
20
    RETURN_IF_ERROR(
747
20
        codegen_enter_scope(c, name, COMPILE_SCOPE_ANNOTATIONS,
748
20
                            key, loc.lineno, NULL, &umd));
749
750
20
    RETURN_IF_ERROR_IN_SCOPE(c, codegen_emit_annotations_prologue(c, loc));
751
20
    return SUCCESS;
752
20
}
753
754
static int
755
codegen_rename_annotations_format_param(PyCodeObject *co)
756
20
{
757
    // We want the parameter to __annotate__ to be named "format" in the
758
    // signature  shown by inspect.signature(), but we need to use a
759
    // different name (.format) in the symtable; if the name
760
    // "format" appears in the annotations, it doesn't get clobbered
761
    // by this name.  This code is essentially:
762
    // co->co_localsplusnames = ("format", *co->co_localsplusnames[1:])
763
20
    const Py_ssize_t size = PyObject_Size(co->co_localsplusnames);
764
20
    if (size == -1) {
765
0
        return ERROR;
766
0
    }
767
20
    PyObject *new_names = PyTuple_New(size);
768
20
    if (new_names == NULL) {
769
0
        return ERROR;
770
0
    }
771
20
    PyTuple_SET_ITEM(new_names, 0, Py_NewRef(&_Py_ID(format)));
772
28
    for (int i = 1; i < size; i++) {
773
8
        PyObject *item = PyTuple_GetItem(co->co_localsplusnames, i);
774
8
        if (item == NULL) {
775
0
            Py_DECREF(new_names);
776
0
            return ERROR;
777
0
        }
778
8
        Py_INCREF(item);
779
8
        PyTuple_SET_ITEM(new_names, i, item);
780
8
    }
781
20
    Py_SETREF(co->co_localsplusnames, new_names);
782
20
    return SUCCESS;
783
20
}
784
785
static int
786
codegen_finish_annotations_scope(compiler *c, location loc)
787
20
{
788
20
    ADDOP_IN_SCOPE(c, loc, RETURN_VALUE);
789
20
    PyCodeObject *co = _PyCompile_OptimizeAndAssemble(c, 1);
790
20
    _PyCompile_ExitScope(c);
791
20
    if (co == NULL) {
792
0
        return ERROR;
793
0
    }
794
795
20
    if (codegen_rename_annotations_format_param(co) < 0) {
796
0
        Py_DECREF(co);
797
0
        return ERROR;
798
0
    }
799
800
20
    int ret = codegen_make_closure(c, loc, co, 0);
801
20
    Py_DECREF(co);
802
20
    RETURN_IF_ERROR(ret);
803
20
    return SUCCESS;
804
20
}
805
806
static int
807
codegen_deferred_annotations_body(compiler *c, location loc,
808
    PyObject *deferred_anno, PyObject *conditional_annotation_indices, int scope_type)
809
4
{
810
4
    Py_ssize_t annotations_len = PyList_GET_SIZE(deferred_anno);
811
812
4
    assert(PyList_CheckExact(conditional_annotation_indices));
813
4
    assert(annotations_len == PyList_Size(conditional_annotation_indices));
814
815
4
    ADDOP_I(c, loc, BUILD_MAP, 0); // stack now contains <annos>
816
817
12
    for (Py_ssize_t i = 0; i < annotations_len; i++) {
818
8
        PyObject *ptr = PyList_GET_ITEM(deferred_anno, i);
819
8
        stmt_ty st = (stmt_ty)PyLong_AsVoidPtr(ptr);
820
8
        if (st == NULL) {
821
0
            return ERROR;
822
0
        }
823
8
        PyObject *mangled = _PyCompile_Mangle(c, st->v.AnnAssign.target->v.Name.id);
824
8
        if (!mangled) {
825
0
            return ERROR;
826
0
        }
827
        // NOTE: ref of mangled can be leaked on ADDOP* and VISIT macros due to early returns
828
        // fixing would require an overhaul of these macros
829
830
8
        PyObject *cond_index = PyList_GET_ITEM(conditional_annotation_indices, i);
831
8
        assert(PyLong_CheckExact(cond_index));
832
8
        long idx = PyLong_AS_LONG(cond_index);
833
8
        NEW_JUMP_TARGET_LABEL(c, not_set);
834
835
8
        if (idx != -1) {
836
0
            ADDOP_LOAD_CONST(c, LOC(st), cond_index);
837
0
            if (scope_type == COMPILE_SCOPE_CLASS) {
838
0
                ADDOP_NAME(
839
0
                    c, LOC(st), LOAD_DEREF, &_Py_ID(__conditional_annotations__), freevars);
840
0
            }
841
0
            else {
842
0
                ADDOP_NAME(
843
0
                    c, LOC(st), LOAD_GLOBAL, &_Py_ID(__conditional_annotations__), names);
844
0
            }
845
846
0
            ADDOP_I(c, LOC(st), CONTAINS_OP, 0);
847
0
            ADDOP_JUMP(c, LOC(st), POP_JUMP_IF_FALSE, not_set);
848
0
        }
849
850
8
        VISIT(c, expr, st->v.AnnAssign.annotation);
851
8
        ADDOP_I(c, LOC(st), COPY, 2);
852
8
        ADDOP_LOAD_CONST_NEW(c, LOC(st), mangled);
853
        // stack now contains <annos> <name> <annos> <value>
854
8
        ADDOP(c, loc, STORE_SUBSCR);
855
        // stack now contains <annos>
856
857
8
        USE_LABEL(c, not_set);
858
8
    }
859
4
    return SUCCESS;
860
4
}
861
862
static int
863
codegen_process_deferred_annotations(compiler *c, location loc)
864
1.15k
{
865
1.15k
    PyObject *deferred_anno = NULL;
866
1.15k
    PyObject *conditional_annotation_indices = NULL;
867
1.15k
    _PyCompile_DeferredAnnotations(c, &deferred_anno, &conditional_annotation_indices);
868
1.15k
    if (deferred_anno == NULL) {
869
1.15k
        assert(conditional_annotation_indices == NULL);
870
1.15k
        return SUCCESS;
871
1.15k
    }
872
873
4
    int scope_type = SCOPE_TYPE(c);
874
4
    bool need_separate_block = scope_type == COMPILE_SCOPE_MODULE;
875
4
    if (need_separate_block) {
876
0
        if (_PyCompile_StartAnnotationSetup(c) == ERROR) {
877
0
            goto error;
878
0
        }
879
0
    }
880
881
    // It's possible that ste_annotations_block is set but
882
    // u_deferred_annotations is not, because the former is still
883
    // set if there are only non-simple annotations (i.e., annotations
884
    // for attributes, subscripts, or parenthesized names). However, the
885
    // reverse should not be possible.
886
4
    PySTEntryObject *ste = SYMTABLE_ENTRY(c);
887
4
    assert(ste->ste_annotation_block != NULL);
888
4
    void *key = (void *)((uintptr_t)ste->ste_id + 1);
889
4
    if (codegen_setup_annotations_scope(c, loc, key,
890
4
                                        ste->ste_annotation_block->ste_name) < 0) {
891
0
        goto error;
892
0
    }
893
4
    if (codegen_deferred_annotations_body(c, loc, deferred_anno,
894
4
                                          conditional_annotation_indices, scope_type) < 0) {
895
0
        _PyCompile_ExitScope(c);
896
0
        goto error;
897
0
    }
898
899
4
    Py_DECREF(deferred_anno);
900
4
    Py_DECREF(conditional_annotation_indices);
901
902
4
    RETURN_IF_ERROR(codegen_finish_annotations_scope(c, loc));
903
4
    RETURN_IF_ERROR(codegen_nameop(
904
4
        c, loc,
905
4
        ste->ste_type == ClassBlock ? &_Py_ID(__annotate_func__) : &_Py_ID(__annotate__),
906
4
        Store));
907
908
4
    if (need_separate_block) {
909
0
        RETURN_IF_ERROR(_PyCompile_EndAnnotationSetup(c));
910
0
    }
911
912
4
    return SUCCESS;
913
0
error:
914
0
    Py_XDECREF(deferred_anno);
915
0
    Py_XDECREF(conditional_annotation_indices);
916
0
    return ERROR;
917
4
}
918
919
/* Compile an expression */
920
int
921
_PyCodegen_Expression(compiler *c, expr_ty e)
922
172
{
923
172
    VISIT(c, expr, e);
924
172
    return SUCCESS;
925
172
}
926
927
/* Compile a sequence of statements, checking for a docstring
928
   and for annotations. */
929
930
int
931
_PyCodegen_Module(compiler *c, location loc, asdl_stmt_seq *stmts, bool is_interactive)
932
528
{
933
528
    if (SYMTABLE_ENTRY(c)->ste_has_conditional_annotations) {
934
0
        ADDOP_I(c, loc, BUILD_SET, 0);
935
0
        ADDOP_N(c, loc, STORE_NAME, &_Py_ID(__conditional_annotations__), names);
936
0
    }
937
528
    return codegen_body(c, loc, stmts, is_interactive);
938
528
}
939
940
int
941
codegen_body(compiler *c, location loc, asdl_stmt_seq *stmts, bool is_interactive)
942
1.15k
{
943
    /* If from __future__ import annotations is active,
944
     * every annotated class and module should have __annotations__.
945
     * Else __annotate__ is created when necessary. */
946
1.15k
    PySTEntryObject *ste = SYMTABLE_ENTRY(c);
947
1.15k
    if ((FUTURE_FEATURES(c) & CO_FUTURE_ANNOTATIONS) && ste->ste_annotations_used) {
948
0
        ADDOP(c, loc, SETUP_ANNOTATIONS);
949
0
    }
950
1.15k
    if (!asdl_seq_LEN(stmts)) {
951
1
        return SUCCESS;
952
1
    }
953
1.15k
    Py_ssize_t first_instr = 0;
954
1.15k
    if (!is_interactive) { /* A string literal on REPL prompt is not a docstring */
955
1.15k
        if (ste->ste_has_docstring) {
956
139
            PyObject *docstring = _PyAST_GetDocString(stmts);
957
139
            assert(docstring);
958
139
            first_instr = 1;
959
            /* set docstring */
960
139
            assert(OPTIMIZATION_LEVEL(c) < 2);
961
139
            PyObject *cleandoc = _PyCompile_CleanDoc(docstring);
962
139
            if (cleandoc == NULL) {
963
0
                return ERROR;
964
0
            }
965
139
            stmt_ty st = (stmt_ty)asdl_seq_GET(stmts, 0);
966
139
            assert(st->kind == Expr_kind);
967
139
            location loc = LOC(st->v.Expr.value);
968
139
            ADDOP_LOAD_CONST(c, loc, cleandoc);
969
139
            Py_DECREF(cleandoc);
970
139
            RETURN_IF_ERROR(codegen_nameop(c, NO_LOCATION, &_Py_ID(__doc__), Store));
971
139
        }
972
1.15k
    }
973
4.96k
    for (Py_ssize_t i = first_instr; i < asdl_seq_LEN(stmts); i++) {
974
3.81k
        VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
975
3.81k
    }
976
    // If there are annotations and the future import is not on, we
977
    // collect the annotations in a separate pass and generate an
978
    // __annotate__ function. See PEP 649.
979
1.15k
    if (!(FUTURE_FEATURES(c) & CO_FUTURE_ANNOTATIONS)) {
980
1.15k
        RETURN_IF_ERROR(codegen_process_deferred_annotations(c, loc));
981
1.15k
    }
982
1.15k
    return SUCCESS;
983
1.15k
}
984
985
int
986
_PyCodegen_EnterAnonymousScope(compiler* c, mod_ty mod)
987
700
{
988
700
    _Py_DECLARE_STR(anon_module, "<module>");
989
700
    RETURN_IF_ERROR(
990
700
        codegen_enter_scope(c, &_Py_STR(anon_module), COMPILE_SCOPE_MODULE,
991
700
                            mod, 1, NULL, NULL));
992
700
    return SUCCESS;
993
700
}
994
995
static int
996
codegen_make_closure(compiler *c, location loc,
997
                     PyCodeObject *co, Py_ssize_t flags)
998
3.14k
{
999
3.14k
    if (co->co_nfreevars) {
1000
466
        int i = PyUnstable_Code_GetFirstFree(co);
1001
1.13k
        for (; i < co->co_nlocalsplus; ++i) {
1002
            /* Bypass com_addop_varname because it will generate
1003
               LOAD_DEREF but LOAD_CLOSURE is needed.
1004
            */
1005
672
            PyObject *name = PyTuple_GET_ITEM(co->co_localsplusnames, i);
1006
672
            int arg = _PyCompile_LookupArg(c, co, name);
1007
672
            RETURN_IF_ERROR(arg);
1008
672
            ADDOP_I(c, loc, LOAD_CLOSURE, arg);
1009
672
        }
1010
466
        flags |= MAKE_FUNCTION_CLOSURE;
1011
466
        ADDOP_I(c, loc, BUILD_TUPLE, co->co_nfreevars);
1012
466
    }
1013
3.14k
    ADDOP_LOAD_CONST(c, loc, (PyObject*)co);
1014
1015
3.14k
    ADDOP(c, loc, MAKE_FUNCTION);
1016
1017
3.14k
    if (flags & MAKE_FUNCTION_CLOSURE) {
1018
466
        ADDOP_I(c, loc, SET_FUNCTION_ATTRIBUTE, MAKE_FUNCTION_CLOSURE);
1019
466
    }
1020
3.14k
    if (flags & MAKE_FUNCTION_ANNOTATIONS) {
1021
0
        ADDOP_I(c, loc, SET_FUNCTION_ATTRIBUTE, MAKE_FUNCTION_ANNOTATIONS);
1022
0
    }
1023
3.14k
    if (flags & MAKE_FUNCTION_ANNOTATE) {
1024
16
        ADDOP_I(c, loc, SET_FUNCTION_ATTRIBUTE, MAKE_FUNCTION_ANNOTATE);
1025
16
    }
1026
3.14k
    if (flags & MAKE_FUNCTION_KWDEFAULTS) {
1027
142
        ADDOP_I(c, loc, SET_FUNCTION_ATTRIBUTE, MAKE_FUNCTION_KWDEFAULTS);
1028
142
    }
1029
3.14k
    if (flags & MAKE_FUNCTION_DEFAULTS) {
1030
575
        ADDOP_I(c, loc, SET_FUNCTION_ATTRIBUTE, MAKE_FUNCTION_DEFAULTS);
1031
575
    }
1032
3.14k
    return SUCCESS;
1033
3.14k
}
1034
1035
static int
1036
codegen_decorators(compiler *c, asdl_expr_seq* decos)
1037
2.90k
{
1038
2.90k
    if (!decos) {
1039
2.76k
        return SUCCESS;
1040
2.76k
    }
1041
1042
282
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(decos); i++) {
1043
143
        VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1044
143
    }
1045
139
    return SUCCESS;
1046
139
}
1047
1048
static int
1049
codegen_apply_decorators(compiler *c, asdl_expr_seq* decos)
1050
2.90k
{
1051
2.90k
    if (!decos) {
1052
2.76k
        return SUCCESS;
1053
2.76k
    }
1054
1055
282
    for (Py_ssize_t i = asdl_seq_LEN(decos) - 1; i > -1; i--) {
1056
143
        location loc = LOC((expr_ty)asdl_seq_GET(decos, i));
1057
143
        ADDOP_I(c, loc, CALL, 0);
1058
143
    }
1059
139
    return SUCCESS;
1060
139
}
1061
1062
static int
1063
codegen_kwonlydefaults(compiler *c, location loc,
1064
                       asdl_arg_seq *kwonlyargs, asdl_expr_seq *kw_defaults)
1065
2.47k
{
1066
    /* Push a dict of keyword-only default values.
1067
1068
       Return -1 on error, 0 if no dict pushed, 1 if a dict is pushed.
1069
       */
1070
2.47k
    int default_count = 0;
1071
2.98k
    for (int i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1072
512
        arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1073
512
        expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1074
512
        if (default_) {
1075
506
            default_count++;
1076
506
            PyObject *mangled = _PyCompile_MaybeMangle(c, arg->arg);
1077
506
            if (!mangled) {
1078
0
                return ERROR;
1079
0
            }
1080
506
            ADDOP_LOAD_CONST_NEW(c, loc, mangled);
1081
506
            VISIT(c, expr, default_);
1082
506
        }
1083
512
    }
1084
2.47k
    if (default_count) {
1085
142
        ADDOP_I(c, loc, BUILD_MAP, default_count);
1086
142
        return 1;
1087
142
    }
1088
2.33k
    else {
1089
2.33k
        return 0;
1090
2.33k
    }
1091
2.47k
}
1092
1093
static int
1094
codegen_visit_annexpr(compiler *c, expr_ty annotation)
1095
0
{
1096
0
    location loc = LOC(annotation);
1097
0
    ADDOP_LOAD_CONST_NEW(c, loc, _PyAST_ExprAsUnicode(annotation));
1098
0
    return SUCCESS;
1099
0
}
1100
1101
static int
1102
codegen_argannotation(compiler *c, identifier id,
1103
    expr_ty annotation, Py_ssize_t *annotations_len, location loc)
1104
38
{
1105
38
    if (!annotation) {
1106
4
        return SUCCESS;
1107
4
    }
1108
34
    PyObject *mangled = _PyCompile_MaybeMangle(c, id);
1109
34
    if (!mangled) {
1110
0
        return ERROR;
1111
0
    }
1112
34
    ADDOP_LOAD_CONST(c, loc, mangled);
1113
34
    Py_DECREF(mangled);
1114
1115
34
    if (FUTURE_FEATURES(c) & CO_FUTURE_ANNOTATIONS) {
1116
0
        VISIT(c, annexpr, annotation);
1117
0
    }
1118
34
    else {
1119
34
        if (annotation->kind == Starred_kind) {
1120
            // *args: *Ts (where Ts is a TypeVarTuple).
1121
            // Do [annotation_value] = [*Ts].
1122
            // (Note that in theory we could end up here even for an argument
1123
            // other than *args, but in practice the grammar doesn't allow it.)
1124
0
            VISIT(c, expr, annotation->v.Starred.value);
1125
0
            ADDOP_I(c, loc, UNPACK_SEQUENCE, (Py_ssize_t) 1);
1126
0
        }
1127
34
        else {
1128
34
            VISIT(c, expr, annotation);
1129
34
        }
1130
34
    }
1131
34
    *annotations_len += 1;
1132
34
    return SUCCESS;
1133
34
}
1134
1135
static int
1136
codegen_argannotations(compiler *c, asdl_arg_seq* args,
1137
                       Py_ssize_t *annotations_len, location loc)
1138
48
{
1139
48
    int i;
1140
70
    for (i = 0; i < asdl_seq_LEN(args); i++) {
1141
22
        arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
1142
22
        RETURN_IF_ERROR(
1143
22
            codegen_argannotation(
1144
22
                        c,
1145
22
                        arg->arg,
1146
22
                        arg->annotation,
1147
22
                        annotations_len,
1148
22
                        loc));
1149
22
    }
1150
48
    return SUCCESS;
1151
48
}
1152
1153
static int
1154
codegen_annotations_in_scope(compiler *c, location loc,
1155
                             arguments_ty args, expr_ty returns,
1156
                             Py_ssize_t *annotations_len)
1157
16
{
1158
16
    RETURN_IF_ERROR(
1159
16
        codegen_argannotations(c, args->posonlyargs, annotations_len, loc));
1160
1161
16
    RETURN_IF_ERROR(
1162
16
        codegen_argannotations(c, args->args, annotations_len, loc));
1163
1164
16
    if (args->vararg && args->vararg->annotation) {
1165
0
        RETURN_IF_ERROR(
1166
0
            codegen_argannotation(c, args->vararg->arg,
1167
0
                                     args->vararg->annotation, annotations_len, loc));
1168
0
    }
1169
1170
16
    RETURN_IF_ERROR(
1171
16
        codegen_argannotations(c, args->kwonlyargs, annotations_len, loc));
1172
1173
16
    if (args->kwarg && args->kwarg->annotation) {
1174
0
        RETURN_IF_ERROR(
1175
0
            codegen_argannotation(c, args->kwarg->arg,
1176
0
                                     args->kwarg->annotation, annotations_len, loc));
1177
0
    }
1178
1179
16
    RETURN_IF_ERROR(
1180
16
        codegen_argannotation(c, &_Py_ID(return), returns, annotations_len, loc));
1181
1182
16
    return 0;
1183
16
}
1184
1185
static int
1186
codegen_function_annotations(compiler *c, location loc,
1187
                             arguments_ty args, expr_ty returns)
1188
2.27k
{
1189
    /* Push arg annotation names and values.
1190
       The expressions are evaluated separately from the rest of the source code.
1191
1192
       Return -1 on error, or a combination of flags to add to the function.
1193
       */
1194
2.27k
    Py_ssize_t annotations_len = 0;
1195
1196
2.27k
    PySTEntryObject *ste;
1197
2.27k
    RETURN_IF_ERROR(_PySymtable_LookupOptional(SYMTABLE(c), args, &ste));
1198
2.27k
    assert(ste != NULL);
1199
1200
2.27k
    if (ste->ste_annotations_used) {
1201
16
        int err = codegen_setup_annotations_scope(c, loc, (void *)args, ste->ste_name);
1202
16
        Py_DECREF(ste);
1203
16
        RETURN_IF_ERROR(err);
1204
16
        RETURN_IF_ERROR_IN_SCOPE(
1205
16
            c, codegen_annotations_in_scope(c, loc, args, returns, &annotations_len)
1206
16
        );
1207
16
        ADDOP_I_IN_SCOPE(c, loc, BUILD_MAP, annotations_len);
1208
16
        RETURN_IF_ERROR(codegen_finish_annotations_scope(c, loc));
1209
16
        return MAKE_FUNCTION_ANNOTATE;
1210
16
    }
1211
2.26k
    else {
1212
2.26k
        Py_DECREF(ste);
1213
2.26k
    }
1214
1215
2.26k
    return 0;
1216
2.27k
}
1217
1218
static int
1219
codegen_defaults(compiler *c, arguments_ty args,
1220
                        location loc)
1221
575
{
1222
575
    VISIT_SEQ(c, expr, args->defaults);
1223
575
    ADDOP_I(c, loc, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
1224
575
    return SUCCESS;
1225
575
}
1226
1227
static Py_ssize_t
1228
codegen_default_arguments(compiler *c, location loc,
1229
                          arguments_ty args)
1230
2.47k
{
1231
2.47k
    Py_ssize_t funcflags = 0;
1232
2.47k
    if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
1233
575
        RETURN_IF_ERROR(codegen_defaults(c, args, loc));
1234
575
        funcflags |= MAKE_FUNCTION_DEFAULTS;
1235
575
    }
1236
2.47k
    if (args->kwonlyargs) {
1237
2.47k
        int res = codegen_kwonlydefaults(c, loc,
1238
2.47k
                                         args->kwonlyargs,
1239
2.47k
                                         args->kw_defaults);
1240
2.47k
        RETURN_IF_ERROR(res);
1241
2.47k
        if (res > 0) {
1242
142
            funcflags |= MAKE_FUNCTION_KWDEFAULTS;
1243
142
        }
1244
2.47k
    }
1245
2.47k
    return funcflags;
1246
2.47k
}
1247
1248
static int
1249
codegen_wrap_in_stopiteration_handler(compiler *c)
1250
59
{
1251
59
    NEW_JUMP_TARGET_LABEL(c, handler);
1252
1253
    /* Insert SETUP_CLEANUP just after the initial RETURN_GENERATOR; POP_TOP */
1254
59
    instr_sequence *seq = INSTR_SEQUENCE(c);
1255
59
    int resume = 0;
1256
131
    while (_PyInstructionSequence_GetInstruction(seq, resume).i_opcode != RETURN_GENERATOR) {
1257
72
        resume++;
1258
72
        assert(resume < seq->s_used);
1259
72
    }
1260
59
    resume++;
1261
59
    assert(_PyInstructionSequence_GetInstruction(seq, resume).i_opcode == POP_TOP);
1262
59
    resume++;
1263
59
    assert(resume < seq->s_used);
1264
59
    RETURN_IF_ERROR(
1265
59
        _PyInstructionSequence_InsertInstruction(
1266
59
            seq, resume,
1267
59
            SETUP_CLEANUP, handler.id, NO_LOCATION));
1268
1269
59
    ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
1270
59
    ADDOP(c, NO_LOCATION, RETURN_VALUE);
1271
59
    USE_LABEL(c, handler);
1272
59
    ADDOP_I(c, NO_LOCATION, CALL_INTRINSIC_1, INTRINSIC_STOPITERATION_ERROR);
1273
59
    ADDOP_I(c, NO_LOCATION, RERAISE, 1);
1274
59
    return SUCCESS;
1275
59
}
1276
1277
static int
1278
codegen_type_param_bound_or_default(compiler *c, expr_ty e,
1279
                                    identifier name, void *key,
1280
                                    bool allow_starred)
1281
0
{
1282
0
    PyObject *defaults = PyTuple_Pack(1, _PyLong_GetOne());
1283
0
    ADDOP_LOAD_CONST_NEW(c, LOC(e), defaults);
1284
0
    RETURN_IF_ERROR(codegen_setup_annotations_scope(c, LOC(e), key, name));
1285
0
    if (allow_starred && e->kind == Starred_kind) {
1286
0
        VISIT_IN_SCOPE(c, expr, e->v.Starred.value);
1287
0
        ADDOP_I_IN_SCOPE(c, LOC(e), UNPACK_SEQUENCE, (Py_ssize_t)1);
1288
0
    }
1289
0
    else {
1290
0
        VISIT_IN_SCOPE(c, expr, e);
1291
0
    }
1292
0
    ADDOP_IN_SCOPE(c, LOC(e), RETURN_VALUE);
1293
0
    PyCodeObject *co = _PyCompile_OptimizeAndAssemble(c, 1);
1294
0
    _PyCompile_ExitScope(c);
1295
0
    if (co == NULL) {
1296
0
        return ERROR;
1297
0
    }
1298
0
    if (codegen_rename_annotations_format_param(co) < 0) {
1299
0
        Py_DECREF(co);
1300
0
        return ERROR;
1301
0
    }
1302
0
    int ret = codegen_make_closure(c, LOC(e), co, MAKE_FUNCTION_DEFAULTS);
1303
0
    Py_DECREF(co);
1304
0
    RETURN_IF_ERROR(ret);
1305
0
    return SUCCESS;
1306
0
}
1307
1308
static int
1309
codegen_type_params(compiler *c, asdl_type_param_seq *type_params)
1310
0
{
1311
0
    if (!type_params) {
1312
0
        return SUCCESS;
1313
0
    }
1314
0
    Py_ssize_t n = asdl_seq_LEN(type_params);
1315
0
    bool seen_default = false;
1316
1317
0
    for (Py_ssize_t i = 0; i < n; i++) {
1318
0
        type_param_ty typeparam = asdl_seq_GET(type_params, i);
1319
0
        location loc = LOC(typeparam);
1320
0
        switch(typeparam->kind) {
1321
0
        case TypeVar_kind:
1322
0
            ADDOP_LOAD_CONST(c, loc, typeparam->v.TypeVar.name);
1323
0
            if (typeparam->v.TypeVar.bound) {
1324
0
                expr_ty bound = typeparam->v.TypeVar.bound;
1325
0
                RETURN_IF_ERROR(
1326
0
                    codegen_type_param_bound_or_default(c, bound, typeparam->v.TypeVar.name,
1327
0
                                                        (void *)typeparam, false));
1328
1329
0
                int intrinsic = bound->kind == Tuple_kind
1330
0
                    ? INTRINSIC_TYPEVAR_WITH_CONSTRAINTS
1331
0
                    : INTRINSIC_TYPEVAR_WITH_BOUND;
1332
0
                ADDOP_I(c, loc, CALL_INTRINSIC_2, intrinsic);
1333
0
            }
1334
0
            else {
1335
0
                ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEVAR);
1336
0
            }
1337
0
            if (typeparam->v.TypeVar.default_value) {
1338
0
                seen_default = true;
1339
0
                expr_ty default_ = typeparam->v.TypeVar.default_value;
1340
0
                RETURN_IF_ERROR(
1341
0
                    codegen_type_param_bound_or_default(c, default_, typeparam->v.TypeVar.name,
1342
0
                                                        (void *)((uintptr_t)typeparam + 1), false));
1343
0
                ADDOP_I(c, loc, CALL_INTRINSIC_2, INTRINSIC_SET_TYPEPARAM_DEFAULT);
1344
0
            }
1345
0
            else if (seen_default) {
1346
0
                return _PyCompile_Error(c, loc, "non-default type parameter '%U' "
1347
0
                                        "follows default type parameter",
1348
0
                                        typeparam->v.TypeVar.name);
1349
0
            }
1350
0
            ADDOP_I(c, loc, COPY, 1);
1351
0
            RETURN_IF_ERROR(codegen_nameop(c, loc, typeparam->v.TypeVar.name, Store));
1352
0
            break;
1353
0
        case TypeVarTuple_kind:
1354
0
            ADDOP_LOAD_CONST(c, loc, typeparam->v.TypeVarTuple.name);
1355
0
            ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEVARTUPLE);
1356
0
            if (typeparam->v.TypeVarTuple.default_value) {
1357
0
                expr_ty default_ = typeparam->v.TypeVarTuple.default_value;
1358
0
                RETURN_IF_ERROR(
1359
0
                    codegen_type_param_bound_or_default(c, default_, typeparam->v.TypeVarTuple.name,
1360
0
                                                        (void *)typeparam, true));
1361
0
                ADDOP_I(c, loc, CALL_INTRINSIC_2, INTRINSIC_SET_TYPEPARAM_DEFAULT);
1362
0
                seen_default = true;
1363
0
            }
1364
0
            else if (seen_default) {
1365
0
                return _PyCompile_Error(c, loc, "non-default type parameter '%U' "
1366
0
                                        "follows default type parameter",
1367
0
                                        typeparam->v.TypeVarTuple.name);
1368
0
            }
1369
0
            ADDOP_I(c, loc, COPY, 1);
1370
0
            RETURN_IF_ERROR(codegen_nameop(c, loc, typeparam->v.TypeVarTuple.name, Store));
1371
0
            break;
1372
0
        case ParamSpec_kind:
1373
0
            ADDOP_LOAD_CONST(c, loc, typeparam->v.ParamSpec.name);
1374
0
            ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_PARAMSPEC);
1375
0
            if (typeparam->v.ParamSpec.default_value) {
1376
0
                expr_ty default_ = typeparam->v.ParamSpec.default_value;
1377
0
                RETURN_IF_ERROR(
1378
0
                    codegen_type_param_bound_or_default(c, default_, typeparam->v.ParamSpec.name,
1379
0
                                                        (void *)typeparam, false));
1380
0
                ADDOP_I(c, loc, CALL_INTRINSIC_2, INTRINSIC_SET_TYPEPARAM_DEFAULT);
1381
0
                seen_default = true;
1382
0
            }
1383
0
            else if (seen_default) {
1384
0
                return _PyCompile_Error(c, loc, "non-default type parameter '%U' "
1385
0
                                        "follows default type parameter",
1386
0
                                        typeparam->v.ParamSpec.name);
1387
0
            }
1388
0
            ADDOP_I(c, loc, COPY, 1);
1389
0
            RETURN_IF_ERROR(codegen_nameop(c, loc, typeparam->v.ParamSpec.name, Store));
1390
0
            break;
1391
0
        }
1392
0
    }
1393
0
    ADDOP_I(c, LOC(asdl_seq_GET(type_params, 0)), BUILD_TUPLE, n);
1394
0
    return SUCCESS;
1395
0
}
1396
1397
static int
1398
codegen_emit_function_body(compiler *c, asdl_stmt_seq *body)
1399
2.27k
{
1400
2.27k
    PySTEntryObject *ste = SYMTABLE_ENTRY(c);
1401
2.27k
    Py_ssize_t first_instr = 0;
1402
2.27k
    if (ste->ste_has_docstring) {
1403
201
        PyObject *docstring = _PyAST_GetDocString(body);
1404
201
        assert(docstring);
1405
201
        first_instr = 1;
1406
201
        docstring = _PyCompile_CleanDoc(docstring);
1407
201
        if (docstring == NULL) {
1408
0
            return ERROR;
1409
0
        }
1410
201
        Py_ssize_t idx = _PyCompile_AddConst(c, docstring);
1411
201
        Py_DECREF(docstring);
1412
201
        RETURN_IF_ERROR(idx < 0 ? ERROR : SUCCESS);
1413
201
    }
1414
1415
2.27k
    NEW_JUMP_TARGET_LABEL(c, start);
1416
2.27k
    USE_LABEL(c, start);
1417
2.27k
    bool add_stopiteration_handler = ste->ste_coroutine || ste->ste_generator;
1418
2.27k
    if (add_stopiteration_handler) {
1419
        /* codegen_wrap_in_stopiteration_handler will push a block, so we need to account for that */
1420
35
        RETURN_IF_ERROR(
1421
35
            _PyCompile_PushFBlock(c, NO_LOCATION, COMPILE_FBLOCK_STOP_ITERATION,
1422
35
                                  start, NO_LABEL, NULL));
1423
35
    }
1424
1425
7.68k
    for (Py_ssize_t i = first_instr; i < asdl_seq_LEN(body); i++) {
1426
5.40k
        VISIT(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
1427
5.40k
    }
1428
2.27k
    if (add_stopiteration_handler) {
1429
35
        RETURN_IF_ERROR(codegen_wrap_in_stopiteration_handler(c));
1430
35
        _PyCompile_PopFBlock(c, COMPILE_FBLOCK_STOP_ITERATION, start);
1431
35
    }
1432
2.27k
    return SUCCESS;
1433
2.27k
}
1434
1435
static int
1436
codegen_function_body(compiler *c, stmt_ty s, int is_async, Py_ssize_t funcflags,
1437
                      int firstlineno)
1438
2.27k
{
1439
2.27k
    arguments_ty args;
1440
2.27k
    identifier name;
1441
2.27k
    asdl_stmt_seq *body;
1442
2.27k
    int scope_type;
1443
1444
2.27k
    if (is_async) {
1445
0
        assert(s->kind == AsyncFunctionDef_kind);
1446
1447
0
        args = s->v.AsyncFunctionDef.args;
1448
0
        name = s->v.AsyncFunctionDef.name;
1449
0
        body = s->v.AsyncFunctionDef.body;
1450
1451
0
        scope_type = COMPILE_SCOPE_ASYNC_FUNCTION;
1452
2.27k
    } else {
1453
2.27k
        assert(s->kind == FunctionDef_kind);
1454
1455
2.27k
        args = s->v.FunctionDef.args;
1456
2.27k
        name = s->v.FunctionDef.name;
1457
2.27k
        body = s->v.FunctionDef.body;
1458
1459
2.27k
        scope_type = COMPILE_SCOPE_FUNCTION;
1460
2.27k
    }
1461
1462
2.27k
    _PyCompile_CodeUnitMetadata umd = {
1463
2.27k
        .u_argcount = asdl_seq_LEN(args->args),
1464
2.27k
        .u_posonlyargcount = asdl_seq_LEN(args->posonlyargs),
1465
2.27k
        .u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs),
1466
2.27k
    };
1467
2.27k
    RETURN_IF_ERROR(
1468
2.27k
        codegen_enter_scope(c, name, scope_type, (void *)s, firstlineno, NULL, &umd));
1469
1470
2.27k
    RETURN_IF_ERROR_IN_SCOPE(c, codegen_emit_function_body(c, body));
1471
1472
2.27k
    PyCodeObject *co = _PyCompile_OptimizeAndAssemble(c, 1);
1473
2.27k
    _PyCompile_ExitScope(c);
1474
2.27k
    if (co == NULL) {
1475
0
        return ERROR;
1476
0
    }
1477
2.27k
    int ret = codegen_make_closure(c, LOC(s), co, funcflags);
1478
2.27k
    Py_DECREF(co);
1479
2.27k
    return ret;
1480
2.27k
}
1481
1482
static int
1483
codegen_function(compiler *c, stmt_ty s, int is_async)
1484
2.27k
{
1485
2.27k
    arguments_ty args;
1486
2.27k
    expr_ty returns;
1487
2.27k
    identifier name;
1488
2.27k
    asdl_expr_seq *decos;
1489
2.27k
    asdl_type_param_seq *type_params;
1490
2.27k
    Py_ssize_t funcflags;
1491
2.27k
    int firstlineno;
1492
1493
2.27k
    if (is_async) {
1494
0
        assert(s->kind == AsyncFunctionDef_kind);
1495
1496
0
        args = s->v.AsyncFunctionDef.args;
1497
0
        returns = s->v.AsyncFunctionDef.returns;
1498
0
        decos = s->v.AsyncFunctionDef.decorator_list;
1499
0
        name = s->v.AsyncFunctionDef.name;
1500
0
        type_params = s->v.AsyncFunctionDef.type_params;
1501
2.27k
    } else {
1502
2.27k
        assert(s->kind == FunctionDef_kind);
1503
1504
2.27k
        args = s->v.FunctionDef.args;
1505
2.27k
        returns = s->v.FunctionDef.returns;
1506
2.27k
        decos = s->v.FunctionDef.decorator_list;
1507
2.27k
        name = s->v.FunctionDef.name;
1508
2.27k
        type_params = s->v.FunctionDef.type_params;
1509
2.27k
    }
1510
1511
2.27k
    RETURN_IF_ERROR(codegen_decorators(c, decos));
1512
1513
2.27k
    firstlineno = s->lineno;
1514
2.27k
    if (asdl_seq_LEN(decos)) {
1515
138
        firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
1516
138
    }
1517
1518
2.27k
    location loc = LOC(s);
1519
1520
2.27k
    int is_generic = asdl_seq_LEN(type_params) > 0;
1521
1522
2.27k
    funcflags = codegen_default_arguments(c, loc, args);
1523
2.27k
    RETURN_IF_ERROR(funcflags);
1524
1525
2.27k
    int num_typeparam_args = 0;
1526
1527
2.27k
    if (is_generic) {
1528
0
        if (funcflags & MAKE_FUNCTION_DEFAULTS) {
1529
0
            num_typeparam_args += 1;
1530
0
        }
1531
0
        if (funcflags & MAKE_FUNCTION_KWDEFAULTS) {
1532
0
            num_typeparam_args += 1;
1533
0
        }
1534
0
        if (num_typeparam_args == 2) {
1535
0
            ADDOP_I(c, loc, SWAP, 2);
1536
0
        }
1537
0
        PyObject *type_params_name = PyUnicode_FromFormat("<generic parameters of %U>", name);
1538
0
        if (!type_params_name) {
1539
0
            return ERROR;
1540
0
        }
1541
0
        _PyCompile_CodeUnitMetadata umd = {
1542
0
            .u_argcount = num_typeparam_args,
1543
0
        };
1544
0
        int ret = codegen_enter_scope(c, type_params_name, COMPILE_SCOPE_ANNOTATIONS,
1545
0
                                      (void *)type_params, firstlineno, NULL, &umd);
1546
0
        Py_DECREF(type_params_name);
1547
0
        RETURN_IF_ERROR(ret);
1548
0
        RETURN_IF_ERROR_IN_SCOPE(c, codegen_type_params(c, type_params));
1549
0
        for (int i = 0; i < num_typeparam_args; i++) {
1550
0
            ADDOP_I_IN_SCOPE(c, loc, LOAD_FAST, i);
1551
0
        }
1552
0
    }
1553
1554
2.27k
    int annotations_flag = codegen_function_annotations(c, loc, args, returns);
1555
2.27k
    if (annotations_flag < 0) {
1556
0
        if (is_generic) {
1557
0
            _PyCompile_ExitScope(c);
1558
0
        }
1559
0
        return ERROR;
1560
0
    }
1561
2.27k
    funcflags |= annotations_flag;
1562
1563
2.27k
    int ret = codegen_function_body(c, s, is_async, funcflags, firstlineno);
1564
2.27k
    if (is_generic) {
1565
0
        RETURN_IF_ERROR_IN_SCOPE(c, ret);
1566
0
    }
1567
2.27k
    else {
1568
2.27k
        RETURN_IF_ERROR(ret);
1569
2.27k
    }
1570
1571
2.27k
    if (is_generic) {
1572
0
        ADDOP_I_IN_SCOPE(c, loc, SWAP, 2);
1573
0
        ADDOP_I_IN_SCOPE(c, loc, CALL_INTRINSIC_2, INTRINSIC_SET_FUNCTION_TYPE_PARAMS);
1574
1575
0
        PyCodeObject *co = _PyCompile_OptimizeAndAssemble(c, 0);
1576
0
        _PyCompile_ExitScope(c);
1577
0
        if (co == NULL) {
1578
0
            return ERROR;
1579
0
        }
1580
0
        int ret = codegen_make_closure(c, loc, co, 0);
1581
0
        Py_DECREF(co);
1582
0
        RETURN_IF_ERROR(ret);
1583
0
        if (num_typeparam_args > 0) {
1584
0
            ADDOP_I(c, loc, SWAP, num_typeparam_args + 1);
1585
0
            ADDOP_I(c, loc, CALL, num_typeparam_args - 1);
1586
0
        }
1587
0
        else {
1588
0
            ADDOP(c, loc, PUSH_NULL);
1589
0
            ADDOP_I(c, loc, CALL, 0);
1590
0
        }
1591
0
    }
1592
1593
2.27k
    RETURN_IF_ERROR(codegen_apply_decorators(c, decos));
1594
2.27k
    return codegen_nameop(c, loc, name, Store);
1595
2.27k
}
1596
1597
static int
1598
codegen_set_type_params_in_class(compiler *c, location loc)
1599
0
{
1600
0
    _Py_DECLARE_STR(type_params, ".type_params");
1601
0
    RETURN_IF_ERROR(codegen_nameop(c, loc, &_Py_STR(type_params), Load));
1602
0
    RETURN_IF_ERROR(codegen_nameop(c, loc, &_Py_ID(__type_params__), Store));
1603
0
    return SUCCESS;
1604
0
}
1605
1606
1607
static int
1608
codegen_class_body(compiler *c, stmt_ty s, int firstlineno)
1609
629
{
1610
    /* ultimately generate code for:
1611
         <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
1612
       where:
1613
         <func> is a zero arg function/closure created from the class body.
1614
            It mutates its locals to build the class namespace.
1615
         <name> is the class name
1616
         <bases> is the positional arguments and *varargs argument
1617
         <keywords> is the keyword arguments and **kwds argument
1618
       This borrows from codegen_call.
1619
    */
1620
1621
    /* 1. compile the class body into a code object */
1622
629
    RETURN_IF_ERROR(
1623
629
        codegen_enter_scope(c, s->v.ClassDef.name, COMPILE_SCOPE_CLASS,
1624
629
                            (void *)s, firstlineno, s->v.ClassDef.name, NULL));
1625
1626
629
    location loc = LOCATION(firstlineno, firstlineno, 0, 0);
1627
    /* load (global) __name__ ... */
1628
629
    RETURN_IF_ERROR_IN_SCOPE(c, codegen_nameop(c, loc, &_Py_ID(__name__), Load));
1629
    /* ... and store it as __module__ */
1630
629
    RETURN_IF_ERROR_IN_SCOPE(c, codegen_nameop(c, loc, &_Py_ID(__module__), Store));
1631
629
    ADDOP_LOAD_CONST_IN_SCOPE(c, loc, QUALNAME(c));
1632
629
    RETURN_IF_ERROR_IN_SCOPE(c, codegen_nameop(c, loc, &_Py_ID(__qualname__), Store));
1633
629
    ADDOP_LOAD_CONST_NEW_IN_SCOPE(c, loc, PyLong_FromLong(METADATA(c)->u_firstlineno));
1634
629
    RETURN_IF_ERROR_IN_SCOPE(c, codegen_nameop(c, loc, &_Py_ID(__firstlineno__), Store));
1635
629
    asdl_type_param_seq *type_params = s->v.ClassDef.type_params;
1636
629
    if (asdl_seq_LEN(type_params) > 0) {
1637
0
        RETURN_IF_ERROR_IN_SCOPE(c, codegen_set_type_params_in_class(c, loc));
1638
0
    }
1639
629
    if (SYMTABLE_ENTRY(c)->ste_needs_classdict) {
1640
316
        ADDOP_IN_SCOPE(c, loc, LOAD_LOCALS);
1641
1642
        // We can't use codegen_nameop here because we need to generate a
1643
        // STORE_DEREF in a class namespace, and codegen_nameop() won't do
1644
        // that by default.
1645
316
        ADDOP_N_IN_SCOPE(c, loc, STORE_DEREF, &_Py_ID(__classdict__), cellvars);
1646
316
    }
1647
629
    if (SYMTABLE_ENTRY(c)->ste_has_conditional_annotations) {
1648
0
        ADDOP_I_IN_SCOPE(c, loc, BUILD_SET, 0);
1649
0
        ADDOP_N_IN_SCOPE(c, loc, STORE_DEREF, &_Py_ID(__conditional_annotations__), cellvars);
1650
0
    }
1651
    /* compile the body proper */
1652
629
    RETURN_IF_ERROR_IN_SCOPE(c, codegen_body(c, loc, s->v.ClassDef.body, false));
1653
629
    ADDOP_LOAD_CONST_NEW_IN_SCOPE(c, NO_LOCATION, _PyCompile_StaticAttributesAsTuple(c));
1654
629
    RETURN_IF_ERROR_IN_SCOPE(
1655
629
        c, codegen_nameop(c, NO_LOCATION, &_Py_ID(__static_attributes__), Store));
1656
    /* The following code is artificial */
1657
    /* Set __classdictcell__ if necessary */
1658
629
    if (SYMTABLE_ENTRY(c)->ste_needs_classdict) {
1659
        /* Store __classdictcell__ into class namespace */
1660
316
        int i = _PyCompile_LookupCellvar(c, &_Py_ID(__classdict__));
1661
316
        RETURN_IF_ERROR_IN_SCOPE(c, i);
1662
316
        ADDOP_I_IN_SCOPE(c, NO_LOCATION, LOAD_CLOSURE, i);
1663
316
        RETURN_IF_ERROR_IN_SCOPE(
1664
316
            c, codegen_nameop(c, NO_LOCATION, &_Py_ID(__classdictcell__), Store));
1665
316
    }
1666
    /* Return __classcell__ if it is referenced, otherwise return None */
1667
629
    if (SYMTABLE_ENTRY(c)->ste_needs_class_closure) {
1668
        /* Store __classcell__ into class namespace & return it */
1669
7
        int i = _PyCompile_LookupCellvar(c, &_Py_ID(__class__));
1670
7
        RETURN_IF_ERROR_IN_SCOPE(c, i);
1671
7
        ADDOP_I_IN_SCOPE(c, NO_LOCATION, LOAD_CLOSURE, i);
1672
7
        ADDOP_I_IN_SCOPE(c, NO_LOCATION, COPY, 1);
1673
7
        RETURN_IF_ERROR_IN_SCOPE(
1674
7
            c, codegen_nameop(c, NO_LOCATION, &_Py_ID(__classcell__), Store));
1675
7
    }
1676
622
    else {
1677
        /* No methods referenced __class__, so just return None */
1678
622
        ADDOP_LOAD_CONST_IN_SCOPE(c, NO_LOCATION, Py_None);
1679
622
    }
1680
629
    ADDOP_IN_SCOPE(c, NO_LOCATION, RETURN_VALUE);
1681
    /* create the code object */
1682
629
    PyCodeObject *co = _PyCompile_OptimizeAndAssemble(c, 1);
1683
1684
    /* leave the new scope */
1685
629
    _PyCompile_ExitScope(c);
1686
629
    if (co == NULL) {
1687
0
        return ERROR;
1688
0
    }
1689
1690
    /* 2. load the 'build_class' function */
1691
1692
    // these instructions should be attributed to the class line,
1693
    // not a decorator line
1694
629
    loc = LOC(s);
1695
629
    ADDOP(c, loc, LOAD_BUILD_CLASS);
1696
629
    ADDOP(c, loc, PUSH_NULL);
1697
1698
    /* 3. load a function (or closure) made from the code object */
1699
629
    int ret = codegen_make_closure(c, loc, co, 0);
1700
629
    Py_DECREF(co);
1701
629
    RETURN_IF_ERROR(ret);
1702
1703
    /* 4. load class name */
1704
629
    ADDOP_LOAD_CONST(c, loc, s->v.ClassDef.name);
1705
1706
629
    return SUCCESS;
1707
629
}
1708
1709
static int
1710
codegen_class(compiler *c, stmt_ty s)
1711
629
{
1712
629
    asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
1713
1714
629
    RETURN_IF_ERROR(codegen_decorators(c, decos));
1715
1716
629
    int firstlineno = s->lineno;
1717
629
    if (asdl_seq_LEN(decos)) {
1718
1
        firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
1719
1
    }
1720
629
    location loc = LOC(s);
1721
1722
629
    asdl_type_param_seq *type_params = s->v.ClassDef.type_params;
1723
629
    int is_generic = asdl_seq_LEN(type_params) > 0;
1724
629
    if (is_generic) {
1725
0
        PyObject *type_params_name = PyUnicode_FromFormat("<generic parameters of %U>",
1726
0
                                                         s->v.ClassDef.name);
1727
0
        if (!type_params_name) {
1728
0
            return ERROR;
1729
0
        }
1730
0
        int ret = codegen_enter_scope(c, type_params_name, COMPILE_SCOPE_ANNOTATIONS,
1731
0
                                      (void *)type_params, firstlineno, s->v.ClassDef.name, NULL);
1732
0
        Py_DECREF(type_params_name);
1733
0
        RETURN_IF_ERROR(ret);
1734
0
        RETURN_IF_ERROR_IN_SCOPE(c, codegen_type_params(c, type_params));
1735
0
        _Py_DECLARE_STR(type_params, ".type_params");
1736
0
        RETURN_IF_ERROR_IN_SCOPE(c, codegen_nameop(c, loc, &_Py_STR(type_params), Store));
1737
0
    }
1738
1739
629
    int ret = codegen_class_body(c, s, firstlineno);
1740
629
    if (is_generic) {
1741
0
        RETURN_IF_ERROR_IN_SCOPE(c, ret);
1742
0
    }
1743
629
    else {
1744
629
        RETURN_IF_ERROR(ret);
1745
629
    }
1746
1747
    /* generate the rest of the code for the call */
1748
1749
629
    if (is_generic) {
1750
0
        _Py_DECLARE_STR(type_params, ".type_params");
1751
0
        _Py_DECLARE_STR(generic_base, ".generic_base");
1752
0
        RETURN_IF_ERROR_IN_SCOPE(c, codegen_nameop(c, loc, &_Py_STR(type_params), Load));
1753
0
        ADDOP_I_IN_SCOPE(c, loc, CALL_INTRINSIC_1, INTRINSIC_SUBSCRIPT_GENERIC);
1754
0
        RETURN_IF_ERROR_IN_SCOPE(c, codegen_nameop(c, loc, &_Py_STR(generic_base), Store));
1755
1756
0
        RETURN_IF_ERROR_IN_SCOPE(c, codegen_call_helper_impl(c, loc, 2,
1757
0
                                                             s->v.ClassDef.bases,
1758
0
                                                             &_Py_STR(generic_base),
1759
0
                                                             s->v.ClassDef.keywords));
1760
1761
0
        PyCodeObject *co = _PyCompile_OptimizeAndAssemble(c, 0);
1762
1763
0
        _PyCompile_ExitScope(c);
1764
0
        if (co == NULL) {
1765
0
            return ERROR;
1766
0
        }
1767
0
        int ret = codegen_make_closure(c, loc, co, 0);
1768
0
        Py_DECREF(co);
1769
0
        RETURN_IF_ERROR(ret);
1770
0
        ADDOP(c, loc, PUSH_NULL);
1771
0
        ADDOP_I(c, loc, CALL, 0);
1772
629
    } else {
1773
629
        RETURN_IF_ERROR(codegen_call_helper(c, loc, 2,
1774
629
                                            s->v.ClassDef.bases,
1775
629
                                            s->v.ClassDef.keywords));
1776
629
    }
1777
1778
    /* 6. apply decorators */
1779
629
    RETURN_IF_ERROR(codegen_apply_decorators(c, decos));
1780
1781
    /* 7. store into <name> */
1782
629
    RETURN_IF_ERROR(codegen_nameop(c, loc, s->v.ClassDef.name, Store));
1783
629
    return SUCCESS;
1784
629
}
1785
1786
static int
1787
codegen_typealias_body(compiler *c, stmt_ty s)
1788
0
{
1789
0
    location loc = LOC(s);
1790
0
    PyObject *name = s->v.TypeAlias.name->v.Name.id;
1791
0
    PyObject *defaults = PyTuple_Pack(1, _PyLong_GetOne());
1792
0
    ADDOP_LOAD_CONST_NEW(c, loc, defaults);
1793
0
    RETURN_IF_ERROR(
1794
0
        codegen_setup_annotations_scope(c, LOC(s), s, name));
1795
1796
0
    assert(!SYMTABLE_ENTRY(c)->ste_has_docstring);
1797
0
    VISIT_IN_SCOPE(c, expr, s->v.TypeAlias.value);
1798
0
    ADDOP_IN_SCOPE(c, loc, RETURN_VALUE);
1799
0
    PyCodeObject *co = _PyCompile_OptimizeAndAssemble(c, 0);
1800
0
    _PyCompile_ExitScope(c);
1801
0
    if (co == NULL) {
1802
0
        return ERROR;
1803
0
    }
1804
0
    if (codegen_rename_annotations_format_param(co) < 0) {
1805
0
        Py_DECREF(co);
1806
0
        return ERROR;
1807
0
    }
1808
0
    int ret = codegen_make_closure(c, loc, co, MAKE_FUNCTION_DEFAULTS);
1809
0
    Py_DECREF(co);
1810
0
    RETURN_IF_ERROR(ret);
1811
1812
0
    ADDOP_I(c, loc, BUILD_TUPLE, 3);
1813
0
    ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_TYPEALIAS);
1814
0
    return SUCCESS;
1815
0
}
1816
1817
static int
1818
codegen_typealias(compiler *c, stmt_ty s)
1819
0
{
1820
0
    location loc = LOC(s);
1821
0
    asdl_type_param_seq *type_params = s->v.TypeAlias.type_params;
1822
0
    int is_generic = asdl_seq_LEN(type_params) > 0;
1823
0
    PyObject *name = s->v.TypeAlias.name->v.Name.id;
1824
0
    if (is_generic) {
1825
0
        PyObject *type_params_name = PyUnicode_FromFormat("<generic parameters of %U>",
1826
0
                                                         name);
1827
0
        if (!type_params_name) {
1828
0
            return ERROR;
1829
0
        }
1830
0
        int ret = codegen_enter_scope(c, type_params_name, COMPILE_SCOPE_ANNOTATIONS,
1831
0
                                      (void *)type_params, loc.lineno, NULL, NULL);
1832
0
        Py_DECREF(type_params_name);
1833
0
        RETURN_IF_ERROR(ret);
1834
0
        ADDOP_LOAD_CONST_IN_SCOPE(c, loc, name);
1835
0
        RETURN_IF_ERROR_IN_SCOPE(c, codegen_type_params(c, type_params));
1836
0
    }
1837
0
    else {
1838
0
        ADDOP_LOAD_CONST(c, loc, name);
1839
0
        ADDOP_LOAD_CONST(c, loc, Py_None);
1840
0
    }
1841
1842
0
    int ret = codegen_typealias_body(c, s);
1843
0
    if (is_generic) {
1844
0
        RETURN_IF_ERROR_IN_SCOPE(c, ret);
1845
0
    }
1846
0
    else {
1847
0
        RETURN_IF_ERROR(ret);
1848
0
    }
1849
1850
0
    if (is_generic) {
1851
0
        PyCodeObject *co = _PyCompile_OptimizeAndAssemble(c, 0);
1852
0
        _PyCompile_ExitScope(c);
1853
0
        if (co == NULL) {
1854
0
            return ERROR;
1855
0
        }
1856
0
        int ret = codegen_make_closure(c, loc, co, 0);
1857
0
        Py_DECREF(co);
1858
0
        RETURN_IF_ERROR(ret);
1859
0
        ADDOP(c, loc, PUSH_NULL);
1860
0
        ADDOP_I(c, loc, CALL, 0);
1861
0
    }
1862
0
    RETURN_IF_ERROR(codegen_nameop(c, loc, name, Store));
1863
0
    return SUCCESS;
1864
0
}
1865
1866
static bool
1867
is_const_tuple(asdl_expr_seq *elts)
1868
14
{
1869
30
    for (Py_ssize_t i = 0; i < asdl_seq_LEN(elts); i++) {
1870
24
        expr_ty e = (expr_ty)asdl_seq_GET(elts, i);
1871
24
        if (e->kind != Constant_kind) {
1872
8
            return false;
1873
8
        }
1874
24
    }
1875
6
    return true;
1876
14
}
1877
1878
/* Return false if the expression is a constant value except named singletons.
1879
   Return true otherwise. */
1880
static bool
1881
check_is_arg(expr_ty e)
1882
3.71k
{
1883
3.71k
    if (e->kind == Tuple_kind) {
1884
14
        return !is_const_tuple(e->v.Tuple.elts);
1885
14
    }
1886
3.69k
    if (e->kind != Constant_kind) {
1887
3.20k
        return true;
1888
3.20k
    }
1889
490
    PyObject *value = e->v.Constant.value;
1890
490
    return (value == Py_None
1891
490
         || value == Py_False
1892
490
         || value == Py_True
1893
291
         || value == Py_Ellipsis);
1894
3.69k
}
1895
1896
static PyTypeObject * infer_type(expr_ty e);
1897
1898
/* Check operands of identity checks ("is" and "is not").
1899
   Emit a warning if any operand is a constant except named singletons.
1900
 */
1901
static int
1902
codegen_check_compare(compiler *c, expr_ty e)
1903
1.84k
{
1904
1.84k
    Py_ssize_t i, n;
1905
1.84k
    bool left = check_is_arg(e->v.Compare.left);
1906
1.84k
    expr_ty left_expr = e->v.Compare.left;
1907
1.84k
    n = asdl_seq_LEN(e->v.Compare.ops);
1908
3.71k
    for (i = 0; i < n; i++) {
1909
1.86k
        cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
1910
1.86k
        expr_ty right_expr = (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i);
1911
1.86k
        bool right = check_is_arg(right_expr);
1912
1.86k
        if (op == Is || op == IsNot) {
1913
583
            if (!right || !left) {
1914
0
                const char *msg = (op == Is)
1915
0
                        ? "\"is\" with '%.200s' literal. Did you mean \"==\"?"
1916
0
                        : "\"is not\" with '%.200s' literal. Did you mean \"!=\"?";
1917
0
                expr_ty literal = !left ? left_expr : right_expr;
1918
0
                return _PyCompile_Warn(
1919
0
                    c, LOC(e), msg, infer_type(literal)->tp_name
1920
0
                );
1921
0
            }
1922
583
        }
1923
1.86k
        left = right;
1924
1.86k
        left_expr = right_expr;
1925
1.86k
    }
1926
1.84k
    return SUCCESS;
1927
1.84k
}
1928
1929
static int
1930
codegen_addcompare(compiler *c, location loc, cmpop_ty op)
1931
1.87k
{
1932
1.87k
    int cmp;
1933
1.87k
    switch (op) {
1934
865
    case Eq:
1935
865
        cmp = Py_EQ;
1936
865
        break;
1937
46
    case NotEq:
1938
46
        cmp = Py_NE;
1939
46
        break;
1940
59
    case Lt:
1941
59
        cmp = Py_LT;
1942
59
        break;
1943
34
    case LtE:
1944
34
        cmp = Py_LE;
1945
34
        break;
1946
35
    case Gt:
1947
35
        cmp = Py_GT;
1948
35
        break;
1949
17
    case GtE:
1950
17
        cmp = Py_GE;
1951
17
        break;
1952
485
    case Is:
1953
485
        ADDOP_I(c, loc, IS_OP, 0);
1954
485
        return SUCCESS;
1955
110
    case IsNot:
1956
110
        ADDOP_I(c, loc, IS_OP, 1);
1957
110
        return SUCCESS;
1958
198
    case In:
1959
198
        ADDOP_I(c, loc, CONTAINS_OP, 0);
1960
198
        return SUCCESS;
1961
27
    case NotIn:
1962
27
        ADDOP_I(c, loc, CONTAINS_OP, 1);
1963
27
        return SUCCESS;
1964
0
    default:
1965
0
        Py_UNREACHABLE();
1966
1.87k
    }
1967
    // cmp goes in top three bits of the oparg, while the low four bits are used
1968
    // by quickened versions of this opcode to store the comparison mask. The
1969
    // fifth-lowest bit indicates whether the result should be converted to bool
1970
    // and is set later):
1971
1.05k
    ADDOP_I(c, loc, COMPARE_OP, (cmp << 5) | compare_masks[cmp]);
1972
1.05k
    return SUCCESS;
1973
1.05k
}
1974
1975
static int
1976
codegen_jump_if(compiler *c, location loc,
1977
                expr_ty e, jump_target_label next, int cond)
1978
2.41k
{
1979
2.41k
    switch (e->kind) {
1980
178
    case UnaryOp_kind:
1981
178
        if (e->v.UnaryOp.op == Not) {
1982
178
            return codegen_jump_if(c, loc, e->v.UnaryOp.operand, next, !cond);
1983
178
        }
1984
        /* fallback to general implementation */
1985
0
        break;
1986
264
    case BoolOp_kind: {
1987
264
        asdl_expr_seq *s = e->v.BoolOp.values;
1988
264
        Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
1989
264
        assert(n >= 0);
1990
264
        int cond2 = e->v.BoolOp.op == Or;
1991
264
        jump_target_label next2 = next;
1992
264
        if (!cond2 != !cond) {
1993
168
            NEW_JUMP_TARGET_LABEL(c, new_next2);
1994
168
            next2 = new_next2;
1995
168
        }
1996
546
        for (i = 0; i < n; ++i) {
1997
282
            RETURN_IF_ERROR(
1998
282
                codegen_jump_if(c, loc, (expr_ty)asdl_seq_GET(s, i), next2, cond2));
1999
282
        }
2000
264
        RETURN_IF_ERROR(
2001
264
            codegen_jump_if(c, loc, (expr_ty)asdl_seq_GET(s, n), next, cond));
2002
264
        if (!SAME_JUMP_TARGET_LABEL(next2, next)) {
2003
168
            USE_LABEL(c, next2);
2004
168
        }
2005
264
        return SUCCESS;
2006
264
    }
2007
0
    case IfExp_kind: {
2008
0
        NEW_JUMP_TARGET_LABEL(c, end);
2009
0
        NEW_JUMP_TARGET_LABEL(c, next2);
2010
0
        RETURN_IF_ERROR(
2011
0
            codegen_jump_if(c, loc, e->v.IfExp.test, next2, 0));
2012
0
        RETURN_IF_ERROR(
2013
0
            codegen_jump_if(c, loc, e->v.IfExp.body, next, cond));
2014
0
        ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
2015
2016
0
        USE_LABEL(c, next2);
2017
0
        RETURN_IF_ERROR(
2018
0
            codegen_jump_if(c, loc, e->v.IfExp.orelse, next, cond));
2019
2020
0
        USE_LABEL(c, end);
2021
0
        return SUCCESS;
2022
0
    }
2023
1.20k
    case Compare_kind: {
2024
1.20k
        Py_ssize_t n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2025
1.20k
        if (n > 0) {
2026
10
            RETURN_IF_ERROR(codegen_check_compare(c, e));
2027
10
            NEW_JUMP_TARGET_LABEL(c, cleanup);
2028
10
            VISIT(c, expr, e->v.Compare.left);
2029
20
            for (Py_ssize_t i = 0; i < n; i++) {
2030
10
                VISIT(c, expr,
2031
10
                    (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2032
10
                ADDOP_I(c, LOC(e), SWAP, 2);
2033
10
                ADDOP_I(c, LOC(e), COPY, 2);
2034
10
                ADDOP_COMPARE(c, LOC(e), asdl_seq_GET(e->v.Compare.ops, i));
2035
10
                ADDOP(c, LOC(e), TO_BOOL);
2036
10
                ADDOP_JUMP(c, LOC(e), POP_JUMP_IF_FALSE, cleanup);
2037
10
            }
2038
10
            VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
2039
10
            ADDOP_COMPARE(c, LOC(e), asdl_seq_GET(e->v.Compare.ops, n));
2040
10
            ADDOP(c, LOC(e), TO_BOOL);
2041
10
            ADDOP_JUMP(c, LOC(e), cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2042
10
            NEW_JUMP_TARGET_LABEL(c, end);
2043
10
            ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
2044
2045
10
            USE_LABEL(c, cleanup);
2046
10
            ADDOP(c, LOC(e), POP_TOP);
2047
10
            if (!cond) {
2048
7
                ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, next);
2049
7
            }
2050
2051
10
            USE_LABEL(c, end);
2052
10
            return SUCCESS;
2053
10
        }
2054
        /* fallback to general implementation */
2055
1.19k
        break;
2056
1.20k
    }
2057
1.19k
    default:
2058
        /* fallback to general implementation */
2059
772
        break;
2060
2.41k
    }
2061
2062
    /* general implementation */
2063
1.96k
    VISIT(c, expr, e);
2064
1.96k
    ADDOP(c, LOC(e), TO_BOOL);
2065
1.96k
    ADDOP_JUMP(c, LOC(e), cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
2066
1.96k
    return SUCCESS;
2067
1.96k
}
2068
2069
static int
2070
codegen_ifexp(compiler *c, expr_ty e)
2071
71
{
2072
71
    assert(e->kind == IfExp_kind);
2073
71
    NEW_JUMP_TARGET_LABEL(c, end);
2074
71
    NEW_JUMP_TARGET_LABEL(c, next);
2075
2076
71
    RETURN_IF_ERROR(
2077
71
        codegen_jump_if(c, LOC(e), e->v.IfExp.test, next, 0));
2078
2079
71
    VISIT(c, expr, e->v.IfExp.body);
2080
71
    ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
2081
2082
71
    USE_LABEL(c, next);
2083
71
    VISIT(c, expr, e->v.IfExp.orelse);
2084
2085
71
    USE_LABEL(c, end);
2086
71
    return SUCCESS;
2087
71
}
2088
2089
static int
2090
codegen_lambda(compiler *c, expr_ty e)
2091
198
{
2092
198
    PyCodeObject *co;
2093
198
    Py_ssize_t funcflags;
2094
198
    arguments_ty args = e->v.Lambda.args;
2095
198
    assert(e->kind == Lambda_kind);
2096
2097
198
    location loc = LOC(e);
2098
198
    funcflags = codegen_default_arguments(c, loc, args);
2099
198
    RETURN_IF_ERROR(funcflags);
2100
2101
198
    _PyCompile_CodeUnitMetadata umd = {
2102
198
        .u_argcount = asdl_seq_LEN(args->args),
2103
198
        .u_posonlyargcount = asdl_seq_LEN(args->posonlyargs),
2104
198
        .u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs),
2105
198
    };
2106
198
    _Py_DECLARE_STR(anon_lambda, "<lambda>");
2107
198
    RETURN_IF_ERROR(
2108
198
        codegen_enter_scope(c, &_Py_STR(anon_lambda), COMPILE_SCOPE_LAMBDA,
2109
198
                            (void *)e, e->lineno, NULL, &umd));
2110
2111
198
    assert(!SYMTABLE_ENTRY(c)->ste_has_docstring);
2112
2113
198
    VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2114
198
    if (SYMTABLE_ENTRY(c)->ste_generator) {
2115
0
        co = _PyCompile_OptimizeAndAssemble(c, 0);
2116
0
    }
2117
198
    else {
2118
198
        location loc = LOC(e->v.Lambda.body);
2119
198
        ADDOP_IN_SCOPE(c, loc, RETURN_VALUE);
2120
198
        co = _PyCompile_OptimizeAndAssemble(c, 1);
2121
198
    }
2122
198
    _PyCompile_ExitScope(c);
2123
198
    if (co == NULL) {
2124
0
        return ERROR;
2125
0
    }
2126
2127
198
    int ret = codegen_make_closure(c, loc, co, funcflags);
2128
198
    Py_DECREF(co);
2129
198
    RETURN_IF_ERROR(ret);
2130
198
    return SUCCESS;
2131
198
}
2132
2133
static int
2134
codegen_if(compiler *c, stmt_ty s)
2135
1.53k
{
2136
1.53k
    jump_target_label next;
2137
1.53k
    assert(s->kind == If_kind);
2138
1.53k
    NEW_JUMP_TARGET_LABEL(c, end);
2139
1.53k
    if (asdl_seq_LEN(s->v.If.orelse)) {
2140
370
        NEW_JUMP_TARGET_LABEL(c, orelse);
2141
370
        next = orelse;
2142
370
    }
2143
1.16k
    else {
2144
1.16k
        next = end;
2145
1.16k
    }
2146
1.53k
    RETURN_IF_ERROR(
2147
1.53k
        codegen_jump_if(c, LOC(s), s->v.If.test, next, 0));
2148
2149
1.53k
    VISIT_SEQ(c, stmt, s->v.If.body);
2150
1.53k
    if (asdl_seq_LEN(s->v.If.orelse)) {
2151
370
        ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
2152
2153
370
        USE_LABEL(c, next);
2154
370
        VISIT_SEQ(c, stmt, s->v.If.orelse);
2155
370
    }
2156
2157
1.53k
    USE_LABEL(c, end);
2158
1.53k
    return SUCCESS;
2159
1.53k
}
2160
2161
static int
2162
codegen_for(compiler *c, stmt_ty s)
2163
183
{
2164
183
    location loc = LOC(s);
2165
183
    NEW_JUMP_TARGET_LABEL(c, start);
2166
183
    NEW_JUMP_TARGET_LABEL(c, body);
2167
183
    NEW_JUMP_TARGET_LABEL(c, cleanup);
2168
183
    NEW_JUMP_TARGET_LABEL(c, end);
2169
2170
183
    RETURN_IF_ERROR(_PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_FOR_LOOP, start, end, NULL));
2171
2172
183
    VISIT(c, expr, s->v.For.iter);
2173
2174
183
    loc = LOC(s->v.For.iter);
2175
183
    ADDOP_I(c, loc, GET_ITER, 0);
2176
2177
183
    USE_LABEL(c, start);
2178
183
    ADDOP_JUMP(c, loc, FOR_ITER, cleanup);
2179
2180
    /* Add NOP to ensure correct line tracing of multiline for statements.
2181
     * It will be removed later if redundant.
2182
     */
2183
183
    ADDOP(c, LOC(s->v.For.target), NOP);
2184
2185
183
    USE_LABEL(c, body);
2186
183
    VISIT(c, expr, s->v.For.target);
2187
183
    VISIT_SEQ(c, stmt, s->v.For.body);
2188
    /* Mark jump as artificial */
2189
183
    ADDOP_JUMP(c, NO_LOCATION, JUMP, start);
2190
2191
183
    USE_LABEL(c, cleanup);
2192
    /* It is important for instrumentation that the `END_FOR` comes first.
2193
    * Iteration over a generator will jump to the first of these instructions,
2194
    * but a non-generator will jump to the second instruction.
2195
    */
2196
183
    ADDOP(c, NO_LOCATION, END_FOR);
2197
183
    ADDOP(c, NO_LOCATION, POP_ITER);
2198
2199
183
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_FOR_LOOP, start);
2200
2201
183
    VISIT_SEQ(c, stmt, s->v.For.orelse);
2202
2203
183
    USE_LABEL(c, end);
2204
183
    return SUCCESS;
2205
183
}
2206
2207
static int
2208
codegen_async_for(compiler *c, stmt_ty s)
2209
0
{
2210
0
    location loc = LOC(s);
2211
2212
0
    NEW_JUMP_TARGET_LABEL(c, start);
2213
0
    NEW_JUMP_TARGET_LABEL(c, send);
2214
0
    NEW_JUMP_TARGET_LABEL(c, except);
2215
0
    NEW_JUMP_TARGET_LABEL(c, end);
2216
2217
0
    VISIT(c, expr, s->v.AsyncFor.iter);
2218
0
    ADDOP(c, LOC(s->v.AsyncFor.iter), GET_AITER);
2219
2220
0
    USE_LABEL(c, start);
2221
0
    RETURN_IF_ERROR(_PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_ASYNC_FOR_LOOP, start, end, NULL));
2222
2223
    /* SETUP_FINALLY to guard the __anext__ call */
2224
0
    ADDOP_JUMP(c, loc, SETUP_FINALLY, except);
2225
0
    ADDOP(c, loc, GET_ANEXT);
2226
0
    USE_LABEL(c, send);
2227
0
    ADD_YIELD_FROM(c, loc, 1);
2228
0
    ADDOP(c, loc, POP_BLOCK);  /* for SETUP_FINALLY */
2229
0
    ADDOP(c, loc, NOT_TAKEN);
2230
2231
    /* Success block for __anext__ */
2232
0
    VISIT(c, expr, s->v.AsyncFor.target);
2233
0
    VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
2234
    /* Mark jump as artificial */
2235
0
    ADDOP_JUMP(c, NO_LOCATION, JUMP, start);
2236
2237
0
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_ASYNC_FOR_LOOP, start);
2238
2239
    /* Except block for __anext__ */
2240
0
    USE_LABEL(c, except);
2241
2242
    /* Use same line number as the iterator,
2243
     * as the END_ASYNC_FOR succeeds the `for`, not the body. */
2244
0
    loc = LOC(s->v.AsyncFor.iter);
2245
0
    ADDOP_JUMP(c, loc, END_ASYNC_FOR, send);
2246
2247
    /* `else` block */
2248
0
    VISIT_SEQ(c, stmt, s->v.AsyncFor.orelse);
2249
2250
0
    USE_LABEL(c, end);
2251
0
    return SUCCESS;
2252
0
}
2253
2254
static int
2255
codegen_while(compiler *c, stmt_ty s)
2256
33
{
2257
33
    NEW_JUMP_TARGET_LABEL(c, loop);
2258
33
    NEW_JUMP_TARGET_LABEL(c, end);
2259
33
    NEW_JUMP_TARGET_LABEL(c, anchor);
2260
2261
33
    USE_LABEL(c, loop);
2262
2263
33
    RETURN_IF_ERROR(_PyCompile_PushFBlock(c, LOC(s), COMPILE_FBLOCK_WHILE_LOOP, loop, end, NULL));
2264
33
    RETURN_IF_ERROR(codegen_jump_if(c, LOC(s), s->v.While.test, anchor, 0));
2265
2266
33
    VISIT_SEQ(c, stmt, s->v.While.body);
2267
33
    ADDOP_JUMP(c, NO_LOCATION, JUMP, loop);
2268
2269
33
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_WHILE_LOOP, loop);
2270
2271
33
    USE_LABEL(c, anchor);
2272
33
    if (s->v.While.orelse) {
2273
0
        VISIT_SEQ(c, stmt, s->v.While.orelse);
2274
0
    }
2275
2276
33
    USE_LABEL(c, end);
2277
33
    return SUCCESS;
2278
33
}
2279
2280
static int
2281
codegen_return(compiler *c, stmt_ty s)
2282
2.02k
{
2283
2.02k
    location loc = LOC(s);
2284
2.02k
    int preserve_tos = ((s->v.Return.value != NULL) &&
2285
1.90k
                        (s->v.Return.value->kind != Constant_kind));
2286
2287
2.02k
    PySTEntryObject *ste = SYMTABLE_ENTRY(c);
2288
2.02k
    if (!_PyST_IsFunctionLike(ste)) {
2289
0
        return _PyCompile_Error(c, loc, "'return' outside function");
2290
0
    }
2291
2.02k
    if (s->v.Return.value != NULL && ste->ste_coroutine && ste->ste_generator) {
2292
0
        return _PyCompile_Error(c, loc, "'return' with value in async generator");
2293
0
    }
2294
2295
2.02k
    if (preserve_tos) {
2296
1.75k
        VISIT(c, expr, s->v.Return.value);
2297
1.75k
    } else {
2298
        /* Emit instruction with line number for return value */
2299
269
        if (s->v.Return.value != NULL) {
2300
147
            loc = LOC(s->v.Return.value);
2301
147
            ADDOP(c, loc, NOP);
2302
147
        }
2303
269
    }
2304
2.02k
    if (s->v.Return.value == NULL || s->v.Return.value->lineno != s->lineno) {
2305
124
        loc = LOC(s);
2306
124
        ADDOP(c, loc, NOP);
2307
124
    }
2308
2309
2.02k
    RETURN_IF_ERROR(codegen_unwind_fblock_stack(c, &loc, preserve_tos, NULL));
2310
2.02k
    if (s->v.Return.value == NULL) {
2311
122
        ADDOP_LOAD_CONST(c, loc, Py_None);
2312
122
    }
2313
1.90k
    else if (!preserve_tos) {
2314
147
        ADDOP_LOAD_CONST(c, loc, s->v.Return.value->v.Constant.value);
2315
147
    }
2316
2.02k
    ADDOP(c, loc, RETURN_VALUE);
2317
2318
2.02k
    return SUCCESS;
2319
2.02k
}
2320
2321
static int
2322
codegen_break(compiler *c, location loc)
2323
22
{
2324
22
    fblockinfo *loop = NULL;
2325
22
    location origin_loc = loc;
2326
    /* Emit instruction with line number */
2327
22
    ADDOP(c, loc, NOP);
2328
22
    RETURN_IF_ERROR(codegen_unwind_fblock_stack(c, &loc, 0, &loop));
2329
22
    if (loop == NULL) {
2330
0
        return _PyCompile_Error(c, origin_loc, "'break' outside loop");
2331
0
    }
2332
22
    RETURN_IF_ERROR(codegen_unwind_fblock(c, &loc, loop, 0));
2333
22
    ADDOP_JUMP(c, loc, JUMP, loop->fb_exit);
2334
22
    return SUCCESS;
2335
22
}
2336
2337
static int
2338
codegen_continue(compiler *c, location loc)
2339
19
{
2340
19
    fblockinfo *loop = NULL;
2341
19
    location origin_loc = loc;
2342
    /* Emit instruction with line number */
2343
19
    ADDOP(c, loc, NOP);
2344
19
    RETURN_IF_ERROR(codegen_unwind_fblock_stack(c, &loc, 0, &loop));
2345
19
    if (loop == NULL) {
2346
0
        return _PyCompile_Error(c, origin_loc, "'continue' not properly in loop");
2347
0
    }
2348
19
    ADDOP_JUMP(c, loc, JUMP, loop->fb_block);
2349
19
    return SUCCESS;
2350
19
}
2351
2352
2353
/* Code generated for "try: <body> finally: <finalbody>" is as follows:
2354
2355
        SETUP_FINALLY           L
2356
        <code for body>
2357
        POP_BLOCK
2358
        <code for finalbody>
2359
        JUMP E
2360
    L:
2361
        <code for finalbody>
2362
    E:
2363
2364
   The special instructions use the block stack.  Each block
2365
   stack entry contains the instruction that created it (here
2366
   SETUP_FINALLY), the level of the value stack at the time the
2367
   block stack entry was created, and a label (here L).
2368
2369
   SETUP_FINALLY:
2370
    Pushes the current value stack level and the label
2371
    onto the block stack.
2372
   POP_BLOCK:
2373
    Pops en entry from the block stack.
2374
2375
   The block stack is unwound when an exception is raised:
2376
   when a SETUP_FINALLY entry is found, the raised and the caught
2377
   exceptions are pushed onto the value stack (and the exception
2378
   condition is cleared), and the interpreter jumps to the label
2379
   gotten from the block stack.
2380
*/
2381
2382
static int
2383
codegen_try_finally(compiler *c, stmt_ty s)
2384
29
{
2385
29
    location loc = LOC(s);
2386
2387
29
    NEW_JUMP_TARGET_LABEL(c, body);
2388
29
    NEW_JUMP_TARGET_LABEL(c, end);
2389
29
    NEW_JUMP_TARGET_LABEL(c, exit);
2390
29
    NEW_JUMP_TARGET_LABEL(c, cleanup);
2391
2392
    /* `try` block */
2393
29
    ADDOP_JUMP(c, loc, SETUP_FINALLY, end);
2394
2395
29
    USE_LABEL(c, body);
2396
29
    RETURN_IF_ERROR(
2397
29
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_FINALLY_TRY, body, end,
2398
29
                              s->v.Try.finalbody));
2399
2400
29
    if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2401
5
        RETURN_IF_ERROR(codegen_try_except(c, s));
2402
5
    }
2403
24
    else {
2404
24
        VISIT_SEQ(c, stmt, s->v.Try.body);
2405
24
    }
2406
29
    ADDOP(c, NO_LOCATION, POP_BLOCK);
2407
29
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_FINALLY_TRY, body);
2408
29
    VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2409
2410
29
    ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, exit);
2411
    /* `finally` block */
2412
2413
29
    USE_LABEL(c, end);
2414
2415
29
    loc = NO_LOCATION;
2416
29
    ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup);
2417
29
    ADDOP(c, loc, PUSH_EXC_INFO);
2418
29
    RETURN_IF_ERROR(
2419
29
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_FINALLY_END, end, NO_LABEL, NULL));
2420
29
    VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2421
29
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_FINALLY_END, end);
2422
2423
29
    loc = NO_LOCATION;
2424
29
    ADDOP_I(c, loc, RERAISE, 0);
2425
2426
29
    USE_LABEL(c, cleanup);
2427
29
    POP_EXCEPT_AND_RERAISE(c, loc);
2428
2429
29
    USE_LABEL(c, exit);
2430
29
    return SUCCESS;
2431
29
}
2432
2433
static int
2434
codegen_try_star_finally(compiler *c, stmt_ty s)
2435
0
{
2436
0
    location loc = LOC(s);
2437
2438
0
    NEW_JUMP_TARGET_LABEL(c, body);
2439
0
    NEW_JUMP_TARGET_LABEL(c, end);
2440
0
    NEW_JUMP_TARGET_LABEL(c, exit);
2441
0
    NEW_JUMP_TARGET_LABEL(c, cleanup);
2442
    /* `try` block */
2443
0
    ADDOP_JUMP(c, loc, SETUP_FINALLY, end);
2444
2445
0
    USE_LABEL(c, body);
2446
0
    RETURN_IF_ERROR(
2447
0
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_FINALLY_TRY, body, end,
2448
0
                              s->v.TryStar.finalbody));
2449
2450
0
    if (s->v.TryStar.handlers && asdl_seq_LEN(s->v.TryStar.handlers)) {
2451
0
        RETURN_IF_ERROR(codegen_try_star_except(c, s));
2452
0
    }
2453
0
    else {
2454
0
        VISIT_SEQ(c, stmt, s->v.TryStar.body);
2455
0
    }
2456
0
    ADDOP(c, NO_LOCATION, POP_BLOCK);
2457
0
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_FINALLY_TRY, body);
2458
0
    VISIT_SEQ(c, stmt, s->v.TryStar.finalbody);
2459
2460
0
    ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, exit);
2461
2462
    /* `finally` block */
2463
0
    USE_LABEL(c, end);
2464
2465
0
    loc = NO_LOCATION;
2466
0
    ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup);
2467
0
    ADDOP(c, loc, PUSH_EXC_INFO);
2468
0
    RETURN_IF_ERROR(
2469
0
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_FINALLY_END, end, NO_LABEL, NULL));
2470
2471
0
    VISIT_SEQ(c, stmt, s->v.TryStar.finalbody);
2472
2473
0
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_FINALLY_END, end);
2474
0
    loc = NO_LOCATION;
2475
0
    ADDOP_I(c, loc, RERAISE, 0);
2476
2477
0
    USE_LABEL(c, cleanup);
2478
0
    POP_EXCEPT_AND_RERAISE(c, loc);
2479
2480
0
    USE_LABEL(c, exit);
2481
0
    return SUCCESS;
2482
0
}
2483
2484
2485
/*
2486
   Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
2487
   (The contents of the value stack is shown in [], with the top
2488
   at the right; 'tb' is trace-back info, 'val' the exception's
2489
   associated value, and 'exc' the exception.)
2490
2491
   Value stack          Label   Instruction     Argument
2492
   []                           SETUP_FINALLY   L1
2493
   []                           <code for S>
2494
   []                           POP_BLOCK
2495
   []                           JUMP            L0
2496
2497
   [exc]                L1:     <evaluate E1>           )
2498
   [exc, E1]                    CHECK_EXC_MATCH         )
2499
   [exc, bool]                  POP_JUMP_IF_FALSE L2    ) only if E1
2500
   [exc]                        <assign to V1>  (or POP if no V1)
2501
   []                           <code for S1>
2502
                                JUMP            L0
2503
2504
   [exc]                L2:     <evaluate E2>
2505
   .............................etc.......................
2506
2507
   [exc]                Ln+1:   RERAISE     # re-raise exception
2508
2509
   []                   L0:     <next statement>
2510
2511
   Of course, parts are not generated if Vi or Ei is not present.
2512
*/
2513
static int
2514
codegen_try_except(compiler *c, stmt_ty s)
2515
153
{
2516
153
    location loc = LOC(s);
2517
153
    Py_ssize_t i, n;
2518
2519
153
    NEW_JUMP_TARGET_LABEL(c, body);
2520
153
    NEW_JUMP_TARGET_LABEL(c, except);
2521
153
    NEW_JUMP_TARGET_LABEL(c, end);
2522
153
    NEW_JUMP_TARGET_LABEL(c, cleanup);
2523
2524
153
    ADDOP_JUMP(c, loc, SETUP_FINALLY, except);
2525
2526
153
    USE_LABEL(c, body);
2527
153
    RETURN_IF_ERROR(
2528
153
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_TRY_EXCEPT, body, NO_LABEL, NULL));
2529
153
    VISIT_SEQ(c, stmt, s->v.Try.body);
2530
153
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_TRY_EXCEPT, body);
2531
153
    ADDOP(c, NO_LOCATION, POP_BLOCK);
2532
153
    if (s->v.Try.orelse && asdl_seq_LEN(s->v.Try.orelse)) {
2533
17
        VISIT_SEQ(c, stmt, s->v.Try.orelse);
2534
17
    }
2535
153
    ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
2536
153
    n = asdl_seq_LEN(s->v.Try.handlers);
2537
2538
153
    USE_LABEL(c, except);
2539
2540
153
    ADDOP_JUMP(c, NO_LOCATION, SETUP_CLEANUP, cleanup);
2541
153
    ADDOP(c, NO_LOCATION, PUSH_EXC_INFO);
2542
2543
    /* Runtime will push a block here, so we need to account for that */
2544
153
    RETURN_IF_ERROR(
2545
153
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_EXCEPTION_HANDLER,
2546
153
                              NO_LABEL, NO_LABEL, NULL));
2547
2548
348
    for (i = 0; i < n; i++) {
2549
195
        excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
2550
195
            s->v.Try.handlers, i);
2551
195
        location loc = LOC(handler);
2552
195
        if (!handler->v.ExceptHandler.type && i < n-1) {
2553
0
            return _PyCompile_Error(c, loc, "default 'except:' must be last");
2554
0
        }
2555
195
        NEW_JUMP_TARGET_LABEL(c, next_except);
2556
195
        except = next_except;
2557
195
        if (handler->v.ExceptHandler.type) {
2558
183
            VISIT(c, expr, handler->v.ExceptHandler.type);
2559
183
            ADDOP(c, loc, CHECK_EXC_MATCH);
2560
183
            ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, except);
2561
183
        }
2562
195
        if (handler->v.ExceptHandler.name) {
2563
28
            NEW_JUMP_TARGET_LABEL(c, cleanup_end);
2564
28
            NEW_JUMP_TARGET_LABEL(c, cleanup_body);
2565
2566
28
            RETURN_IF_ERROR(
2567
28
                codegen_nameop(c, loc, handler->v.ExceptHandler.name, Store));
2568
2569
            /*
2570
              try:
2571
                  # body
2572
              except type as name:
2573
                  try:
2574
                      # body
2575
                  finally:
2576
                      name = None # in case body contains "del name"
2577
                      del name
2578
            */
2579
2580
            /* second try: */
2581
28
            ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup_end);
2582
2583
28
            USE_LABEL(c, cleanup_body);
2584
28
            RETURN_IF_ERROR(
2585
28
                _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_HANDLER_CLEANUP, cleanup_body,
2586
28
                                      NO_LABEL, handler->v.ExceptHandler.name));
2587
2588
            /* second # body */
2589
28
            VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2590
28
            _PyCompile_PopFBlock(c, COMPILE_FBLOCK_HANDLER_CLEANUP, cleanup_body);
2591
            /* name = None; del name; # Mark as artificial */
2592
28
            ADDOP(c, NO_LOCATION, POP_BLOCK);
2593
28
            ADDOP(c, NO_LOCATION, POP_BLOCK);
2594
28
            ADDOP(c, NO_LOCATION, POP_EXCEPT);
2595
28
            ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
2596
28
            RETURN_IF_ERROR(
2597
28
                codegen_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Store));
2598
28
            RETURN_IF_ERROR(
2599
28
                codegen_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Del));
2600
28
            ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
2601
2602
            /* except: */
2603
28
            USE_LABEL(c, cleanup_end);
2604
2605
            /* name = None; del name; # artificial */
2606
28
            ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
2607
28
            RETURN_IF_ERROR(
2608
28
                codegen_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Store));
2609
28
            RETURN_IF_ERROR(
2610
28
                codegen_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Del));
2611
2612
28
            ADDOP_I(c, NO_LOCATION, RERAISE, 1);
2613
28
        }
2614
167
        else {
2615
167
            NEW_JUMP_TARGET_LABEL(c, cleanup_body);
2616
2617
167
            ADDOP(c, loc, POP_TOP); /* exc_value */
2618
2619
167
            USE_LABEL(c, cleanup_body);
2620
167
            RETURN_IF_ERROR(
2621
167
                _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_HANDLER_CLEANUP, cleanup_body,
2622
167
                                      NO_LABEL, NULL));
2623
2624
167
            VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2625
167
            _PyCompile_PopFBlock(c, COMPILE_FBLOCK_HANDLER_CLEANUP, cleanup_body);
2626
167
            ADDOP(c, NO_LOCATION, POP_BLOCK);
2627
167
            ADDOP(c, NO_LOCATION, POP_EXCEPT);
2628
167
            ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
2629
167
        }
2630
2631
195
        USE_LABEL(c, except);
2632
195
    }
2633
    /* artificial */
2634
153
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_EXCEPTION_HANDLER, NO_LABEL);
2635
153
    ADDOP_I(c, NO_LOCATION, RERAISE, 0);
2636
2637
153
    USE_LABEL(c, cleanup);
2638
153
    POP_EXCEPT_AND_RERAISE(c, NO_LOCATION);
2639
2640
153
    USE_LABEL(c, end);
2641
153
    return SUCCESS;
2642
153
}
2643
2644
/*
2645
   Code generated for "try: S except* E1 as V1: S1 except* E2 as V2: S2 ...":
2646
   (The contents of the value stack is shown in [], with the top
2647
   at the right; 'tb' is trace-back info, 'val' the exception instance,
2648
   and 'typ' the exception's type.)
2649
2650
   Value stack                   Label         Instruction     Argument
2651
   []                                         SETUP_FINALLY         L1
2652
   []                                         <code for S>
2653
   []                                         POP_BLOCK
2654
   []                                         JUMP                  L0
2655
2656
   [exc]                            L1:       BUILD_LIST   )  list for raised/reraised excs ("result")
2657
   [orig, res]                                COPY 2       )  make a copy of the original EG
2658
2659
   [orig, res, exc]                           <evaluate E1>
2660
   [orig, res, exc, E1]                       CHECK_EG_MATCH
2661
   [orig, res, rest/exc, match?]              COPY 1
2662
   [orig, res, rest/exc, match?, match?]      POP_JUMP_IF_NONE      C1
2663
2664
   [orig, res, rest, match]                   <assign to V1>  (or POP if no V1)
2665
2666
   [orig, res, rest]                          SETUP_FINALLY         R1
2667
   [orig, res, rest]                          <code for S1>
2668
   [orig, res, rest]                          JUMP                  L2
2669
2670
   [orig, res, rest, i, v]          R1:       LIST_APPEND   3 ) exc raised in except* body - add to res
2671
   [orig, res, rest, i]                       POP
2672
   [orig, res, rest]                          JUMP                  LE2
2673
2674
   [orig, res, rest]                L2:       NOP  ) for lineno
2675
   [orig, res, rest]                          JUMP                  LE2
2676
2677
   [orig, res, rest/exc, None]      C1:       POP
2678
2679
   [orig, res, rest]               LE2:       <evaluate E2>
2680
   .............................etc.......................
2681
2682
   [orig, res, rest]                Ln+1:     LIST_APPEND 1  ) add unhandled exc to res (could be None)
2683
2684
   [orig, res]                                CALL_INTRINSIC_2 PREP_RERAISE_STAR
2685
   [exc]                                      COPY 1
2686
   [exc, exc]                                 POP_JUMP_IF_NOT_NONE  RER
2687
   [exc]                                      POP_TOP
2688
   []                                         JUMP                  L0
2689
2690
   [exc]                            RER:      SWAP 2
2691
   [exc, prev_exc_info]                       POP_EXCEPT
2692
   [exc]                                      RERAISE               0
2693
2694
   []                               L0:       <next statement>
2695
*/
2696
static int
2697
codegen_try_star_except(compiler *c, stmt_ty s)
2698
0
{
2699
0
    location loc = LOC(s);
2700
2701
0
    NEW_JUMP_TARGET_LABEL(c, body);
2702
0
    NEW_JUMP_TARGET_LABEL(c, except);
2703
0
    NEW_JUMP_TARGET_LABEL(c, orelse);
2704
0
    NEW_JUMP_TARGET_LABEL(c, end);
2705
0
    NEW_JUMP_TARGET_LABEL(c, cleanup);
2706
0
    NEW_JUMP_TARGET_LABEL(c, reraise_star);
2707
2708
0
    ADDOP_JUMP(c, loc, SETUP_FINALLY, except);
2709
2710
0
    USE_LABEL(c, body);
2711
0
    RETURN_IF_ERROR(
2712
0
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_TRY_EXCEPT, body, NO_LABEL, NULL));
2713
0
    VISIT_SEQ(c, stmt, s->v.TryStar.body);
2714
0
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_TRY_EXCEPT, body);
2715
0
    ADDOP(c, NO_LOCATION, POP_BLOCK);
2716
0
    ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, orelse);
2717
0
    Py_ssize_t n = asdl_seq_LEN(s->v.TryStar.handlers);
2718
2719
0
    USE_LABEL(c, except);
2720
2721
0
    ADDOP_JUMP(c, NO_LOCATION, SETUP_CLEANUP, cleanup);
2722
0
    ADDOP(c, NO_LOCATION, PUSH_EXC_INFO);
2723
2724
    /* Runtime will push a block here, so we need to account for that */
2725
0
    RETURN_IF_ERROR(
2726
0
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_EXCEPTION_GROUP_HANDLER,
2727
0
                              NO_LABEL, NO_LABEL, "except handler"));
2728
2729
0
    for (Py_ssize_t i = 0; i < n; i++) {
2730
0
        excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
2731
0
            s->v.TryStar.handlers, i);
2732
0
        location loc = LOC(handler);
2733
0
        NEW_JUMP_TARGET_LABEL(c, next_except);
2734
0
        except = next_except;
2735
0
        NEW_JUMP_TARGET_LABEL(c, except_with_error);
2736
0
        NEW_JUMP_TARGET_LABEL(c, no_match);
2737
0
        if (i == 0) {
2738
            /* create empty list for exceptions raised/reraise in the except* blocks */
2739
            /*
2740
               [orig]       BUILD_LIST
2741
            */
2742
            /* Create a copy of the original EG */
2743
            /*
2744
               [orig, []]   COPY 2
2745
               [orig, [], exc]
2746
            */
2747
0
            ADDOP_I(c, loc, BUILD_LIST, 0);
2748
0
            ADDOP_I(c, loc, COPY, 2);
2749
0
        }
2750
0
        if (handler->v.ExceptHandler.type) {
2751
0
            VISIT(c, expr, handler->v.ExceptHandler.type);
2752
0
            ADDOP(c, loc, CHECK_EG_MATCH);
2753
0
            ADDOP_I(c, loc, COPY, 1);
2754
0
            ADDOP_JUMP(c, loc, POP_JUMP_IF_NONE, no_match);
2755
0
        }
2756
2757
0
        NEW_JUMP_TARGET_LABEL(c, cleanup_end);
2758
0
        NEW_JUMP_TARGET_LABEL(c, cleanup_body);
2759
2760
0
        if (handler->v.ExceptHandler.name) {
2761
0
            RETURN_IF_ERROR(
2762
0
                codegen_nameop(c, loc, handler->v.ExceptHandler.name, Store));
2763
0
        }
2764
0
        else {
2765
0
            ADDOP(c, loc, POP_TOP);  // match
2766
0
        }
2767
2768
        /*
2769
          try:
2770
              # body
2771
          except type as name:
2772
              try:
2773
                  # body
2774
              finally:
2775
                  name = None # in case body contains "del name"
2776
                  del name
2777
        */
2778
        /* second try: */
2779
0
        ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup_end);
2780
2781
0
        USE_LABEL(c, cleanup_body);
2782
0
        RETURN_IF_ERROR(
2783
0
            _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_HANDLER_CLEANUP, cleanup_body,
2784
0
                                  NO_LABEL, handler->v.ExceptHandler.name));
2785
2786
        /* second # body */
2787
0
        VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
2788
0
        _PyCompile_PopFBlock(c, COMPILE_FBLOCK_HANDLER_CLEANUP, cleanup_body);
2789
        /* name = None; del name; # artificial */
2790
0
        ADDOP(c, NO_LOCATION, POP_BLOCK);
2791
0
        if (handler->v.ExceptHandler.name) {
2792
0
            ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
2793
0
            RETURN_IF_ERROR(
2794
0
                codegen_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Store));
2795
0
            RETURN_IF_ERROR(
2796
0
                codegen_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Del));
2797
0
        }
2798
0
        ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, except);
2799
2800
        /* except: */
2801
0
        USE_LABEL(c, cleanup_end);
2802
2803
        /* name = None; del name; # artificial */
2804
0
        if (handler->v.ExceptHandler.name) {
2805
0
            ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
2806
0
            RETURN_IF_ERROR(
2807
0
                codegen_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Store));
2808
0
            RETURN_IF_ERROR(
2809
0
                codegen_nameop(c, NO_LOCATION, handler->v.ExceptHandler.name, Del));
2810
0
        }
2811
2812
        /* add exception raised to the res list */
2813
0
        ADDOP_I(c, NO_LOCATION, LIST_APPEND, 3); // exc
2814
0
        ADDOP(c, NO_LOCATION, POP_TOP); // lasti
2815
0
        ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, except_with_error);
2816
2817
0
        USE_LABEL(c, except);
2818
0
        ADDOP(c, NO_LOCATION, NOP);  // to hold a propagated location info
2819
0
        ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, except_with_error);
2820
2821
0
        USE_LABEL(c, no_match);
2822
0
        ADDOP(c, loc, POP_TOP);  // match (None)
2823
2824
0
        USE_LABEL(c, except_with_error);
2825
2826
0
        if (i == n - 1) {
2827
            /* Add exc to the list (if not None it's the unhandled part of the EG) */
2828
0
            ADDOP_I(c, NO_LOCATION, LIST_APPEND, 1);
2829
0
            ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, reraise_star);
2830
0
        }
2831
0
    }
2832
    /* artificial */
2833
0
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_EXCEPTION_GROUP_HANDLER, NO_LABEL);
2834
0
    NEW_JUMP_TARGET_LABEL(c, reraise);
2835
2836
0
    USE_LABEL(c, reraise_star);
2837
0
    ADDOP_I(c, NO_LOCATION, CALL_INTRINSIC_2, INTRINSIC_PREP_RERAISE_STAR);
2838
0
    ADDOP_I(c, NO_LOCATION, COPY, 1);
2839
0
    ADDOP_JUMP(c, NO_LOCATION, POP_JUMP_IF_NOT_NONE, reraise);
2840
2841
    /* Nothing to reraise */
2842
0
    ADDOP(c, NO_LOCATION, POP_TOP);
2843
0
    ADDOP(c, NO_LOCATION, POP_BLOCK);
2844
0
    ADDOP(c, NO_LOCATION, POP_EXCEPT);
2845
0
    ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
2846
2847
0
    USE_LABEL(c, reraise);
2848
0
    ADDOP(c, NO_LOCATION, POP_BLOCK);
2849
0
    ADDOP_I(c, NO_LOCATION, SWAP, 2);
2850
0
    ADDOP(c, NO_LOCATION, POP_EXCEPT);
2851
0
    ADDOP_I(c, NO_LOCATION, RERAISE, 0);
2852
2853
0
    USE_LABEL(c, cleanup);
2854
0
    POP_EXCEPT_AND_RERAISE(c, NO_LOCATION);
2855
2856
0
    USE_LABEL(c, orelse);
2857
0
    VISIT_SEQ(c, stmt, s->v.TryStar.orelse);
2858
2859
0
    USE_LABEL(c, end);
2860
0
    return SUCCESS;
2861
0
}
2862
2863
static int
2864
177
codegen_try(compiler *c, stmt_ty s) {
2865
177
    if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
2866
29
        return codegen_try_finally(c, s);
2867
148
    else
2868
148
        return codegen_try_except(c, s);
2869
177
}
2870
2871
static int
2872
codegen_try_star(compiler *c, stmt_ty s)
2873
0
{
2874
0
    if (s->v.TryStar.finalbody && asdl_seq_LEN(s->v.TryStar.finalbody)) {
2875
0
        return codegen_try_star_finally(c, s);
2876
0
    }
2877
0
    else {
2878
0
        return codegen_try_star_except(c, s);
2879
0
    }
2880
0
}
2881
2882
static int
2883
codegen_import_as(compiler *c, location loc,
2884
                  identifier name, identifier asname)
2885
30
{
2886
    /* The IMPORT_NAME opcode was already generated.  This function
2887
       merely needs to bind the result to a name.
2888
2889
       If there is a dot in name, we need to split it and emit a
2890
       IMPORT_FROM for each name.
2891
    */
2892
30
    Py_ssize_t len = PyUnicode_GET_LENGTH(name);
2893
30
    Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
2894
30
    if (dot == -2) {
2895
0
        return ERROR;
2896
0
    }
2897
30
    if (dot != -1) {
2898
        /* Consume the base module name to get the first attribute */
2899
4
        while (1) {
2900
4
            Py_ssize_t pos = dot + 1;
2901
4
            PyObject *attr;
2902
4
            dot = PyUnicode_FindChar(name, '.', pos, len, 1);
2903
4
            if (dot == -2) {
2904
0
                return ERROR;
2905
0
            }
2906
4
            attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
2907
4
            if (!attr) {
2908
0
                return ERROR;
2909
0
            }
2910
4
            ADDOP_N(c, loc, IMPORT_FROM, attr, names);
2911
4
            if (dot == -1) {
2912
2
                break;
2913
2
            }
2914
2
            ADDOP_I(c, loc, SWAP, 2);
2915
2
            ADDOP(c, loc, POP_TOP);
2916
2
        }
2917
2
        RETURN_IF_ERROR(codegen_nameop(c, loc, asname, Store));
2918
2
        ADDOP(c, loc, POP_TOP);
2919
2
        return SUCCESS;
2920
2
    }
2921
28
    return codegen_nameop(c, loc, asname, Store);
2922
30
}
2923
2924
static int
2925
codegen_validate_lazy_import(compiler *c, location loc)
2926
1
{
2927
1
    if (_PyCompile_ScopeType(c) != COMPILE_SCOPE_MODULE) {
2928
0
        return _PyCompile_Error(
2929
0
            c, loc, "lazy imports only allowed in module scope");
2930
0
    }
2931
2932
1
    return SUCCESS;
2933
1
}
2934
2935
static int
2936
codegen_import(compiler *c, stmt_ty s)
2937
359
{
2938
359
    location loc = LOC(s);
2939
    /* The Import node stores a module name like a.b.c as a single
2940
       string.  This is convenient for all cases except
2941
         import a.b.c as d
2942
       where we need to parse that string to extract the individual
2943
       module names.
2944
       XXX Perhaps change the representation to make this case simpler?
2945
     */
2946
359
    Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
2947
2948
359
    PyObject *zero = _PyLong_GetZero();  // borrowed reference
2949
744
    for (i = 0; i < n; i++) {
2950
385
        alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
2951
385
        int r;
2952
2953
385
        ADDOP_LOAD_CONST(c, loc, zero);
2954
385
        ADDOP_LOAD_CONST(c, loc, Py_None);
2955
385
        if (s->v.Import.is_lazy) {
2956
0
            RETURN_IF_ERROR(codegen_validate_lazy_import(c, loc));
2957
0
            ADDOP_NAME_CUSTOM(c, loc, IMPORT_NAME, alias->name, names, 2, 1);
2958
385
        } else {
2959
385
            if (_PyCompile_InExceptionHandler(c) ||
2960
382
                _PyCompile_ScopeType(c) != COMPILE_SCOPE_MODULE) {
2961
                // force eager import in try/except block
2962
6
                ADDOP_NAME_CUSTOM(c, loc, IMPORT_NAME, alias->name, names, 2, 2);
2963
379
            } else {
2964
379
                ADDOP_NAME_CUSTOM(c, loc, IMPORT_NAME, alias->name, names, 2, 0);
2965
379
            }
2966
385
        }
2967
2968
385
        if (alias->asname) {
2969
30
            r = codegen_import_as(c, loc, alias->name, alias->asname);
2970
30
            RETURN_IF_ERROR(r);
2971
30
        }
2972
355
        else {
2973
355
            identifier tmp = alias->name;
2974
355
            Py_ssize_t dot = PyUnicode_FindChar(
2975
355
                alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
2976
355
            if (dot != -1) {
2977
5
                tmp = PyUnicode_Substring(alias->name, 0, dot);
2978
5
                if (tmp == NULL) {
2979
0
                    return ERROR;
2980
0
                }
2981
5
            }
2982
355
            r = codegen_nameop(c, loc, tmp, Store);
2983
355
            if (dot != -1) {
2984
5
                Py_DECREF(tmp);
2985
5
            }
2986
355
            RETURN_IF_ERROR(r);
2987
355
        }
2988
385
    }
2989
359
    return SUCCESS;
2990
359
}
2991
2992
static int
2993
codegen_from_import(compiler *c, stmt_ty s)
2994
426
{
2995
426
    Py_ssize_t n = asdl_seq_LEN(s->v.ImportFrom.names);
2996
2997
426
    ADDOP_LOAD_CONST_NEW(c, LOC(s), PyLong_FromLong(s->v.ImportFrom.level));
2998
2999
426
    PyObject *names = PyTuple_New(n);
3000
426
    if (!names) {
3001
0
        return ERROR;
3002
0
    }
3003
3004
    /* build up the names */
3005
1.12k
    for (Py_ssize_t i = 0; i < n; i++) {
3006
696
        alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3007
696
        PyTuple_SET_ITEM(names, i, Py_NewRef(alias->name));
3008
696
    }
3009
3010
426
    ADDOP_LOAD_CONST_NEW(c, LOC(s), names);
3011
3012
426
    identifier from = &_Py_STR(empty);
3013
426
    if (s->v.ImportFrom.module) {
3014
417
        from = s->v.ImportFrom.module;
3015
417
    }
3016
426
    if (s->v.ImportFrom.is_lazy) {
3017
1
        alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, 0);
3018
1
        if (PyUnicode_READ_CHAR(alias->name, 0) == '*') {
3019
0
            return _PyCompile_Error(c, LOC(s), "cannot lazy import *");
3020
0
        }
3021
1
        RETURN_IF_ERROR(codegen_validate_lazy_import(c, LOC(s)));
3022
1
        ADDOP_NAME_CUSTOM(c, LOC(s), IMPORT_NAME, from, names, 2, 1);
3023
425
    } else {
3024
425
        alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, 0);
3025
425
        if (_PyCompile_InExceptionHandler(c) ||
3026
419
            _PyCompile_ScopeType(c) != COMPILE_SCOPE_MODULE ||
3027
410
            PyUnicode_READ_CHAR(alias->name, 0) == '*') {
3028
            // forced non-lazy import due to try/except or import *
3029
16
            ADDOP_NAME_CUSTOM(c, LOC(s), IMPORT_NAME, from, names, 2, 2);
3030
409
        } else {
3031
409
            ADDOP_NAME_CUSTOM(c, LOC(s), IMPORT_NAME, from, names, 2, 0);
3032
409
        }
3033
425
    }
3034
3035
1.12k
    for (Py_ssize_t i = 0; i < n; i++) {
3036
696
        alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3037
696
        identifier store_name;
3038
3039
696
        if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
3040
2
            assert(n == 1);
3041
2
            ADDOP_I(c, LOC(s), CALL_INTRINSIC_1, INTRINSIC_IMPORT_STAR);
3042
2
            ADDOP(c, NO_LOCATION, POP_TOP);
3043
2
            return SUCCESS;
3044
2
        }
3045
3046
694
        ADDOP_NAME(c, LOC(s), IMPORT_FROM, alias->name, names);
3047
694
        store_name = alias->name;
3048
694
        if (alias->asname) {
3049
6
            store_name = alias->asname;
3050
6
        }
3051
3052
694
        RETURN_IF_ERROR(codegen_nameop(c, LOC(s), store_name, Store));
3053
694
    }
3054
    /* remove imported module */
3055
424
    ADDOP(c, LOC(s), POP_TOP);
3056
424
    return SUCCESS;
3057
424
}
3058
3059
static int
3060
codegen_assert(compiler *c, stmt_ty s)
3061
48
{
3062
    /* Always emit a warning if the test is a non-zero length tuple */
3063
48
    if ((s->v.Assert.test->kind == Tuple_kind &&
3064
0
        asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) ||
3065
48
        (s->v.Assert.test->kind == Constant_kind &&
3066
48
         PyTuple_Check(s->v.Assert.test->v.Constant.value) &&
3067
0
         PyTuple_Size(s->v.Assert.test->v.Constant.value) > 0))
3068
0
    {
3069
0
        RETURN_IF_ERROR(
3070
0
            _PyCompile_Warn(c, LOC(s), "assertion is always true, "
3071
0
                                       "perhaps remove parentheses?"));
3072
0
    }
3073
48
    if (OPTIMIZATION_LEVEL(c)) {
3074
0
        return SUCCESS;
3075
0
    }
3076
48
    NEW_JUMP_TARGET_LABEL(c, end);
3077
48
    RETURN_IF_ERROR(codegen_jump_if(c, LOC(s), s->v.Assert.test, end, 1));
3078
48
    ADDOP_I(c, LOC(s), LOAD_COMMON_CONSTANT, CONSTANT_ASSERTIONERROR);
3079
48
    if (s->v.Assert.msg) {
3080
20
        VISIT(c, expr, s->v.Assert.msg);
3081
20
        ADDOP_I(c, LOC(s), CALL, 0);
3082
20
    }
3083
48
    ADDOP_I(c, LOC(s->v.Assert.test), RAISE_VARARGS, 1);
3084
3085
48
    USE_LABEL(c, end);
3086
48
    return SUCCESS;
3087
48
}
3088
3089
static int
3090
codegen_stmt_expr(compiler *c, location loc, expr_ty value)
3091
2.03k
{
3092
2.03k
    if (IS_INTERACTIVE_TOP_LEVEL(c)) {
3093
0
        VISIT(c, expr, value);
3094
0
        ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_PRINT);
3095
0
        ADDOP(c, NO_LOCATION, POP_TOP);
3096
0
        return SUCCESS;
3097
0
    }
3098
3099
2.03k
    if (value->kind == Constant_kind) {
3100
        /* ignore constant statement */
3101
4
        ADDOP(c, loc, NOP);
3102
4
        return SUCCESS;
3103
4
    }
3104
3105
2.03k
    VISIT_UNUSED(c, expr, value);
3106
2.03k
    ADDOP(c, NO_LOCATION, POP_TOP); /* artificial */
3107
2.03k
    return SUCCESS;
3108
2.03k
}
3109
3110
#define CODEGEN_COND_BLOCK(FUNC, C, S) \
3111
2.00k
    do { \
3112
2.00k
        _PyCompile_EnterConditionalBlock((C)); \
3113
2.00k
        int result = FUNC((C), (S)); \
3114
2.00k
        _PyCompile_LeaveConditionalBlock((C)); \
3115
2.00k
        return result; \
3116
2.00k
    } while(0)
3117
3118
static int
3119
codegen_visit_stmt(compiler *c, stmt_ty s)
3120
13.1k
{
3121
3122
13.1k
    switch (s->kind) {
3123
2.27k
    case FunctionDef_kind:
3124
2.27k
        return codegen_function(c, s, 0);
3125
629
    case ClassDef_kind:
3126
629
        return codegen_class(c, s);
3127
0
    case TypeAlias_kind:
3128
0
        return codegen_typealias(c, s);
3129
2.02k
    case Return_kind:
3130
2.02k
        return codegen_return(c, s);
3131
20
    case Delete_kind:
3132
20
        VISIT_SEQ(c, expr, s->v.Delete.targets);
3133
20
        break;
3134
2.62k
    case Assign_kind:
3135
2.62k
    {
3136
2.62k
        Py_ssize_t n = asdl_seq_LEN(s->v.Assign.targets);
3137
2.62k
        VISIT(c, expr, s->v.Assign.value);
3138
5.28k
        for (Py_ssize_t i = 0; i < n; i++) {
3139
2.65k
            if (i < n - 1) {
3140
22
                ADDOP_I(c, LOC(s), COPY, 1);
3141
22
            }
3142
2.65k
            VISIT(c, expr,
3143
2.65k
                  (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3144
2.65k
        }
3145
2.62k
        break;
3146
2.62k
    }
3147
2.62k
    case AugAssign_kind:
3148
100
        return codegen_augassign(c, s);
3149
8
    case AnnAssign_kind:
3150
8
        return codegen_annassign(c, s);
3151
183
    case For_kind:
3152
183
        CODEGEN_COND_BLOCK(codegen_for, c, s);
3153
0
        break;
3154
33
    case While_kind:
3155
33
        CODEGEN_COND_BLOCK(codegen_while, c, s);
3156
0
        break;
3157
1.53k
    case If_kind:
3158
1.53k
        CODEGEN_COND_BLOCK(codegen_if, c, s);
3159
0
        break;
3160
0
    case Match_kind:
3161
0
        CODEGEN_COND_BLOCK(codegen_match, c, s);
3162
0
        break;
3163
306
    case Raise_kind:
3164
306
    {
3165
306
        Py_ssize_t n = 0;
3166
306
        if (s->v.Raise.exc) {
3167
278
            VISIT(c, expr, s->v.Raise.exc);
3168
278
            n++;
3169
278
            if (s->v.Raise.cause) {
3170
12
                VISIT(c, expr, s->v.Raise.cause);
3171
12
                n++;
3172
12
            }
3173
278
        }
3174
306
        ADDOP_I(c, LOC(s), RAISE_VARARGS, (int)n);
3175
306
        break;
3176
306
    }
3177
306
    case Try_kind:
3178
177
        CODEGEN_COND_BLOCK(codegen_try, c, s);
3179
0
        break;
3180
0
    case TryStar_kind:
3181
0
        CODEGEN_COND_BLOCK(codegen_try_star, c, s);
3182
0
        break;
3183
48
    case Assert_kind:
3184
48
        return codegen_assert(c, s);
3185
359
    case Import_kind:
3186
359
        return codegen_import(c, s);
3187
426
    case ImportFrom_kind:
3188
426
        return codegen_from_import(c, s);
3189
4
    case Global_kind:
3190
6
    case Nonlocal_kind:
3191
6
        break;
3192
2.03k
    case Expr_kind:
3193
2.03k
    {
3194
2.03k
        return codegen_stmt_expr(c, LOC(s), s->v.Expr.value);
3195
4
    }
3196
198
    case Pass_kind:
3197
198
    {
3198
198
        ADDOP(c, LOC(s), NOP);
3199
198
        break;
3200
198
    }
3201
198
    case Break_kind:
3202
22
    {
3203
22
        return codegen_break(c, LOC(s));
3204
198
    }
3205
19
    case Continue_kind:
3206
19
    {
3207
19
        return codegen_continue(c, LOC(s));
3208
198
    }
3209
79
    case With_kind:
3210
79
        CODEGEN_COND_BLOCK(codegen_with, c, s);
3211
0
        break;
3212
0
    case AsyncFunctionDef_kind:
3213
0
        return codegen_function(c, s, 1);
3214
0
    case AsyncWith_kind:
3215
0
        CODEGEN_COND_BLOCK(codegen_async_with, c, s);
3216
0
        break;
3217
0
    case AsyncFor_kind:
3218
0
        CODEGEN_COND_BLOCK(codegen_async_for, c, s);
3219
0
        break;
3220
13.1k
    }
3221
3222
3.15k
    return SUCCESS;
3223
13.1k
}
3224
3225
static int
3226
unaryop(unaryop_ty op)
3227
1.72k
{
3228
1.72k
    switch (op) {
3229
0
    case Invert:
3230
0
        return UNARY_INVERT;
3231
1.72k
    case USub:
3232
1.72k
        return UNARY_NEGATIVE;
3233
0
    default:
3234
0
        PyErr_Format(PyExc_SystemError,
3235
0
            "unary op %d should not be possible", op);
3236
0
        return 0;
3237
1.72k
    }
3238
1.72k
}
3239
3240
static int
3241
addop_binary(compiler *c, location loc, operator_ty binop,
3242
             bool inplace)
3243
581
{
3244
581
    int oparg;
3245
581
    switch (binop) {
3246
283
        case Add:
3247
283
            oparg = inplace ? NB_INPLACE_ADD : NB_ADD;
3248
283
            break;
3249
95
        case Sub:
3250
95
            oparg = inplace ? NB_INPLACE_SUBTRACT : NB_SUBTRACT;
3251
95
            break;
3252
49
        case Mult:
3253
49
            oparg = inplace ? NB_INPLACE_MULTIPLY : NB_MULTIPLY;
3254
49
            break;
3255
0
        case MatMult:
3256
0
            oparg = inplace ? NB_INPLACE_MATRIX_MULTIPLY : NB_MATRIX_MULTIPLY;
3257
0
            break;
3258
3
        case Div:
3259
3
            oparg = inplace ? NB_INPLACE_TRUE_DIVIDE : NB_TRUE_DIVIDE;
3260
3
            break;
3261
84
        case Mod:
3262
84
            oparg = inplace ? NB_INPLACE_REMAINDER : NB_REMAINDER;
3263
84
            break;
3264
7
        case Pow:
3265
7
            oparg = inplace ? NB_INPLACE_POWER : NB_POWER;
3266
7
            break;
3267
24
        case LShift:
3268
24
            oparg = inplace ? NB_INPLACE_LSHIFT : NB_LSHIFT;
3269
24
            break;
3270
0
        case RShift:
3271
0
            oparg = inplace ? NB_INPLACE_RSHIFT : NB_RSHIFT;
3272
0
            break;
3273
14
        case BitOr:
3274
14
            oparg = inplace ? NB_INPLACE_OR : NB_OR;
3275
14
            break;
3276
1
        case BitXor:
3277
1
            oparg = inplace ? NB_INPLACE_XOR : NB_XOR;
3278
1
            break;
3279
10
        case BitAnd:
3280
10
            oparg = inplace ? NB_INPLACE_AND : NB_AND;
3281
10
            break;
3282
11
        case FloorDiv:
3283
11
            oparg = inplace ? NB_INPLACE_FLOOR_DIVIDE : NB_FLOOR_DIVIDE;
3284
11
            break;
3285
0
        default:
3286
0
            PyErr_Format(PyExc_SystemError, "%s op %d should not be possible",
3287
0
                         inplace ? "inplace" : "binary", binop);
3288
0
            return ERROR;
3289
581
    }
3290
581
    ADDOP_I(c, loc, BINARY_OP, oparg);
3291
581
    return SUCCESS;
3292
581
}
3293
3294
3295
static int
3296
63
codegen_addop_yield(compiler *c, location loc) {
3297
63
    PySTEntryObject *ste = SYMTABLE_ENTRY(c);
3298
63
    if (ste->ste_generator && ste->ste_coroutine) {
3299
0
        ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_ASYNC_GEN_WRAP);
3300
0
    }
3301
63
    ADDOP_I(c, loc, YIELD_VALUE, 0);
3302
63
    ADDOP_I(c, loc, RESUME, RESUME_AFTER_YIELD);
3303
63
    return SUCCESS;
3304
63
}
3305
3306
static int
3307
codegen_load_classdict_freevar(compiler *c, location loc)
3308
28
{
3309
28
    ADDOP_N(c, loc, LOAD_DEREF, &_Py_ID(__classdict__), freevars);
3310
28
    return SUCCESS;
3311
28
}
3312
3313
static int
3314
codegen_nameop(compiler *c, location loc,
3315
               identifier name, expr_context_ty ctx)
3316
34.1k
{
3317
34.1k
    assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3318
34.1k
           !_PyUnicode_EqualToASCIIString(name, "True") &&
3319
34.1k
           !_PyUnicode_EqualToASCIIString(name, "False"));
3320
3321
34.1k
    PyObject *mangled = _PyCompile_MaybeMangle(c, name);
3322
34.1k
    if (!mangled) {
3323
0
        return ERROR;
3324
0
    }
3325
3326
34.1k
    _PyCompile_optype optype;
3327
34.1k
    Py_ssize_t arg = 0;
3328
34.1k
    int scope = _PyCompile_ResolveNameop(c, mangled, &optype, &arg);
3329
34.1k
    if (scope < 0) {
3330
0
        Py_DECREF(mangled);
3331
0
        return ERROR;
3332
0
    }
3333
3334
34.1k
    int op = 0;
3335
34.1k
    switch (optype) {
3336
1.50k
    case COMPILE_OP_DEREF:
3337
1.50k
        switch (ctx) {
3338
1.43k
        case Load:
3339
1.43k
            if (SYMTABLE_ENTRY(c)->ste_type == ClassBlock) {
3340
1
                op = LOAD_FROM_DICT_OR_DEREF;
3341
                // First load the locals
3342
1
                if (codegen_addop_noarg(INSTR_SEQUENCE(c), LOAD_LOCALS, loc) < 0) {
3343
0
                    goto error;
3344
0
                }
3345
1
            }
3346
1.43k
            else if (SYMTABLE_ENTRY(c)->ste_can_see_class_scope) {
3347
0
                op = LOAD_FROM_DICT_OR_DEREF;
3348
                // First load the classdict
3349
0
                if (codegen_load_classdict_freevar(c, loc) < 0) {
3350
0
                    goto error;
3351
0
                }
3352
0
            }
3353
1.43k
            else {
3354
1.43k
                op = LOAD_DEREF;
3355
1.43k
            }
3356
1.43k
            break;
3357
1.43k
        case Store: op = STORE_DEREF; break;
3358
0
        case Del: op = DELETE_DEREF; break;
3359
1.50k
        }
3360
1.50k
        break;
3361
18.4k
    case COMPILE_OP_FAST:
3362
18.4k
        switch (ctx) {
3363
15.7k
        case Load: op = LOAD_FAST; break;
3364
2.59k
        case Store: op = STORE_FAST; break;
3365
67
        case Del: op = DELETE_FAST; break;
3366
18.4k
        }
3367
18.4k
        ADDOP_N(c, loc, op, mangled, varnames);
3368
18.4k
        return SUCCESS;
3369
4.99k
    case COMPILE_OP_GLOBAL:
3370
4.99k
        switch (ctx) {
3371
4.99k
        case Load:
3372
4.99k
            if (SYMTABLE_ENTRY(c)->ste_can_see_class_scope && scope == GLOBAL_IMPLICIT) {
3373
28
                op = LOAD_FROM_DICT_OR_GLOBALS;
3374
                // First load the classdict
3375
28
                if (codegen_load_classdict_freevar(c, loc) < 0) {
3376
0
                    goto error;
3377
0
                }
3378
4.96k
            } else {
3379
4.96k
                op = LOAD_GLOBAL;
3380
4.96k
            }
3381
4.99k
            break;
3382
4.99k
        case Store: op = STORE_GLOBAL; break;
3383
0
        case Del:
3384
0
            ADDOP(c, loc, PUSH_NULL);
3385
0
            op = STORE_GLOBAL;
3386
0
            break;
3387
4.99k
        }
3388
4.99k
        break;
3389
9.21k
    case COMPILE_OP_NAME:
3390
9.21k
        switch (ctx) {
3391
2.40k
        case Load:
3392
            /* LOAD_NAME in a class reads the class dict; inlined comps must not. */
3393
2.40k
            op = (SCOPE_TYPE(c) == COMPILE_SCOPE_CLASS
3394
981
                  && SYMTABLE_ENTRY(c)->ste_type == InlinedComprehensionBlock)
3395
2.40k
                ? LOAD_GLOBAL
3396
2.40k
                : LOAD_NAME;
3397
2.40k
            break;
3398
6.80k
        case Store: op = STORE_NAME; break;
3399
2
        case Del:
3400
2
            ADDOP(c, loc, PUSH_NULL);
3401
2
            op = STORE_NAME;
3402
2
            break;
3403
9.21k
        }
3404
9.21k
        break;
3405
34.1k
    }
3406
3407
34.1k
    assert(op);
3408
15.7k
    Py_DECREF(mangled);
3409
15.7k
    if (op == LOAD_GLOBAL) {
3410
4.96k
        arg <<= 1;
3411
4.96k
    }
3412
15.7k
    ADDOP_I(c, loc, op, arg);
3413
15.7k
    return SUCCESS;
3414
3415
0
error:
3416
0
    Py_DECREF(mangled);
3417
0
    return ERROR;
3418
15.7k
}
3419
3420
static int
3421
codegen_boolop(compiler *c, expr_ty e)
3422
130
{
3423
130
    int jumpi;
3424
130
    Py_ssize_t i, n;
3425
130
    asdl_expr_seq *s;
3426
3427
130
    location loc = LOC(e);
3428
130
    assert(e->kind == BoolOp_kind);
3429
130
    if (e->v.BoolOp.op == And)
3430
107
        jumpi = JUMP_IF_FALSE;
3431
23
    else
3432
23
        jumpi = JUMP_IF_TRUE;
3433
130
    NEW_JUMP_TARGET_LABEL(c, end);
3434
130
    s = e->v.BoolOp.values;
3435
130
    n = asdl_seq_LEN(s) - 1;
3436
130
    assert(n >= 0);
3437
653
    for (i = 0; i < n; ++i) {
3438
523
        VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
3439
523
        ADDOP_JUMP(c, loc, jumpi, end);
3440
523
        ADDOP(c, loc, POP_TOP);
3441
523
    }
3442
130
    VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3443
3444
130
    USE_LABEL(c, end);
3445
130
    return SUCCESS;
3446
130
}
3447
3448
static bool
3449
is_empty_starred_literal(expr_ty elt)
3450
3.51k
{
3451
3.51k
    if (elt->kind != Starred_kind) {
3452
3.43k
        return false;
3453
3.43k
    }
3454
76
    expr_ty value = elt->v.Starred.value;
3455
76
    return (value->kind == Tuple_kind &&
3456
0
            asdl_seq_LEN(value->v.Tuple.elts) == 0) ||
3457
76
           (value->kind == List_kind &&
3458
0
            asdl_seq_LEN(value->v.List.elts) == 0) ||
3459
76
           (value->kind == Dict_kind &&
3460
0
            asdl_seq_LEN(value->v.Dict.keys) == 0);
3461
3.51k
}
3462
3463
static int
3464
starunpack_helper_impl(compiler *c, location loc,
3465
                       asdl_expr_seq *elts, PyObject *injected_arg, int pushed,
3466
                       int build, int add, int extend, int tuple)
3467
989
{
3468
989
    Py_ssize_t end = asdl_seq_LEN(elts);
3469
989
    Py_ssize_t n = 0;
3470
989
    int seen_star = 0;
3471
6.50k
    for (Py_ssize_t i = 0; i < end; i++) {
3472
5.51k
        expr_ty elt = asdl_seq_GET(elts, i);
3473
5.51k
        if (elt->kind == Starred_kind) {
3474
38
            if (is_empty_starred_literal(elt)) {
3475
0
                continue;
3476
0
            }
3477
38
            seen_star = 1;
3478
38
        }
3479
5.51k
        n++;
3480
5.51k
    }
3481
989
    int big = n + pushed + (injected_arg ? 1 : 0) > _PY_STACK_USE_GUIDELINE;
3482
989
    if (!seen_star && !big) {
3483
4.38k
        for (Py_ssize_t i = 0; i < end; i++) {
3484
3.43k
            expr_ty elt = asdl_seq_GET(elts, i);
3485
3.43k
            if (is_empty_starred_literal(elt)) {
3486
0
                continue;
3487
0
            }
3488
3.43k
            VISIT(c, expr, elt);
3489
3.43k
        }
3490
951
        if (injected_arg) {
3491
0
            RETURN_IF_ERROR(codegen_nameop(c, loc, injected_arg, Load));
3492
0
            n++;
3493
0
        }
3494
951
        if (tuple) {
3495
709
            ADDOP_I(c, loc, BUILD_TUPLE, n+pushed);
3496
709
        } else {
3497
242
            ADDOP_I(c, loc, build, n+pushed);
3498
242
        }
3499
951
        return SUCCESS;
3500
951
    }
3501
38
    int sequence_built = 0;
3502
38
    Py_ssize_t nitems = 0;
3503
38
    if (big) {
3504
18
        ADDOP_I(c, loc, build, pushed);
3505
18
        sequence_built = 1;
3506
18
    }
3507
2.11k
    for (Py_ssize_t i = 0; i < end; i++) {
3508
2.07k
        expr_ty elt = asdl_seq_GET(elts, i);
3509
3510
2.07k
        if (elt->kind == Starred_kind) {
3511
38
            if (is_empty_starred_literal(elt)) {
3512
0
                continue;
3513
0
            }
3514
38
            if (sequence_built == 0) {
3515
20
                ADDOP_I(c, loc, build, nitems+pushed);
3516
20
                sequence_built = 1;
3517
20
            }
3518
38
            VISIT(c, expr, elt->v.Starred.value);
3519
38
            ADDOP_I(c, loc, extend, 1);
3520
38
        }
3521
2.04k
        else {
3522
2.04k
            VISIT(c, expr, elt);
3523
2.04k
            if (sequence_built) {
3524
2.02k
                ADDOP_I(c, loc, add, 1);
3525
2.02k
            }
3526
2.04k
        }
3527
2.07k
        nitems++;
3528
2.07k
    }
3529
38
    assert(sequence_built);
3530
38
    if (injected_arg) {
3531
0
        RETURN_IF_ERROR(codegen_nameop(c, loc, injected_arg, Load));
3532
0
        ADDOP_I(c, loc, add, 1);
3533
0
    }
3534
38
    if (tuple) {
3535
35
        ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_LIST_TO_TUPLE);
3536
35
    }
3537
38
    return SUCCESS;
3538
38
}
3539
3540
static int
3541
starunpack_helper(compiler *c, location loc,
3542
                  asdl_expr_seq *elts, int pushed,
3543
                  int build, int add, int extend, int tuple)
3544
970
{
3545
970
    return starunpack_helper_impl(c, loc, elts, NULL, pushed,
3546
970
                                  build, add, extend, tuple);
3547
970
}
3548
3549
static int
3550
unpack_helper(compiler *c, location loc, asdl_expr_seq *elts)
3551
119
{
3552
119
    Py_ssize_t n = asdl_seq_LEN(elts);
3553
119
    int seen_star = 0;
3554
386
    for (Py_ssize_t i = 0; i < n; i++) {
3555
267
        expr_ty elt = asdl_seq_GET(elts, i);
3556
267
        if (elt->kind == Starred_kind && !seen_star) {
3557
1
            if ((i >= (1 << 8)) ||
3558
1
                (n-i-1 >= (INT_MAX >> 8))) {
3559
0
                return _PyCompile_Error(c, loc,
3560
0
                    "too many expressions in "
3561
0
                    "star-unpacking assignment");
3562
0
            }
3563
1
            ADDOP_I(c, loc, UNPACK_EX, (i + ((n-i-1) << 8)));
3564
1
            seen_star = 1;
3565
1
        }
3566
266
        else if (elt->kind == Starred_kind) {
3567
0
            return _PyCompile_Error(c, loc,
3568
0
                "multiple starred expressions in assignment");
3569
0
        }
3570
267
    }
3571
119
    if (!seen_star) {
3572
118
        ADDOP_I(c, loc, UNPACK_SEQUENCE, n);
3573
118
    }
3574
119
    return SUCCESS;
3575
119
}
3576
3577
static int
3578
assignment_helper(compiler *c, location loc, asdl_expr_seq *elts)
3579
119
{
3580
119
    Py_ssize_t n = asdl_seq_LEN(elts);
3581
119
    RETURN_IF_ERROR(unpack_helper(c, loc, elts));
3582
386
    for (Py_ssize_t i = 0; i < n; i++) {
3583
267
        expr_ty elt = asdl_seq_GET(elts, i);
3584
267
        VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3585
267
    }
3586
119
    return SUCCESS;
3587
119
}
3588
3589
static int
3590
codegen_list(compiler *c, expr_ty e)
3591
114
{
3592
114
    location loc = LOC(e);
3593
114
    asdl_expr_seq *elts = e->v.List.elts;
3594
114
    if (e->v.List.ctx == Store) {
3595
0
        return assignment_helper(c, loc, elts);
3596
0
    }
3597
114
    else if (e->v.List.ctx == Load) {
3598
114
        return starunpack_helper(c, loc, elts, 0,
3599
114
                                 BUILD_LIST, LIST_APPEND, LIST_EXTEND, 0);
3600
114
    }
3601
0
    else {
3602
0
        VISIT_SEQ(c, expr, elts);
3603
0
    }
3604
0
    return SUCCESS;
3605
114
}
3606
3607
static int
3608
codegen_tuple(compiler *c, expr_ty e)
3609
844
{
3610
844
    location loc = LOC(e);
3611
844
    asdl_expr_seq *elts = e->v.Tuple.elts;
3612
844
    if (e->v.Tuple.ctx == Store) {
3613
119
        return assignment_helper(c, loc, elts);
3614
119
    }
3615
725
    else if (e->v.Tuple.ctx == Load) {
3616
725
        return starunpack_helper(c, loc, elts, 0,
3617
725
                                 BUILD_LIST, LIST_APPEND, LIST_EXTEND, 1);
3618
725
    }
3619
0
    else {
3620
0
        VISIT_SEQ(c, expr, elts);
3621
0
    }
3622
0
    return SUCCESS;
3623
844
}
3624
3625
static int
3626
codegen_set(compiler *c, expr_ty e)
3627
131
{
3628
131
    location loc = LOC(e);
3629
131
    return starunpack_helper(c, loc, e->v.Set.elts, 0,
3630
131
                             BUILD_SET, SET_ADD, SET_UPDATE, 0);
3631
131
}
3632
3633
static int
3634
codegen_subdict(compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3635
431
{
3636
431
    Py_ssize_t i, n = end - begin;
3637
431
    int big = n*2 > _PY_STACK_USE_GUIDELINE;
3638
431
    location loc = LOC(e);
3639
431
    if (big) {
3640
376
        ADDOP_I(c, loc, BUILD_MAP, 0);
3641
376
    }
3642
7.12k
    for (i = begin; i < end; i++) {
3643
6.69k
        VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3644
6.69k
        VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3645
6.69k
        if (big) {
3646
6.39k
            ADDOP_I(c, loc, MAP_ADD, 1);
3647
6.39k
        }
3648
6.69k
    }
3649
431
    if (!big) {
3650
55
        ADDOP_I(c, loc, BUILD_MAP, n);
3651
55
    }
3652
431
    return SUCCESS;
3653
431
}
3654
3655
static int
3656
codegen_dict(compiler *c, expr_ty e)
3657
92
{
3658
92
    location loc = LOC(e);
3659
92
    Py_ssize_t i, n, elements;
3660
92
    int have_dict;
3661
92
    int is_unpacking = 0;
3662
92
    n = asdl_seq_LEN(e->v.Dict.values);
3663
92
    have_dict = 0;
3664
92
    elements = 0;
3665
6.78k
    for (i = 0; i < n; i++) {
3666
6.69k
        is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
3667
6.69k
        if (is_unpacking) {
3668
4
            if (elements) {
3669
0
                RETURN_IF_ERROR(codegen_subdict(c, e, i - elements, i));
3670
0
                if (have_dict) {
3671
0
                    ADDOP_I(c, loc, DICT_UPDATE, 1);
3672
0
                }
3673
0
                have_dict = 1;
3674
0
                elements = 0;
3675
0
            }
3676
4
            if (have_dict == 0) {
3677
2
                ADDOP_I(c, loc, BUILD_MAP, 0);
3678
2
                have_dict = 1;
3679
2
            }
3680
4
            VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3681
4
            ADDOP_I(c, loc, DICT_UPDATE, 1);
3682
4
        }
3683
6.69k
        else {
3684
6.69k
            if (elements*2 > _PY_STACK_USE_GUIDELINE) {
3685
375
                RETURN_IF_ERROR(codegen_subdict(c, e, i - elements, i + 1));
3686
375
                if (have_dict) {
3687
339
                    ADDOP_I(c, loc, DICT_UPDATE, 1);
3688
339
                }
3689
375
                have_dict = 1;
3690
375
                elements = 0;
3691
375
            }
3692
6.31k
            else {
3693
6.31k
                elements++;
3694
6.31k
            }
3695
6.69k
        }
3696
6.69k
    }
3697
92
    if (elements) {
3698
56
        RETURN_IF_ERROR(codegen_subdict(c, e, n - elements, n));
3699
56
        if (have_dict) {
3700
36
            ADDOP_I(c, loc, DICT_UPDATE, 1);
3701
36
        }
3702
56
        have_dict = 1;
3703
56
    }
3704
92
    if (!have_dict) {
3705
34
        ADDOP_I(c, loc, BUILD_MAP, 0);
3706
34
    }
3707
92
    return SUCCESS;
3708
92
}
3709
3710
static int
3711
codegen_compare(compiler *c, expr_ty e)
3712
1.83k
{
3713
1.83k
    location loc = LOC(e);
3714
1.83k
    Py_ssize_t i, n;
3715
3716
1.83k
    RETURN_IF_ERROR(codegen_check_compare(c, e));
3717
1.83k
    VISIT(c, expr, e->v.Compare.left);
3718
1.83k
    assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3719
1.83k
    n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3720
1.83k
    if (n == 0) {
3721
1.83k
        VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
3722
1.83k
        ADDOP_COMPARE(c, loc, asdl_seq_GET(e->v.Compare.ops, 0));
3723
1.83k
    }
3724
5
    else {
3725
5
        NEW_JUMP_TARGET_LABEL(c, cleanup);
3726
10
        for (i = 0; i < n; i++) {
3727
5
            VISIT(c, expr,
3728
5
                (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
3729
5
            ADDOP_I(c, loc, SWAP, 2);
3730
5
            ADDOP_I(c, loc, COPY, 2);
3731
5
            ADDOP_COMPARE(c, loc, asdl_seq_GET(e->v.Compare.ops, i));
3732
5
            ADDOP_I(c, loc, COPY, 1);
3733
5
            ADDOP(c, loc, TO_BOOL);
3734
5
            ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, cleanup);
3735
5
            ADDOP(c, loc, POP_TOP);
3736
5
        }
3737
5
        VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
3738
5
        ADDOP_COMPARE(c, loc, asdl_seq_GET(e->v.Compare.ops, n));
3739
5
        NEW_JUMP_TARGET_LABEL(c, end);
3740
5
        ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
3741
3742
5
        USE_LABEL(c, cleanup);
3743
5
        ADDOP_I(c, loc, SWAP, 2);
3744
5
        ADDOP(c, loc, POP_TOP);
3745
3746
5
        USE_LABEL(c, end);
3747
5
    }
3748
1.83k
    return SUCCESS;
3749
1.83k
}
3750
3751
static PyTypeObject *
3752
infer_type(expr_ty e)
3753
493
{
3754
493
    switch (e->kind) {
3755
9
    case Tuple_kind:
3756
9
        return &PyTuple_Type;
3757
0
    case List_kind:
3758
0
    case ListComp_kind:
3759
0
        return &PyList_Type;
3760
0
    case Dict_kind:
3761
0
    case DictComp_kind:
3762
0
        return &PyDict_Type;
3763
0
    case Set_kind:
3764
0
    case SetComp_kind:
3765
0
        return &PySet_Type;
3766
0
    case GeneratorExp_kind:
3767
0
        return &PyGen_Type;
3768
0
    case Lambda_kind:
3769
0
        return &PyFunction_Type;
3770
0
    case TemplateStr_kind:
3771
0
    case Interpolation_kind:
3772
0
        return &_PyTemplate_Type;
3773
0
    case JoinedStr_kind:
3774
0
    case FormattedValue_kind:
3775
0
        return &PyUnicode_Type;
3776
260
    case Constant_kind:
3777
260
        return Py_TYPE(e->v.Constant.value);
3778
224
    default:
3779
224
        return NULL;
3780
493
    }
3781
493
}
3782
3783
static int
3784
check_caller(compiler *c, expr_ty e)
3785
3.49k
{
3786
3.49k
    switch (e->kind) {
3787
0
    case Constant_kind:
3788
0
    case Tuple_kind:
3789
0
    case List_kind:
3790
0
    case ListComp_kind:
3791
0
    case Dict_kind:
3792
0
    case DictComp_kind:
3793
0
    case Set_kind:
3794
0
    case SetComp_kind:
3795
0
    case GeneratorExp_kind:
3796
0
    case JoinedStr_kind:
3797
0
    case TemplateStr_kind:
3798
0
    case FormattedValue_kind:
3799
0
    case Interpolation_kind: {
3800
0
        location loc = LOC(e);
3801
0
        return _PyCompile_Warn(c, loc, "'%.200s' object is not callable; "
3802
0
                                       "perhaps you missed a comma?",
3803
0
                                       infer_type(e)->tp_name);
3804
0
    }
3805
3.49k
    default:
3806
3.49k
        return SUCCESS;
3807
3.49k
    }
3808
3.49k
}
3809
3810
static int
3811
check_subscripter(compiler *c, expr_ty e)
3812
493
{
3813
493
    PyObject *v;
3814
3815
493
    switch (e->kind) {
3816
3
    case Constant_kind:
3817
3
        v = e->v.Constant.value;
3818
3
        if (!(v == Py_None || v == Py_Ellipsis ||
3819
3
              PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3820
3
              PyAnySet_Check(v)))
3821
3
        {
3822
3
            return SUCCESS;
3823
3
        }
3824
0
        _Py_FALLTHROUGH;
3825
0
    case Set_kind:
3826
0
    case SetComp_kind:
3827
0
    case GeneratorExp_kind:
3828
0
    case TemplateStr_kind:
3829
0
    case Interpolation_kind:
3830
0
    case Lambda_kind: {
3831
0
        location loc = LOC(e);
3832
0
        return _PyCompile_Warn(c, loc, "'%.200s' object is not subscriptable; "
3833
0
                                       "perhaps you missed a comma?",
3834
0
                                       infer_type(e)->tp_name);
3835
0
    }
3836
490
    default:
3837
490
        return SUCCESS;
3838
493
    }
3839
493
}
3840
3841
static int
3842
check_index(compiler *c, expr_ty e, expr_ty s)
3843
493
{
3844
493
    PyObject *v;
3845
3846
493
    PyTypeObject *index_type = infer_type(s);
3847
493
    if (index_type == NULL
3848
269
        || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
3849
480
        || index_type == &PySlice_Type) {
3850
480
        return SUCCESS;
3851
480
    }
3852
3853
13
    switch (e->kind) {
3854
0
    case Constant_kind:
3855
0
        v = e->v.Constant.value;
3856
0
        if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
3857
0
            return SUCCESS;
3858
0
        }
3859
0
        _Py_FALLTHROUGH;
3860
0
    case Tuple_kind:
3861
0
    case List_kind:
3862
0
    case ListComp_kind:
3863
0
    case JoinedStr_kind:
3864
0
    case FormattedValue_kind: {
3865
0
        location loc = LOC(e);
3866
0
        return _PyCompile_Warn(c, loc, "%.200s indices must be integers "
3867
0
                                       "or slices, not %.200s; "
3868
0
                                       "perhaps you missed a comma?",
3869
0
                                       infer_type(e)->tp_name,
3870
0
                                       index_type->tp_name);
3871
0
    }
3872
13
    default:
3873
13
        return SUCCESS;
3874
13
    }
3875
13
}
3876
3877
static int
3878
is_import_originated(compiler *c, expr_ty e)
3879
3.45k
{
3880
    /* Check whether the global scope has an import named
3881
     e, if it is a Name object. For not traversing all the
3882
     scope stack every time this function is called, it will
3883
     only check the global scope to determine whether something
3884
     is imported or not. */
3885
3886
3.45k
    if (e->kind != Name_kind) {
3887
649
        return 0;
3888
649
    }
3889
3890
2.80k
    long flags = _PyST_GetSymbol(SYMTABLE(c)->st_top, e->v.Name.id);
3891
2.80k
    RETURN_IF_ERROR(flags);
3892
2.80k
    return flags & DEF_IMPORT;
3893
2.80k
}
3894
3895
static int
3896
can_optimize_super_call(compiler *c, expr_ty attr)
3897
9.29k
{
3898
9.29k
    expr_ty e = attr->v.Attribute.value;
3899
9.29k
    if (e->kind != Call_kind ||
3900
402
        e->v.Call.func->kind != Name_kind ||
3901
358
        !_PyUnicode_EqualToASCIIString(e->v.Call.func->v.Name.id, "super") ||
3902
134
        _PyUnicode_EqualToASCIIString(attr->v.Attribute.attr, "__class__") ||
3903
9.16k
        asdl_seq_LEN(e->v.Call.keywords) != 0) {
3904
9.16k
        return 0;
3905
9.16k
    }
3906
134
    Py_ssize_t num_args = asdl_seq_LEN(e->v.Call.args);
3907
3908
134
    PyObject *super_name = e->v.Call.func->v.Name.id;
3909
    // detect statically-visible shadowing of 'super' name
3910
134
    int scope = _PyST_GetScope(SYMTABLE_ENTRY(c), super_name);
3911
134
    RETURN_IF_ERROR(scope);
3912
134
    if (scope != GLOBAL_IMPLICIT) {
3913
0
        return 0;
3914
0
    }
3915
134
    scope = _PyST_GetScope(SYMTABLE(c)->st_top, super_name);
3916
134
    RETURN_IF_ERROR(scope);
3917
134
    if (scope != 0) {
3918
0
        return 0;
3919
0
    }
3920
3921
134
    if (num_args == 2) {
3922
393
        for (Py_ssize_t i = 0; i < num_args; i++) {
3923
262
            expr_ty elt = asdl_seq_GET(e->v.Call.args, i);
3924
262
            if (elt->kind == Starred_kind) {
3925
0
                return 0;
3926
0
            }
3927
262
        }
3928
        // exactly two non-starred args; we can just load
3929
        // the provided args
3930
131
        return 1;
3931
131
    }
3932
3933
3
    if (num_args != 0) {
3934
0
        return 0;
3935
0
    }
3936
    // we need the following for zero-arg super():
3937
3938
    // enclosing function should have at least one argument
3939
3
    if (METADATA(c)->u_argcount == 0 &&
3940
0
        METADATA(c)->u_posonlyargcount == 0) {
3941
0
        return 0;
3942
0
    }
3943
    // __class__ cell should be available
3944
3
    if (_PyCompile_GetRefType(c, &_Py_ID(__class__)) == FREE) {
3945
3
        return 1;
3946
3
    }
3947
0
    return 0;
3948
3
}
3949
3950
static int
3951
134
load_args_for_super(compiler *c, expr_ty e) {
3952
134
    location loc = LOC(e);
3953
3954
    // load super() global
3955
134
    PyObject *super_name = e->v.Call.func->v.Name.id;
3956
134
    RETURN_IF_ERROR(codegen_nameop(c, LOC(e->v.Call.func), super_name, Load));
3957
3958
134
    if (asdl_seq_LEN(e->v.Call.args) == 2) {
3959
131
        VISIT(c, expr, asdl_seq_GET(e->v.Call.args, 0));
3960
131
        VISIT(c, expr, asdl_seq_GET(e->v.Call.args, 1));
3961
131
        return SUCCESS;
3962
131
    }
3963
3964
    // load __class__ cell
3965
3
    PyObject *name = &_Py_ID(__class__);
3966
3
    assert(_PyCompile_GetRefType(c, name) == FREE);
3967
3
    RETURN_IF_ERROR(codegen_nameop(c, loc, name, Load));
3968
3969
    // load self (first argument)
3970
3
    Py_ssize_t i = 0;
3971
3
    PyObject *key, *value;
3972
3
    if (!PyDict_Next(METADATA(c)->u_varnames, &i, &key, &value)) {
3973
0
        return ERROR;
3974
0
    }
3975
3
    RETURN_IF_ERROR(codegen_nameop(c, loc, key, Load));
3976
3977
3
    return SUCCESS;
3978
3
}
3979
3980
// If an attribute access spans multiple lines, update the current start
3981
// location to point to the attribute name.
3982
static location
3983
update_start_location_to_match_attr(compiler *c, location loc,
3984
                                    expr_ty attr)
3985
12.5k
{
3986
12.5k
    assert(attr->kind == Attribute_kind);
3987
12.5k
    if (loc.lineno != attr->end_lineno) {
3988
8
        loc.lineno = attr->end_lineno;
3989
8
        int len = (int)PyUnicode_GET_LENGTH(attr->v.Attribute.attr);
3990
8
        if (len <= attr->end_col_offset) {
3991
8
            loc.col_offset = attr->end_col_offset - len;
3992
8
        }
3993
0
        else {
3994
            // GH-94694: Somebody's compiling weird ASTs. Just drop the columns:
3995
0
            loc.col_offset = -1;
3996
0
            loc.end_col_offset = -1;
3997
0
        }
3998
        // Make sure the end position still follows the start position, even for
3999
        // weird ASTs:
4000
8
        loc.end_lineno = Py_MAX(loc.lineno, loc.end_lineno);
4001
8
        if (loc.lineno == loc.end_lineno) {
4002
8
            loc.end_col_offset = Py_MAX(loc.col_offset, loc.end_col_offset);
4003
8
        }
4004
8
    }
4005
12.5k
    return loc;
4006
12.5k
}
4007
4008
static int
4009
maybe_optimize_function_call(compiler *c, expr_ty e, jump_target_label end)
4010
3.49k
{
4011
3.49k
    asdl_expr_seq *args = e->v.Call.args;
4012
3.49k
    asdl_keyword_seq *kwds = e->v.Call.keywords;
4013
3.49k
    expr_ty func = e->v.Call.func;
4014
4015
3.49k
    if (! (func->kind == Name_kind &&
4016
2.58k
           asdl_seq_LEN(args) == 1 &&
4017
1.33k
           asdl_seq_LEN(kwds) == 0))
4018
2.20k
    {
4019
2.20k
        return 0;
4020
2.20k
    }
4021
4022
1.28k
    location loc = LOC(func);
4023
4024
1.28k
    expr_ty arg_expr = asdl_seq_GET(args, 0);
4025
4026
1.28k
    if (_PyUnicode_EqualToASCIIString(func->v.Name.id, "frozenset")
4027
5
        && (arg_expr->kind == Set_kind || arg_expr->kind == SetComp_kind)) {
4028
4
        if (arg_expr->kind == SetComp_kind) {
4029
            /* A comprehension that is not inlined returns its set from a
4030
               call, so a trace function may still hold a reference to it. */
4031
0
            PySTEntryObject *entry = _PySymtable_Lookup(SYMTABLE(c),
4032
0
                                                        (void *)arg_expr);
4033
0
            if (entry == NULL) {
4034
0
                return ERROR;
4035
0
            }
4036
0
            int is_inlined = (entry->ste_type == InlinedComprehensionBlock);
4037
0
            Py_DECREF(entry);
4038
0
            if (!is_inlined) {
4039
0
                return 0;
4040
0
            }
4041
0
        }
4042
4
        NEW_JUMP_TARGET_LABEL(c, skip_optimization);
4043
4044
4
        ADDOP_I(c, loc, COPY, 1);
4045
4
        ADDOP_I(c, loc, LOAD_COMMON_CONSTANT, CONSTANT_BUILTIN_FROZENSET);
4046
4
        ADDOP_COMPARE(c, loc, Is);
4047
4
        ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, skip_optimization);
4048
4
        ADDOP(c, loc, POP_TOP);
4049
4050
4
        VISIT(c, expr, arg_expr);
4051
4
        ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_FREEZE_SET);
4052
4053
4
        ADDOP_JUMP(c, loc, JUMP, end);
4054
4055
4
        USE_LABEL(c, skip_optimization);
4056
4
        return 1;
4057
4
    }
4058
4059
1.28k
    if (arg_expr->kind != GeneratorExp_kind) {
4060
1.27k
        return 0;
4061
1.27k
    }
4062
4063
10
    PySTEntryObject *generator_entry = _PySymtable_Lookup(SYMTABLE(c), (void *)arg_expr);
4064
10
    if (generator_entry->ste_coroutine) {
4065
0
        Py_DECREF(generator_entry);
4066
0
        return 0;
4067
0
    }
4068
10
    Py_DECREF(generator_entry);
4069
4070
10
    int optimized = 0;
4071
10
    NEW_JUMP_TARGET_LABEL(c, skip_optimization);
4072
4073
10
    int const_oparg = -1;
4074
10
    PyObject *initial_res = NULL;
4075
10
    int continue_jump_opcode = -1;
4076
10
    if (_PyUnicode_EqualToASCIIString(func->v.Name.id, "all")) {
4077
2
        const_oparg = CONSTANT_BUILTIN_ALL;
4078
2
        initial_res = Py_True;
4079
2
        continue_jump_opcode = POP_JUMP_IF_TRUE;
4080
2
    }
4081
8
    else if (_PyUnicode_EqualToASCIIString(func->v.Name.id, "any")) {
4082
2
        const_oparg = CONSTANT_BUILTIN_ANY;
4083
2
        initial_res = Py_False;
4084
2
        continue_jump_opcode = POP_JUMP_IF_FALSE;
4085
2
    }
4086
6
    else if (_PyUnicode_EqualToASCIIString(func->v.Name.id, "tuple")) {
4087
4
        const_oparg = CONSTANT_BUILTIN_TUPLE;
4088
4
    }
4089
2
    else if (_PyUnicode_EqualToASCIIString(func->v.Name.id, "list")) {
4090
0
        const_oparg = CONSTANT_BUILTIN_LIST;
4091
0
    }
4092
2
    else if (_PyUnicode_EqualToASCIIString(func->v.Name.id, "set")) {
4093
0
        const_oparg = CONSTANT_BUILTIN_SET;
4094
0
    }
4095
2
    else if (_PyUnicode_EqualToASCIIString(func->v.Name.id, "frozenset")) {
4096
0
        const_oparg = CONSTANT_BUILTIN_FROZENSET;
4097
0
    }
4098
10
    if (const_oparg != -1) {
4099
8
        ADDOP_I(c, loc, COPY, 1); // the function
4100
8
        ADDOP_I(c, loc, LOAD_COMMON_CONSTANT, const_oparg);
4101
8
        ADDOP_COMPARE(c, loc, Is);
4102
8
        ADDOP_JUMP(c, loc, POP_JUMP_IF_FALSE, skip_optimization);
4103
8
        ADDOP(c, loc, POP_TOP);
4104
4105
8
        if (const_oparg == CONSTANT_BUILTIN_TUPLE || const_oparg == CONSTANT_BUILTIN_LIST) {
4106
4
            ADDOP_I(c, loc, BUILD_LIST, 0);
4107
4
        } else if (const_oparg == CONSTANT_BUILTIN_SET || const_oparg == CONSTANT_BUILTIN_FROZENSET) {
4108
0
            ADDOP_I(c, loc, BUILD_SET, 0);
4109
0
        }
4110
8
        VISIT(c, expr, arg_expr);
4111
4112
8
        NEW_JUMP_TARGET_LABEL(c, loop);
4113
8
        NEW_JUMP_TARGET_LABEL(c, cleanup);
4114
4115
8
        ADDOP(c, loc, PUSH_NULL); // Push NULL index for loop
4116
8
        USE_LABEL(c, loop);
4117
8
        ADDOP_JUMP(c, loc, FOR_ITER, cleanup);
4118
8
        if (const_oparg == CONSTANT_BUILTIN_TUPLE || const_oparg == CONSTANT_BUILTIN_LIST) {
4119
4
            ADDOP_I(c, loc, LIST_APPEND, 3);
4120
4
            ADDOP_JUMP(c, loc, JUMP, loop);
4121
4
        } else if (const_oparg == CONSTANT_BUILTIN_SET || const_oparg == CONSTANT_BUILTIN_FROZENSET) {
4122
0
            ADDOP_I(c, loc, SET_ADD, 3);
4123
0
            ADDOP_JUMP(c, loc, JUMP, loop);
4124
0
        }
4125
4
        else {
4126
4
            ADDOP(c, loc, TO_BOOL);
4127
4
            ADDOP_JUMP(c, loc, continue_jump_opcode, loop);
4128
4
        }
4129
4130
8
        ADDOP(c, NO_LOCATION, POP_ITER);
4131
8
        if (const_oparg != CONSTANT_BUILTIN_TUPLE &&
4132
4
            const_oparg != CONSTANT_BUILTIN_LIST &&
4133
4
            const_oparg != CONSTANT_BUILTIN_SET &&
4134
4
            const_oparg != CONSTANT_BUILTIN_FROZENSET) {
4135
4
            ADDOP_LOAD_CONST(c, loc, initial_res == Py_True ? Py_False : Py_True);
4136
4
        }
4137
8
        ADDOP_JUMP(c, loc, JUMP, end);
4138
4139
8
        USE_LABEL(c, cleanup);
4140
8
        ADDOP(c, NO_LOCATION, END_FOR);
4141
8
        ADDOP(c, NO_LOCATION, POP_ITER);
4142
8
        if (const_oparg == CONSTANT_BUILTIN_TUPLE) {
4143
4
            ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_LIST_TO_TUPLE);
4144
4
        } else if (const_oparg == CONSTANT_BUILTIN_LIST) {
4145
            // result is already a list
4146
4
        } else if (const_oparg == CONSTANT_BUILTIN_SET) {
4147
            // result is already a set
4148
0
        }
4149
4
        else if (const_oparg == CONSTANT_BUILTIN_FROZENSET) {
4150
0
            ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_FREEZE_SET);
4151
0
        }
4152
4
        else {
4153
4
            ADDOP_LOAD_CONST(c, loc, initial_res);
4154
4
        }
4155
4156
8
        optimized = 1;
4157
8
        ADDOP_JUMP(c, loc, JUMP, end);
4158
8
    }
4159
10
    USE_LABEL(c, skip_optimization);
4160
10
    return optimized;
4161
10
}
4162
4163
// Return 1 if the method call was optimized, 0 if not, and -1 on error.
4164
static int
4165
maybe_optimize_method_call(compiler *c, expr_ty e)
4166
6.04k
{
4167
6.04k
    Py_ssize_t argsl, i, kwdsl;
4168
6.04k
    expr_ty meth = e->v.Call.func;
4169
6.04k
    asdl_expr_seq *args = e->v.Call.args;
4170
6.04k
    asdl_keyword_seq *kwds = e->v.Call.keywords;
4171
4172
    /* Check that the call node is an attribute access */
4173
6.04k
    if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load) {
4174
2.58k
        return 0;
4175
2.58k
    }
4176
4177
    /* Check that the base object is not something that is imported */
4178
3.45k
    int ret = is_import_originated(c, meth->v.Attribute.value);
4179
3.45k
    RETURN_IF_ERROR(ret);
4180
3.45k
    if (ret) {
4181
895
        return 0;
4182
895
    }
4183
4184
    /* Check that there aren't too many arguments */
4185
2.55k
    argsl = asdl_seq_LEN(args);
4186
2.55k
    kwdsl = asdl_seq_LEN(kwds);
4187
2.55k
    if (CALL_STACK_USE(argsl, kwdsl) >= _PY_STACK_USE_GUIDELINE) {
4188
0
        return 0;
4189
0
    }
4190
    /* Check that there are no *varargs types of arguments. */
4191
6.40k
    for (i = 0; i < argsl; i++) {
4192
3.85k
        expr_ty elt = asdl_seq_GET(args, i);
4193
3.85k
        if (elt->kind == Starred_kind) {
4194
10
            return 0;
4195
10
        }
4196
3.85k
    }
4197
4198
2.67k
    for (i = 0; i < kwdsl; i++) {
4199
126
        keyword_ty kw = asdl_seq_GET(kwds, i);
4200
126
        if (kw->arg == NULL) {
4201
0
            return 0;
4202
0
        }
4203
126
    }
4204
4205
    /* Alright, we can optimize the code. */
4206
2.54k
    location loc = LOC(meth);
4207
4208
2.54k
    ret = can_optimize_super_call(c, meth);
4209
2.54k
    RETURN_IF_ERROR(ret);
4210
2.54k
    if (ret) {
4211
133
        RETURN_IF_ERROR(load_args_for_super(c, meth->v.Attribute.value));
4212
133
        int opcode = asdl_seq_LEN(meth->v.Attribute.value->v.Call.args) ?
4213
131
            LOAD_SUPER_METHOD : LOAD_ZERO_SUPER_METHOD;
4214
133
        ADDOP_NAME(c, loc, opcode, meth->v.Attribute.attr, names);
4215
133
        loc = update_start_location_to_match_attr(c, loc, meth);
4216
133
        ADDOP(c, loc, NOP);
4217
2.41k
    } else {
4218
2.41k
        VISIT(c, expr, meth->v.Attribute.value);
4219
2.41k
        loc = update_start_location_to_match_attr(c, loc, meth);
4220
2.41k
        ADDOP_NAME(c, loc, LOAD_METHOD, meth->v.Attribute.attr, names);
4221
2.41k
    }
4222
4223
2.54k
    VISIT_SEQ(c, expr, e->v.Call.args);
4224
4225
2.54k
    if (kwdsl) {
4226
77
        VISIT_SEQ(c, keyword, kwds);
4227
77
        RETURN_IF_ERROR(
4228
77
            codegen_call_simple_kw_helper(c, loc, kwds, kwdsl));
4229
77
        loc = update_start_location_to_match_attr(c, LOC(e), meth);
4230
77
        ADDOP_I(c, loc, CALL_KW, argsl + kwdsl);
4231
77
    }
4232
2.47k
    else {
4233
2.47k
        loc = update_start_location_to_match_attr(c, LOC(e), meth);
4234
2.47k
        ADDOP_I(c, loc, CALL, argsl);
4235
2.47k
    }
4236
2.54k
    return 1;
4237
2.54k
}
4238
4239
static int
4240
codegen_validate_keywords(compiler *c, asdl_keyword_seq *keywords)
4241
10.1k
{
4242
10.1k
    Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4243
13.0k
    for (Py_ssize_t i = 0; i < nkeywords; i++) {
4244
2.87k
        keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4245
2.87k
        if (key->arg == NULL) {
4246
34
            continue;
4247
34
        }
4248
9.63k
        for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
4249
6.78k
            keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4250
6.78k
            if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4251
0
                return _PyCompile_Error(c, LOC(other), "keyword argument repeated: %U", key->arg);
4252
0
            }
4253
6.78k
        }
4254
2.84k
    }
4255
10.1k
    return SUCCESS;
4256
10.1k
}
4257
4258
static int
4259
codegen_call(compiler *c, expr_ty e)
4260
6.04k
{
4261
6.04k
    RETURN_IF_ERROR(codegen_validate_keywords(c, e->v.Call.keywords));
4262
6.04k
    int ret = maybe_optimize_method_call(c, e);
4263
6.04k
    if (ret < 0) {
4264
0
        return ERROR;
4265
0
    }
4266
6.04k
    if (ret == 1) {
4267
2.54k
        return SUCCESS;
4268
2.54k
    }
4269
3.49k
    NEW_JUMP_TARGET_LABEL(c, skip_normal_call);
4270
3.49k
    RETURN_IF_ERROR(check_caller(c, e->v.Call.func));
4271
3.49k
    VISIT(c, expr, e->v.Call.func);
4272
3.49k
    RETURN_IF_ERROR(maybe_optimize_function_call(c, e, skip_normal_call));
4273
3.49k
    location loc = LOC(e->v.Call.func);
4274
3.49k
    ADDOP(c, loc, PUSH_NULL);
4275
3.49k
    loc = LOC(e);
4276
3.49k
    ret = codegen_call_helper(c, loc, 0,
4277
3.49k
                              e->v.Call.args,
4278
3.49k
                              e->v.Call.keywords);
4279
3.49k
    USE_LABEL(c, skip_normal_call);
4280
3.49k
    return ret;
4281
3.49k
}
4282
4283
static int
4284
codegen_template_str(compiler *c, expr_ty e)
4285
1
{
4286
1
    location loc = LOC(e);
4287
1
    expr_ty value;
4288
4289
1
    Py_ssize_t value_count = asdl_seq_LEN(e->v.TemplateStr.values);
4290
1
    int last_was_interpolation = 1;
4291
1
    Py_ssize_t stringslen = 0;
4292
2
    for (Py_ssize_t i = 0; i < value_count; i++) {
4293
1
        value = asdl_seq_GET(e->v.TemplateStr.values, i);
4294
1
        if (value->kind == Interpolation_kind) {
4295
1
            if (last_was_interpolation) {
4296
1
                ADDOP_LOAD_CONST(c, loc, Py_NewRef(&_Py_STR(empty)));
4297
1
                stringslen++;
4298
1
            }
4299
1
            last_was_interpolation = 1;
4300
1
        }
4301
0
        else {
4302
0
            VISIT(c, expr, value);
4303
0
            stringslen++;
4304
0
            last_was_interpolation = 0;
4305
0
        }
4306
1
    }
4307
1
    if (last_was_interpolation) {
4308
1
        ADDOP_LOAD_CONST(c, loc, Py_NewRef(&_Py_STR(empty)));
4309
1
        stringslen++;
4310
1
    }
4311
1
    ADDOP_I(c, loc, BUILD_TUPLE, stringslen);
4312
4313
1
    Py_ssize_t interpolationslen = 0;
4314
2
    for (Py_ssize_t i = 0; i < value_count; i++) {
4315
1
        value = asdl_seq_GET(e->v.TemplateStr.values, i);
4316
1
        if (value->kind == Interpolation_kind) {
4317
1
            VISIT(c, expr, value);
4318
1
            interpolationslen++;
4319
1
        }
4320
1
    }
4321
1
    ADDOP_I(c, loc, BUILD_TUPLE, interpolationslen);
4322
1
    ADDOP(c, loc, BUILD_TEMPLATE);
4323
1
    return SUCCESS;
4324
1
}
4325
4326
static int
4327
codegen_joined_str(compiler *c, expr_ty e)
4328
407
{
4329
407
    location loc = LOC(e);
4330
407
    Py_ssize_t value_count = asdl_seq_LEN(e->v.JoinedStr.values);
4331
407
    if (value_count > _PY_STACK_USE_GUIDELINE) {
4332
3
        _Py_DECLARE_STR(empty, "");
4333
3
        ADDOP_LOAD_CONST_NEW(c, loc, Py_NewRef(&_Py_STR(empty)));
4334
3
        ADDOP_NAME(c, loc, LOAD_METHOD, &_Py_ID(join), names);
4335
3
        ADDOP_I(c, loc, BUILD_LIST, 0);
4336
137
        for (Py_ssize_t i = 0; i < asdl_seq_LEN(e->v.JoinedStr.values); i++) {
4337
134
            VISIT(c, expr, asdl_seq_GET(e->v.JoinedStr.values, i));
4338
134
            ADDOP_I(c, loc, LIST_APPEND, 1);
4339
134
        }
4340
3
        ADDOP_I(c, loc, CALL, 1);
4341
3
    }
4342
404
    else {
4343
404
        VISIT_SEQ(c, expr, e->v.JoinedStr.values);
4344
404
        if (value_count > 1) {
4345
398
            ADDOP_I(c, loc, BUILD_STRING, value_count);
4346
398
        }
4347
6
        else if (value_count == 0) {
4348
0
            _Py_DECLARE_STR(empty, "");
4349
0
            ADDOP_LOAD_CONST_NEW(c, loc, Py_NewRef(&_Py_STR(empty)));
4350
0
        }
4351
404
    }
4352
407
    return SUCCESS;
4353
407
}
4354
4355
static int
4356
codegen_interpolation(compiler *c, expr_ty e)
4357
1
{
4358
1
    location loc = LOC(e);
4359
4360
1
    VISIT(c, expr, e->v.Interpolation.value);
4361
1
    ADDOP_LOAD_CONST(c, loc, e->v.Interpolation.str);
4362
4363
1
    int oparg = 2;
4364
1
    if (e->v.Interpolation.format_spec) {
4365
0
        oparg++;
4366
0
        VISIT(c, expr, e->v.Interpolation.format_spec);
4367
0
    }
4368
4369
1
    int conversion = e->v.Interpolation.conversion;
4370
1
    if (conversion != -1) {
4371
0
        switch (conversion) {
4372
0
        case 's': oparg |= FVC_STR << 2;   break;
4373
0
        case 'r': oparg |= FVC_REPR << 2;  break;
4374
0
        case 'a': oparg |= FVC_ASCII << 2; break;
4375
0
        default:
4376
0
            PyErr_Format(PyExc_SystemError,
4377
0
                     "Unrecognized conversion character %d", conversion);
4378
0
            return ERROR;
4379
0
        }
4380
0
    }
4381
4382
1
    ADDOP_I(c, loc, BUILD_INTERPOLATION, oparg);
4383
1
    return SUCCESS;
4384
1
}
4385
4386
/* Used to implement f-strings. Format a single value. */
4387
static int
4388
codegen_formatted_value(compiler *c, expr_ty e)
4389
1.12k
{
4390
1.12k
    int conversion = e->v.FormattedValue.conversion;
4391
1.12k
    int oparg;
4392
4393
    /* The expression to be formatted. */
4394
1.12k
    VISIT(c, expr, e->v.FormattedValue.value);
4395
4396
1.12k
    location loc = LOC(e);
4397
1.12k
    if (conversion != -1) {
4398
847
        switch (conversion) {
4399
111
        case 's': oparg = FVC_STR;   break;
4400
736
        case 'r': oparg = FVC_REPR;  break;
4401
0
        case 'a': oparg = FVC_ASCII; break;
4402
0
        default:
4403
0
            PyErr_Format(PyExc_SystemError,
4404
0
                     "Unrecognized conversion character %d", conversion);
4405
0
            return ERROR;
4406
847
        }
4407
847
        ADDOP_I(c, loc, CONVERT_VALUE, oparg);
4408
847
    }
4409
1.12k
    if (e->v.FormattedValue.format_spec) {
4410
        /* Evaluate the format spec, and update our opcode arg. */
4411
3
        VISIT(c, expr, e->v.FormattedValue.format_spec);
4412
3
        ADDOP(c, loc, FORMAT_WITH_SPEC);
4413
1.11k
    } else {
4414
1.11k
        ADDOP(c, loc, FORMAT_SIMPLE);
4415
1.11k
    }
4416
1.12k
    return SUCCESS;
4417
1.12k
}
4418
4419
static int
4420
codegen_subkwargs(compiler *c, location loc,
4421
                  asdl_keyword_seq *keywords,
4422
                  Py_ssize_t begin, Py_ssize_t end)
4423
2
{
4424
2
    Py_ssize_t i, n = end - begin;
4425
2
    keyword_ty kw;
4426
2
    assert(n > 0);
4427
2
    int big = n*2 > _PY_STACK_USE_GUIDELINE;
4428
2
    if (big) {
4429
0
        ADDOP_I(c, NO_LOCATION, BUILD_MAP, 0);
4430
0
    }
4431
4
    for (i = begin; i < end; i++) {
4432
2
        kw = asdl_seq_GET(keywords, i);
4433
2
        ADDOP_LOAD_CONST(c, loc, kw->arg);
4434
2
        VISIT(c, expr, kw->value);
4435
2
        if (big) {
4436
0
            ADDOP_I(c, NO_LOCATION, MAP_ADD, 1);
4437
0
        }
4438
2
    }
4439
2
    if (!big) {
4440
2
        ADDOP_I(c, loc, BUILD_MAP, n);
4441
2
    }
4442
2
    return SUCCESS;
4443
2
}
4444
4445
/* Used by codegen_call_helper and maybe_optimize_method_call to emit
4446
 * a tuple of keyword names before CALL.
4447
 */
4448
static int
4449
codegen_call_simple_kw_helper(compiler *c, location loc,
4450
                              asdl_keyword_seq *keywords, Py_ssize_t nkwelts)
4451
432
{
4452
432
    PyObject *names;
4453
432
    names = PyTuple_New(nkwelts);
4454
432
    if (names == NULL) {
4455
0
        return ERROR;
4456
0
    }
4457
1.91k
    for (Py_ssize_t i = 0; i < nkwelts; i++) {
4458
1.48k
        keyword_ty kw = asdl_seq_GET(keywords, i);
4459
1.48k
        PyTuple_SET_ITEM(names, i, Py_NewRef(kw->arg));
4460
1.48k
    }
4461
432
    ADDOP_LOAD_CONST_NEW(c, loc, names);
4462
432
    return SUCCESS;
4463
432
}
4464
4465
/* shared code between codegen_call and codegen_class */
4466
static int
4467
codegen_call_helper_impl(compiler *c, location loc,
4468
                         int n, /* Args already pushed */
4469
                         asdl_expr_seq *args,
4470
                         PyObject *injected_arg,
4471
                         asdl_keyword_seq *keywords)
4472
4.12k
{
4473
4.12k
    Py_ssize_t i, nseen, nelts, nkwelts;
4474
4475
4.12k
    RETURN_IF_ERROR(codegen_validate_keywords(c, keywords));
4476
4477
4.12k
    nelts = asdl_seq_LEN(args);
4478
4.12k
    nkwelts = asdl_seq_LEN(keywords);
4479
4480
4.12k
    if (CALL_STACK_USE(nelts, nkwelts) > _PY_STACK_USE_GUIDELINE) {
4481
0
         goto ex_call;
4482
0
    }
4483
9.34k
    for (i = 0; i < nelts; i++) {
4484
5.25k
        expr_ty elt = asdl_seq_GET(args, i);
4485
5.25k
        if (elt->kind == Starred_kind) {
4486
35
            goto ex_call;
4487
35
        }
4488
5.25k
    }
4489
5.44k
    for (i = 0; i < nkwelts; i++) {
4490
1.35k
        keyword_ty kw = asdl_seq_GET(keywords, i);
4491
1.35k
        if (kw->arg == NULL) {
4492
1
            goto ex_call;
4493
1
        }
4494
1.35k
    }
4495
4496
    /* No * or ** args, so can use faster calling sequence */
4497
9.28k
    for (i = 0; i < nelts; i++) {
4498
5.19k
        expr_ty elt = asdl_seq_GET(args, i);
4499
5.19k
        assert(elt->kind != Starred_kind);
4500
5.19k
        VISIT(c, expr, elt);
4501
5.19k
    }
4502
4.08k
    if (injected_arg) {
4503
0
        RETURN_IF_ERROR(codegen_nameop(c, loc, injected_arg, Load));
4504
0
        nelts++;
4505
0
    }
4506
4.08k
    if (nkwelts) {
4507
355
        VISIT_SEQ(c, keyword, keywords);
4508
355
        RETURN_IF_ERROR(
4509
355
            codegen_call_simple_kw_helper(c, loc, keywords, nkwelts));
4510
355
        ADDOP_I(c, loc, CALL_KW, n + nelts + nkwelts);
4511
355
    }
4512
3.73k
    else {
4513
3.73k
        ADDOP_I(c, loc, CALL, n + nelts);
4514
3.73k
    }
4515
4.08k
    return SUCCESS;
4516
4517
36
ex_call:
4518
4519
    /* Do positional arguments. */
4520
36
    if (n == 0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4521
17
        VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4522
17
    }
4523
19
    else {
4524
19
        RETURN_IF_ERROR(starunpack_helper_impl(c, loc, args, injected_arg, n,
4525
19
                                               BUILD_LIST, LIST_APPEND, LIST_EXTEND, 1));
4526
19
    }
4527
    /* Then keyword arguments */
4528
36
    if (nkwelts) {
4529
        /* Has a new dict been pushed */
4530
18
        int have_dict = 0;
4531
4532
18
        nseen = 0;  /* the number of keyword arguments on the stack following */
4533
37
        for (i = 0; i < nkwelts; i++) {
4534
19
            keyword_ty kw = asdl_seq_GET(keywords, i);
4535
19
            if (kw->arg == NULL) {
4536
                /* A keyword argument unpacking. */
4537
17
                if (nseen) {
4538
1
                    RETURN_IF_ERROR(codegen_subkwargs(c, loc, keywords, i - nseen, i));
4539
1
                    if (have_dict) {
4540
0
                        ADDOP_I(c, loc, DICT_MERGE, 1);
4541
0
                    }
4542
1
                    have_dict = 1;
4543
1
                    nseen = 0;
4544
1
                }
4545
17
                if (!have_dict) {
4546
16
                    ADDOP_I(c, loc, BUILD_MAP, 0);
4547
16
                    have_dict = 1;
4548
16
                }
4549
17
                VISIT(c, expr, kw->value);
4550
17
                ADDOP_I(c, loc, DICT_MERGE, 1);
4551
17
            }
4552
2
            else {
4553
2
                nseen++;
4554
2
            }
4555
19
        }
4556
18
        if (nseen) {
4557
            /* Pack up any trailing keyword arguments. */
4558
1
            RETURN_IF_ERROR(codegen_subkwargs(c, loc, keywords, nkwelts - nseen, nkwelts));
4559
1
            if (have_dict) {
4560
0
                ADDOP_I(c, loc, DICT_MERGE, 1);
4561
0
            }
4562
1
            have_dict = 1;
4563
1
        }
4564
18
        assert(have_dict);
4565
18
    }
4566
36
    if (nkwelts == 0) {
4567
18
        ADDOP(c, loc, PUSH_NULL);
4568
18
    }
4569
36
    ADDOP(c, loc, CALL_FUNCTION_EX);
4570
36
    return SUCCESS;
4571
36
}
4572
4573
static int
4574
codegen_call_helper(compiler *c, location loc,
4575
                    int n, /* Args already pushed */
4576
                    asdl_expr_seq *args,
4577
                    asdl_keyword_seq *keywords)
4578
4.12k
{
4579
4.12k
    return codegen_call_helper_impl(c, loc, n, args, NULL, keywords);
4580
4.12k
}
4581
4582
/* List and set comprehensions work by being inlined at the location where
4583
  they are defined. The isolation of iteration variables is provided by
4584
  pushing/popping clashing locals on the stack. Generator expressions work
4585
  by creating a nested function to perform the actual iteration.
4586
  This means that the iteration variables don't leak into the current scope.
4587
  See https://peps.python.org/pep-0709/ for additional information.
4588
  The defined function is called immediately following its definition, with the
4589
  result of that call being the result of the expression.
4590
  The LC/SC version returns the populated container, while the GE version is
4591
  flagged in symtable.c as a generator, so it returns the generator object
4592
  when the function is called.
4593
4594
  Possible cleanups:
4595
    - iterate over the generator sequence instead of using recursion
4596
*/
4597
4598
4599
static int
4600
codegen_comprehension_generator(compiler *c, location loc,
4601
                                asdl_comprehension_seq *generators, int gen_index,
4602
                                int depth,
4603
                                expr_ty elt, expr_ty val, int type,
4604
                                IterStackPosition iter_pos, bool avoid_creation)
4605
55
{
4606
55
    comprehension_ty gen;
4607
55
    gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4608
55
    if (gen->is_async) {
4609
0
        return codegen_async_comprehension_generator(
4610
0
            c, loc, generators, gen_index, depth, elt, val, type,
4611
0
            iter_pos, avoid_creation);
4612
55
    } else {
4613
55
        return codegen_sync_comprehension_generator(
4614
55
            c, loc, generators, gen_index, depth, elt, val, type,
4615
55
            iter_pos, avoid_creation);
4616
55
    }
4617
55
}
4618
4619
static int
4620
codegen_unpack_starred(compiler *c, location loc, expr_ty value, bool yield)
4621
0
{
4622
0
    NEW_JUMP_TARGET_LABEL(c, unpack_start);
4623
0
    NEW_JUMP_TARGET_LABEL(c, unpack_end);
4624
0
    VISIT(c, expr, value);
4625
0
    ADDOP_I(c, loc, GET_ITER, 0);
4626
0
    USE_LABEL(c, unpack_start);
4627
0
    ADDOP_JUMP(c, loc, FOR_ITER, unpack_end);
4628
0
    if (yield) {
4629
0
        ADDOP_YIELD(c, loc);
4630
0
    }
4631
0
    ADDOP(c, loc, POP_TOP);
4632
0
    ADDOP_JUMP(c, NO_LOCATION, JUMP, unpack_start);
4633
0
    USE_LABEL(c, unpack_end);
4634
0
    ADDOP(c, NO_LOCATION, END_FOR);
4635
0
    ADDOP(c, NO_LOCATION, POP_ITER);
4636
0
    return SUCCESS;
4637
0
}
4638
4639
static int
4640
codegen_comprehension_generator_helper(compiler *c, location elt_loc, int depth,
4641
                                       expr_ty elt, expr_ty val, int type,
4642
                                       bool avoid_creation)
4643
55
{
4644
55
    switch (type) {
4645
24
    case COMP_GENEXP:
4646
24
        assert(!avoid_creation);
4647
24
        if (elt->kind == Starred_kind) {
4648
0
            RETURN_IF_ERROR(codegen_unpack_starred(c, elt_loc, elt->v.Starred.value, /*yield=*/true));
4649
0
        }
4650
24
        else {
4651
24
            VISIT(c, expr, elt);
4652
24
            ADDOP_YIELD(c, elt_loc);
4653
24
            ADDOP(c, elt_loc, POP_TOP);
4654
24
        }
4655
24
        break;
4656
25
    case COMP_LISTCOMP:
4657
25
        if (avoid_creation) {
4658
0
            if (elt->kind == Starred_kind) {
4659
0
                RETURN_IF_ERROR(codegen_unpack_starred(c, elt_loc, elt->v.Starred.value, /*yield=*/false));
4660
0
            } else {
4661
0
                VISIT(c, expr, elt);
4662
0
                ADDOP(c, elt_loc, POP_TOP);
4663
0
            }
4664
0
            break;
4665
0
        }
4666
25
        if (elt->kind == Starred_kind) {
4667
0
            VISIT(c, expr, elt->v.Starred.value);
4668
0
            ADDOP_I(c, elt_loc, LIST_EXTEND, depth + 1);
4669
0
        }
4670
25
        else {
4671
25
            VISIT(c, expr, elt);
4672
25
            ADDOP_I(c, elt_loc, LIST_APPEND, depth + 1);
4673
25
        }
4674
25
        break;
4675
25
    case COMP_SETCOMP:
4676
1
        assert(!avoid_creation);
4677
1
        if (elt->kind == Starred_kind) {
4678
0
            VISIT(c, expr, elt->v.Starred.value);
4679
0
            ADDOP_I(c, elt_loc, SET_UPDATE, depth + 1);
4680
0
        }
4681
1
        else {
4682
1
            VISIT(c, expr, elt);
4683
1
            ADDOP_I(c, elt_loc, SET_ADD, depth + 1);
4684
1
        }
4685
1
        break;
4686
5
    case COMP_DICTCOMP:
4687
5
        assert(!avoid_creation);
4688
5
        if (val == NULL) {
4689
            /* unpacking (**) case */
4690
0
            VISIT(c, expr, elt);
4691
0
            ADDOP_I(c, elt_loc, DICT_UPDATE, depth + 1);
4692
0
        }
4693
5
        else {
4694
            /* With '{k: v}', k is evaluated before v, so we do
4695
            the same. */
4696
5
            VISIT(c, expr, elt);
4697
5
            VISIT(c, expr, val);
4698
5
            elt_loc = LOCATION(elt->lineno,
4699
5
                               val->end_lineno,
4700
5
                               elt->col_offset,
4701
5
                               val->end_col_offset);
4702
5
            ADDOP_I(c, elt_loc, MAP_ADD, depth + 1);
4703
5
        }
4704
5
        break;
4705
5
    default:
4706
0
        return ERROR;
4707
55
    }
4708
55
    return SUCCESS;
4709
55
}
4710
4711
static int
4712
codegen_sync_comprehension_generator(compiler *c, location loc,
4713
                                     asdl_comprehension_seq *generators,
4714
                                     int gen_index, int depth,
4715
                                     expr_ty elt, expr_ty val, int type,
4716
                                     IterStackPosition iter_pos, bool avoid_creation)
4717
55
{
4718
    /* generate code for the iterator, then each of the ifs,
4719
       and then write to the element */
4720
4721
55
    NEW_JUMP_TARGET_LABEL(c, start);
4722
55
    NEW_JUMP_TARGET_LABEL(c, if_cleanup);
4723
55
    NEW_JUMP_TARGET_LABEL(c, anchor);
4724
4725
55
    comprehension_ty gen = (comprehension_ty)asdl_seq_GET(generators,
4726
55
                                                          gen_index);
4727
4728
55
    if (iter_pos == ITERABLE_IN_LOCAL) {
4729
0
        if (gen_index == 0) {
4730
0
            assert(METADATA(c)->u_argcount == 1);
4731
0
            ADDOP_I(c, loc, LOAD_FAST, 0);
4732
0
        }
4733
0
        else {
4734
            /* Sub-iter - calculate on the fly */
4735
            /* Fast path for the temporary variable assignment idiom:
4736
                for y in [f(x)]
4737
            */
4738
0
            asdl_expr_seq *elts;
4739
0
            switch (gen->iter->kind) {
4740
0
                case List_kind:
4741
0
                    elts = gen->iter->v.List.elts;
4742
0
                    break;
4743
0
                case Tuple_kind:
4744
0
                    elts = gen->iter->v.Tuple.elts;
4745
0
                    break;
4746
0
                default:
4747
0
                    elts = NULL;
4748
0
            }
4749
0
            if (asdl_seq_LEN(elts) == 1) {
4750
0
                expr_ty elt = asdl_seq_GET(elts, 0);
4751
0
                if (elt->kind != Starred_kind) {
4752
0
                    VISIT(c, expr, elt);
4753
0
                    start = NO_LABEL;
4754
0
                }
4755
0
            }
4756
0
            if (IS_JUMP_TARGET_LABEL(start)) {
4757
0
                VISIT(c, expr, gen->iter);
4758
0
            }
4759
0
        }
4760
0
    }
4761
4762
55
    if (IS_JUMP_TARGET_LABEL(start)) {
4763
55
        if (iter_pos != ITERATOR_ON_STACK) {
4764
31
            ADDOP_I(c, LOC(gen->iter), GET_ITER, 0);
4765
31
            depth += 1;
4766
31
        }
4767
55
        USE_LABEL(c, start);
4768
55
        depth += 1;
4769
55
        ADDOP_JUMP(c, LOC(gen->iter), FOR_ITER, anchor);
4770
55
    }
4771
55
    VISIT(c, expr, gen->target);
4772
4773
    /* XXX this needs to be cleaned up...a lot! */
4774
55
    Py_ssize_t n = asdl_seq_LEN(gen->ifs);
4775
66
    for (Py_ssize_t i = 0; i < n; i++) {
4776
11
        expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
4777
11
        RETURN_IF_ERROR(codegen_jump_if(c, loc, e, if_cleanup, 0));
4778
11
    }
4779
4780
55
    if (++gen_index < asdl_seq_LEN(generators)) {
4781
0
        RETURN_IF_ERROR(
4782
0
            codegen_comprehension_generator(c, loc,
4783
0
                                            generators, gen_index, depth,
4784
0
                                            elt, val, type, ITERABLE_IN_LOCAL, avoid_creation));
4785
0
    }
4786
4787
55
    location elt_loc = LOC(elt);
4788
4789
    /* only append after the last for generator */
4790
55
    if (gen_index >= asdl_seq_LEN(generators)) {
4791
        /* comprehension specific code */
4792
55
        RETURN_IF_ERROR(codegen_comprehension_generator_helper(c, elt_loc, depth,
4793
55
                                                               elt, val, type,
4794
55
                                                               avoid_creation));
4795
55
        if (type == COMP_DICTCOMP && val != NULL) {
4796
5
            elt_loc = LOCATION(elt->lineno,
4797
5
                               val->end_lineno,
4798
5
                               elt->col_offset,
4799
5
                               val->end_col_offset);
4800
5
        }
4801
55
    }
4802
4803
55
    USE_LABEL(c, if_cleanup);
4804
55
    if (IS_JUMP_TARGET_LABEL(start)) {
4805
55
        ADDOP_JUMP(c, elt_loc, JUMP, start);
4806
4807
55
        USE_LABEL(c, anchor);
4808
        /* It is important for instrumentation that the `END_FOR` comes first.
4809
        * Iteration over a generator will jump to the first of these instructions,
4810
        * but a non-generator will jump to a later instruction.
4811
        */
4812
55
        ADDOP(c, NO_LOCATION, END_FOR);
4813
55
        ADDOP(c, NO_LOCATION, POP_ITER);
4814
55
    }
4815
4816
55
    return SUCCESS;
4817
55
}
4818
4819
static int
4820
codegen_async_comprehension_generator(compiler *c, location loc,
4821
                                      asdl_comprehension_seq *generators,
4822
                                      int gen_index, int depth,
4823
                                      expr_ty elt, expr_ty val, int type,
4824
                                      IterStackPosition iter_pos, bool avoid_creation)
4825
0
{
4826
0
    NEW_JUMP_TARGET_LABEL(c, start);
4827
0
    NEW_JUMP_TARGET_LABEL(c, send);
4828
0
    NEW_JUMP_TARGET_LABEL(c, except);
4829
0
    NEW_JUMP_TARGET_LABEL(c, if_cleanup);
4830
4831
0
    comprehension_ty gen = (comprehension_ty)asdl_seq_GET(generators,
4832
0
                                                          gen_index);
4833
4834
0
    if (iter_pos == ITERABLE_IN_LOCAL) {
4835
0
        if (gen_index == 0) {
4836
0
            assert(METADATA(c)->u_argcount == 1);
4837
0
            ADDOP_I(c, loc, LOAD_FAST, 0);
4838
0
        }
4839
0
        else {
4840
            /* Sub-iter - calculate on the fly */
4841
0
            VISIT(c, expr, gen->iter);
4842
0
        }
4843
0
    }
4844
0
    if (iter_pos != ITERATOR_ON_STACK) {
4845
0
        ADDOP(c, LOC(gen->iter), GET_AITER);
4846
0
    }
4847
4848
0
    USE_LABEL(c, start);
4849
    /* Runtime will push a block here, so we need to account for that */
4850
0
    RETURN_IF_ERROR(
4851
0
        _PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_ASYNC_COMPREHENSION_GENERATOR,
4852
0
                              start, NO_LABEL, NULL));
4853
4854
0
    ADDOP_JUMP(c, loc, SETUP_FINALLY, except);
4855
0
    ADDOP(c, loc, GET_ANEXT);
4856
0
    USE_LABEL(c, send);
4857
0
    ADD_YIELD_FROM(c, loc, 1);
4858
0
    ADDOP(c, loc, POP_BLOCK);
4859
0
    VISIT(c, expr, gen->target);
4860
4861
0
    Py_ssize_t n = asdl_seq_LEN(gen->ifs);
4862
0
    for (Py_ssize_t i = 0; i < n; i++) {
4863
0
        expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
4864
0
        RETURN_IF_ERROR(codegen_jump_if(c, loc, e, if_cleanup, 0));
4865
0
    }
4866
4867
0
    depth++;
4868
0
    if (++gen_index < asdl_seq_LEN(generators)) {
4869
0
        RETURN_IF_ERROR(
4870
0
            codegen_comprehension_generator(c, loc,
4871
0
                                            generators, gen_index, depth,
4872
0
                                            elt, val, type, 0, avoid_creation));
4873
0
    }
4874
4875
0
    location elt_loc = LOC(elt);
4876
    /* only append after the last for generator */
4877
0
    if (gen_index >= asdl_seq_LEN(generators)) {
4878
        /* comprehension specific code */
4879
0
        RETURN_IF_ERROR(codegen_comprehension_generator_helper(c, elt_loc, depth,
4880
0
                                                               elt, val, type,
4881
0
                                                               avoid_creation));
4882
0
        if (type == COMP_DICTCOMP && val != NULL) {
4883
0
            elt_loc = LOCATION(elt->lineno,
4884
0
                               val->end_lineno,
4885
0
                               elt->col_offset,
4886
0
                               val->end_col_offset);
4887
0
        }
4888
0
    }
4889
4890
0
    USE_LABEL(c, if_cleanup);
4891
0
    ADDOP_JUMP(c, elt_loc, JUMP, start);
4892
4893
0
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_ASYNC_COMPREHENSION_GENERATOR, start);
4894
4895
0
    USE_LABEL(c, except);
4896
4897
0
    ADDOP_JUMP(c, loc, END_ASYNC_FOR, send);
4898
4899
0
    return SUCCESS;
4900
0
}
4901
4902
static int
4903
codegen_push_inlined_comprehension_locals(compiler *c, location loc,
4904
                                          PySTEntryObject *comp,
4905
                                          _PyCompile_InlinedComprehensionState *state)
4906
31
{
4907
    // iterate over names bound in the comprehension and ensure we isolate
4908
    // them from the outer scope as needed
4909
31
    PyObject *k, *v;
4910
31
    Py_ssize_t pos = 0;
4911
103
    while (PyDict_Next(comp->ste_symbols, &pos, &k, &v)) {
4912
72
        long symbol = PyLong_AsLong(v);
4913
72
        assert(symbol >= 0 || PyErr_Occurred());
4914
72
        RETURN_IF_ERROR(symbol);
4915
72
        long scope = SYMBOL_TO_SCOPE(symbol);
4916
4917
72
        if ((symbol & DEF_LOCAL) && !(symbol & DEF_NONLOCAL)) {
4918
            // local names bound in comprehension must be isolated from
4919
            // outer scope; push existing value (which may be NULL if
4920
            // not defined) on stack
4921
35
            if (state->pushed_locals == NULL) {
4922
31
                state->pushed_locals = PyList_New(0);
4923
31
                if (state->pushed_locals == NULL) {
4924
0
                    return ERROR;
4925
0
                }
4926
31
            }
4927
            // in the case of a cell, this will actually push the cell
4928
            // itself to the stack, then we'll create a new one for the
4929
            // comprehension and restore the original one after
4930
35
            ADDOP_NAME(c, loc, LOAD_FAST_AND_CLEAR, k, varnames);
4931
35
            if (scope == CELL) {
4932
0
                ADDOP_NAME(c, loc, MAKE_CELL, k, cellvars);
4933
0
            }
4934
35
            if (PyList_Append(state->pushed_locals, k) < 0) {
4935
0
                return ERROR;
4936
0
            }
4937
35
            if (METADATA(c)->u_fasthidden != NULL) {
4938
                /* For Module/Class scopes, assemble needs to set CO_FAST_HIDDEN on these names */
4939
1
                if (PySet_Add(METADATA(c)->u_fasthidden, k) < 0) {
4940
0
                    return ERROR;
4941
0
                }
4942
1
            }
4943
35
        }
4944
72
    }
4945
31
    if (state->pushed_locals) {
4946
        // Outermost iterable expression was already evaluated and is on the
4947
        // stack, we need to swap it back to TOS. This also rotates the order of
4948
        // `pushed_locals` on the stack, but this will be reversed when we swap
4949
        // out the comprehension result in pop_inlined_comprehension_state
4950
31
        ADDOP_I(c, loc, SWAP, PyList_GET_SIZE(state->pushed_locals) + 1);
4951
4952
        // Add our own cleanup handler to restore comprehension locals in case
4953
        // of exception, so they have the correct values inside an exception
4954
        // handler or finally block.
4955
31
        NEW_JUMP_TARGET_LABEL(c, cleanup);
4956
31
        state->cleanup = cleanup;
4957
4958
        // Count against CO_MAXBLOCKS: SETUP_FINALLY consumes an except-stack
4959
        // slot even though return/continue/break cannot appear here.
4960
31
        RETURN_IF_ERROR(_PyCompile_PushFBlock(
4961
31
            c, loc, COMPILE_FBLOCK_INLINED_COMPREHENSION,
4962
31
            cleanup, NO_LABEL, NULL));
4963
31
        ADDOP_JUMP(c, loc, SETUP_FINALLY, cleanup);
4964
31
    }
4965
31
    return SUCCESS;
4966
31
}
4967
4968
static int
4969
push_inlined_comprehension_state(compiler *c, location loc,
4970
                                 PySTEntryObject *comp,
4971
                                 _PyCompile_InlinedComprehensionState *state)
4972
31
{
4973
31
    RETURN_IF_ERROR(
4974
31
        _PyCompile_EnterInlinedComprehensionScope(c, comp, state));
4975
31
    if (codegen_push_inlined_comprehension_locals(c, loc, comp, state) < 0){
4976
0
        _PyCompile_ExitInlinedComprehensionScope(c, state);
4977
0
        return ERROR;
4978
0
    }
4979
31
    return SUCCESS;
4980
31
}
4981
4982
static int
4983
restore_inlined_comprehension_locals(compiler *c, location loc,
4984
                                     _PyCompile_InlinedComprehensionState *state)
4985
62
{
4986
62
    PyObject *k;
4987
    // pop names we pushed to stack earlier
4988
62
    Py_ssize_t npops = PyList_GET_SIZE(state->pushed_locals);
4989
    // Preserve the comprehension result (or exception) as TOS. This
4990
    // reverses the SWAP we did in push_inlined_comprehension_state
4991
    // to get the outermost iterable to TOS, so we can still just iterate
4992
    // pushed_locals in simple reverse order
4993
62
    ADDOP_I(c, loc, SWAP, npops + 1);
4994
132
    for (Py_ssize_t i = npops - 1; i >= 0; --i) {
4995
70
        k = PyList_GetItem(state->pushed_locals, i);
4996
70
        if (k == NULL) {
4997
0
            return ERROR;
4998
0
        }
4999
70
        ADDOP_NAME(c, loc, STORE_FAST_MAYBE_NULL, k, varnames);
5000
70
    }
5001
62
    return SUCCESS;
5002
62
}
5003
5004
static int
5005
codegen_pop_inlined_comprehension_locals(compiler *c, location loc,
5006
                                         _PyCompile_InlinedComprehensionState *state)
5007
31
{
5008
31
    if (state->pushed_locals) {
5009
31
        ADDOP(c, NO_LOCATION, POP_BLOCK);
5010
31
        _PyCompile_PopFBlock(c, COMPILE_FBLOCK_INLINED_COMPREHENSION,
5011
31
                             state->cleanup);
5012
5013
31
        NEW_JUMP_TARGET_LABEL(c, end);
5014
31
        ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, end);
5015
5016
        // cleanup from an exception inside the comprehension
5017
31
        USE_LABEL(c, state->cleanup);
5018
        // discard incomplete comprehension result (beneath exc on stack)
5019
31
        ADDOP_I(c, NO_LOCATION, SWAP, 2);
5020
31
        ADDOP(c, NO_LOCATION, POP_TOP);
5021
31
        RETURN_IF_ERROR(restore_inlined_comprehension_locals(c, loc, state));
5022
31
        ADDOP_I(c, NO_LOCATION, RERAISE, 0);
5023
5024
31
        USE_LABEL(c, end);
5025
31
        RETURN_IF_ERROR(restore_inlined_comprehension_locals(c, loc, state));
5026
31
        Py_CLEAR(state->pushed_locals);
5027
31
    }
5028
31
    return SUCCESS;
5029
31
}
5030
5031
static int
5032
pop_inlined_comprehension_state(compiler *c, location loc,
5033
                                _PyCompile_InlinedComprehensionState *state)
5034
31
{
5035
31
    int result = codegen_pop_inlined_comprehension_locals(c, loc, state);
5036
31
    RETURN_IF_ERROR(_PyCompile_ExitInlinedComprehensionScope(c, state));
5037
31
    return result;
5038
31
}
5039
5040
static int
5041
codegen_comprehension_init_container(compiler *c, location loc, int type,
5042
                                     int is_inlined, bool avoid_creation)
5043
31
{
5044
31
    int op;
5045
31
    switch (type) {
5046
25
    case COMP_LISTCOMP:
5047
25
        op = BUILD_LIST;
5048
25
        break;
5049
1
    case COMP_SETCOMP:
5050
1
        op = BUILD_SET;
5051
1
        break;
5052
5
    case COMP_DICTCOMP:
5053
5
        op = BUILD_MAP;
5054
5
        break;
5055
0
    default:
5056
0
        PyErr_Format(PyExc_SystemError,
5057
0
                     "unknown comprehension type %d", type);
5058
0
        return ERROR;
5059
31
    }
5060
5061
31
    if (!avoid_creation) {
5062
31
        ADDOP_I(c, loc, op, 0);
5063
31
        if (is_inlined) {
5064
31
            ADDOP_I(c, loc, SWAP, 2);
5065
31
        }
5066
31
    } else {
5067
0
        ADDOP_I(c, loc, COPY, 1);
5068
0
    }
5069
31
    return SUCCESS;
5070
31
}
5071
5072
static int
5073
codegen_comprehension(compiler *c, expr_ty e, int type,
5074
                      identifier name, asdl_comprehension_seq *generators, expr_ty elt,
5075
                      expr_ty val, bool avoid_creation)
5076
55
{
5077
55
    PyCodeObject *co = NULL;
5078
55
    _PyCompile_InlinedComprehensionState inline_state = {NULL, NO_LABEL, NULL};
5079
55
    comprehension_ty outermost;
5080
55
    PySTEntryObject *entry = _PySymtable_Lookup(SYMTABLE(c), (void *)e);
5081
55
    if (entry == NULL) {
5082
0
        goto error;
5083
0
    }
5084
55
    int is_inlined = (entry->ste_type == InlinedComprehensionBlock);
5085
55
    int is_async_comprehension = entry->ste_coroutine;
5086
5087
55
    location loc = LOC(e);
5088
5089
55
    outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
5090
55
    IterStackPosition iter_state;
5091
55
    if (is_inlined) {
5092
31
        VISIT(c, expr, outermost->iter);
5093
31
        if (push_inlined_comprehension_state(c, loc, entry, &inline_state) < 0) {
5094
0
            goto error;
5095
0
        }
5096
31
        iter_state = ITERABLE_ON_STACK;
5097
31
    }
5098
24
    else {
5099
        /* Receive outermost iter as an implicit argument */
5100
24
        _PyCompile_CodeUnitMetadata umd = {
5101
24
            .u_argcount = 1,
5102
24
        };
5103
24
        if (codegen_enter_scope(c, name, COMPILE_SCOPE_COMPREHENSION,
5104
24
                                (void *)e, e->lineno, NULL, &umd) < 0) {
5105
0
            goto error;
5106
0
        }
5107
24
        if (type == COMP_GENEXP) {
5108
            /* Insert GET_ITER before RETURN_GENERATOR.
5109
               https://docs.python.org/3/reference/expressions.html#generator-expressions */
5110
24
            if(_PyInstructionSequence_InsertInstruction(
5111
24
                    INSTR_SEQUENCE(c), 0,
5112
24
                    RESUME, RESUME_AT_GEN_EXPR_START, NO_LOCATION) < 0) {
5113
0
                goto error_in_scope;
5114
0
            }
5115
24
            if(_PyInstructionSequence_InsertInstruction(
5116
24
                    INSTR_SEQUENCE(c), 1,
5117
24
                    LOAD_FAST, 0, LOC(outermost->iter)) < 0) {
5118
0
                goto error_in_scope;
5119
0
            }
5120
24
            if(_PyInstructionSequence_InsertInstruction(
5121
24
                    INSTR_SEQUENCE(c), 2,
5122
24
                    outermost->is_async ? GET_AITER : GET_ITER,
5123
24
                    0, LOC(outermost->iter)) < 0) {
5124
0
                goto error_in_scope;
5125
0
            }
5126
24
            iter_state = ITERATOR_ON_STACK;
5127
24
        }
5128
0
        else {
5129
0
            iter_state = ITERABLE_IN_LOCAL;
5130
0
        }
5131
24
    }
5132
55
    Py_CLEAR(entry);
5133
5134
55
    if (type != COMP_GENEXP) {
5135
31
        if (codegen_comprehension_init_container(
5136
31
            c, loc, type, is_inlined, avoid_creation) < 0) {
5137
0
            goto error_in_scope;
5138
0
        }
5139
31
    }
5140
55
    if (codegen_comprehension_generator(c, loc, generators, 0, 0,
5141
55
                                        elt, val, type, iter_state, avoid_creation) < 0) {
5142
0
        goto error_in_scope;
5143
0
    }
5144
5145
55
    if (is_inlined) {
5146
31
        if (pop_inlined_comprehension_state(c, loc, &inline_state) < 0) {
5147
0
            goto error_in_scope;
5148
0
        }
5149
31
        return SUCCESS;
5150
31
    }
5151
5152
24
    if (type != COMP_GENEXP) {
5153
0
        ADDOP_IN_SCOPE(c, LOC(e), RETURN_VALUE);
5154
0
    }
5155
24
    if (type == COMP_GENEXP) {
5156
24
        if (codegen_wrap_in_stopiteration_handler(c) < 0) {
5157
0
            goto error_in_scope;
5158
0
        }
5159
24
    }
5160
5161
24
    co = _PyCompile_OptimizeAndAssemble(c, 1);
5162
24
    _PyCompile_ExitScope(c);
5163
24
    if (co == NULL) {
5164
0
        goto error;
5165
0
    }
5166
5167
24
    loc = LOC(e);
5168
24
    if (codegen_make_closure(c, loc, co, 0) < 0) {
5169
0
        goto error;
5170
0
    }
5171
24
    Py_CLEAR(co);
5172
5173
24
    VISIT(c, expr, outermost->iter);
5174
24
    ADDOP_I(c, loc, CALL, 0);
5175
5176
24
    if (is_async_comprehension && type != COMP_GENEXP) {
5177
0
        ADDOP_I(c, loc, GET_AWAITABLE, 0);
5178
0
        ADD_YIELD_FROM(c, loc, 1);
5179
0
    }
5180
5181
24
    assert(!avoid_creation);
5182
5183
24
    return SUCCESS;
5184
0
error_in_scope:
5185
0
    if (is_inlined) {
5186
0
        if (inline_state.saved_ste != NULL) {
5187
0
            _PyCompile_ExitInlinedComprehensionScope(c, &inline_state);
5188
0
        }
5189
0
    }
5190
0
    else {
5191
0
        _PyCompile_ExitScope(c);
5192
0
    }
5193
0
error:
5194
0
    Py_XDECREF(co);
5195
0
    Py_XDECREF(entry);
5196
0
    Py_XDECREF(inline_state.pushed_locals);
5197
0
    return ERROR;
5198
0
}
5199
5200
static int
5201
codegen_genexp(compiler *c, expr_ty e)
5202
24
{
5203
24
    assert(e->kind == GeneratorExp_kind);
5204
24
    _Py_DECLARE_STR(anon_genexpr, "<genexpr>");
5205
24
    return codegen_comprehension(c, e, COMP_GENEXP, &_Py_STR(anon_genexpr),
5206
24
                                 e->v.GeneratorExp.generators,
5207
24
                                 e->v.GeneratorExp.elt, NULL, false);
5208
24
}
5209
5210
static int
5211
codegen_listcomp(compiler *c, expr_ty e, bool avoid_creation)
5212
25
{
5213
25
    assert(e->kind == ListComp_kind);
5214
25
    _Py_DECLARE_STR(anon_listcomp, "<listcomp>");
5215
25
    return codegen_comprehension(c, e, COMP_LISTCOMP, &_Py_STR(anon_listcomp),
5216
25
                                 e->v.ListComp.generators,
5217
25
                                 e->v.ListComp.elt, NULL, avoid_creation);
5218
25
}
5219
5220
static int
5221
codegen_setcomp(compiler *c, expr_ty e)
5222
1
{
5223
1
    assert(e->kind == SetComp_kind);
5224
1
    _Py_DECLARE_STR(anon_setcomp, "<setcomp>");
5225
1
    return codegen_comprehension(c, e, COMP_SETCOMP, &_Py_STR(anon_setcomp),
5226
1
                                 e->v.SetComp.generators,
5227
1
                                 e->v.SetComp.elt, NULL, /*avoid_creation=*/false);
5228
1
}
5229
5230
5231
static int
5232
codegen_dictcomp(compiler *c, expr_ty e)
5233
5
{
5234
5
    assert(e->kind == DictComp_kind);
5235
5
    _Py_DECLARE_STR(anon_dictcomp, "<dictcomp>");
5236
5
    return codegen_comprehension(c, e, COMP_DICTCOMP, &_Py_STR(anon_dictcomp),
5237
5
                                 e->v.DictComp.generators,
5238
5
                                 e->v.DictComp.key, e->v.DictComp.value, /*avoid_creation=*/false);
5239
5
}
5240
5241
5242
static int
5243
codegen_visit_keyword(compiler *c, keyword_ty k)
5244
1.48k
{
5245
1.48k
    VISIT(c, expr, k->value);
5246
1.48k
    return SUCCESS;
5247
1.48k
}
5248
5249
5250
static int
5251
83
codegen_with_except_finish(compiler *c, jump_target_label cleanup) {
5252
83
    NEW_JUMP_TARGET_LABEL(c, suppress);
5253
83
    ADDOP(c, NO_LOCATION, TO_BOOL);
5254
83
    ADDOP_JUMP(c, NO_LOCATION, POP_JUMP_IF_TRUE, suppress);
5255
83
    ADDOP_I(c, NO_LOCATION, RERAISE, 2);
5256
5257
83
    USE_LABEL(c, suppress);
5258
83
    ADDOP(c, NO_LOCATION, POP_TOP); /* exc_value */
5259
83
    ADDOP(c, NO_LOCATION, POP_BLOCK);
5260
83
    ADDOP(c, NO_LOCATION, POP_EXCEPT);
5261
83
    ADDOP(c, NO_LOCATION, POP_TOP);
5262
83
    ADDOP(c, NO_LOCATION, POP_TOP);
5263
83
    ADDOP(c, NO_LOCATION, POP_TOP);
5264
83
    NEW_JUMP_TARGET_LABEL(c, exit);
5265
83
    ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, exit);
5266
5267
83
    USE_LABEL(c, cleanup);
5268
83
    POP_EXCEPT_AND_RERAISE(c, NO_LOCATION);
5269
5270
83
    USE_LABEL(c, exit);
5271
83
    return SUCCESS;
5272
83
}
5273
5274
/*
5275
   Implements the async with statement.
5276
5277
   The semantics outlined in that PEP are as follows:
5278
5279
   async with EXPR as VAR:
5280
       BLOCK
5281
5282
   It is implemented roughly as:
5283
5284
   context = EXPR
5285
   exit = context.__aexit__  # not calling it
5286
   value = await context.__aenter__()
5287
   try:
5288
       VAR = value  # if VAR present in the syntax
5289
       BLOCK
5290
   finally:
5291
       if an exception was raised:
5292
           exc = copy of (exception, instance, traceback)
5293
       else:
5294
           exc = (None, None, None)
5295
       if not (await exit(*exc)):
5296
           raise
5297
 */
5298
static int
5299
codegen_async_with_inner(compiler *c, stmt_ty s, int pos)
5300
0
{
5301
0
    location loc = LOC(s);
5302
0
    withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
5303
5304
0
    assert(s->kind == AsyncWith_kind);
5305
5306
0
    NEW_JUMP_TARGET_LABEL(c, block);
5307
0
    NEW_JUMP_TARGET_LABEL(c, final);
5308
0
    NEW_JUMP_TARGET_LABEL(c, exit);
5309
0
    NEW_JUMP_TARGET_LABEL(c, cleanup);
5310
5311
    /* Evaluate EXPR */
5312
0
    VISIT(c, expr, item->context_expr);
5313
0
    loc = LOC(item->context_expr);
5314
0
    ADDOP_I(c, loc, COPY, 1);
5315
0
    ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___AEXIT__);
5316
0
    ADDOP_I(c, loc, SWAP, 2);
5317
0
    ADDOP_I(c, loc, SWAP, 3);
5318
0
    ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___AENTER__);
5319
0
    ADDOP_I(c, loc, CALL, 0);
5320
0
    ADDOP_I(c, loc, GET_AWAITABLE, 1);
5321
0
    ADD_YIELD_FROM(c, loc, 1);
5322
5323
0
    ADDOP_JUMP(c, loc, SETUP_WITH, final);
5324
5325
    /* SETUP_WITH pushes a finally block. */
5326
0
    USE_LABEL(c, block);
5327
0
    RETURN_IF_ERROR(_PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_ASYNC_WITH, block, final, s));
5328
5329
0
    if (item->optional_vars) {
5330
0
        VISIT(c, expr, item->optional_vars);
5331
0
    }
5332
0
    else {
5333
        /* Discard result from context.__aenter__() */
5334
0
        ADDOP(c, loc, POP_TOP);
5335
0
    }
5336
5337
0
    pos++;
5338
0
    if (pos == asdl_seq_LEN(s->v.AsyncWith.items)) {
5339
        /* BLOCK code */
5340
0
        VISIT_SEQ(c, stmt, s->v.AsyncWith.body);
5341
0
    }
5342
0
    else {
5343
0
        RETURN_IF_ERROR(codegen_async_with_inner(c, s, pos));
5344
0
    }
5345
5346
0
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_ASYNC_WITH, block);
5347
5348
0
    ADDOP(c, loc, POP_BLOCK);
5349
    /* End of body; start the cleanup */
5350
5351
    /* For successful outcome:
5352
     * call __exit__(None, None, None)
5353
     */
5354
0
    RETURN_IF_ERROR(codegen_call_exit_with_nones(c, loc));
5355
0
    ADDOP_I(c, loc, GET_AWAITABLE, 2);
5356
0
    ADD_YIELD_FROM(c, loc, 1);
5357
5358
0
    ADDOP(c, loc, POP_TOP);
5359
5360
0
    ADDOP_JUMP(c, loc, JUMP, exit);
5361
5362
    /* For exceptional outcome: */
5363
0
    USE_LABEL(c, final);
5364
5365
0
    ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup);
5366
0
    ADDOP(c, loc, PUSH_EXC_INFO);
5367
0
    ADDOP(c, loc, WITH_EXCEPT_START);
5368
0
    ADDOP_I(c, loc, GET_AWAITABLE, 2);
5369
0
    ADD_YIELD_FROM(c, loc, 1);
5370
0
    RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup));
5371
5372
0
    USE_LABEL(c, exit);
5373
0
    return SUCCESS;
5374
0
}
5375
5376
static int
5377
codegen_async_with(compiler *c, stmt_ty s)
5378
0
{
5379
0
    return codegen_async_with_inner(c, s, 0);
5380
0
}
5381
5382
5383
/*
5384
   Implements the with statement from PEP 343.
5385
   with EXPR as VAR:
5386
       BLOCK
5387
   is implemented as:
5388
        <code for EXPR>
5389
        SETUP_WITH  E
5390
        <code to store to VAR> or POP_TOP
5391
        <code for BLOCK>
5392
        LOAD_CONST (None, None, None)
5393
        CALL_FUNCTION_EX 0
5394
        JUMP  EXIT
5395
    E:  WITH_EXCEPT_START (calls EXPR.__exit__)
5396
        POP_JUMP_IF_TRUE T:
5397
        RERAISE
5398
    T:  POP_TOP (remove exception from stack)
5399
        POP_EXCEPT
5400
        POP_TOP
5401
    EXIT:
5402
 */
5403
5404
static int
5405
codegen_with_inner(compiler *c, stmt_ty s, int pos)
5406
83
{
5407
83
    withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
5408
5409
83
    assert(s->kind == With_kind);
5410
5411
83
    NEW_JUMP_TARGET_LABEL(c, block);
5412
83
    NEW_JUMP_TARGET_LABEL(c, final);
5413
83
    NEW_JUMP_TARGET_LABEL(c, exit);
5414
83
    NEW_JUMP_TARGET_LABEL(c, cleanup);
5415
5416
    /* Evaluate EXPR */
5417
83
    VISIT(c, expr, item->context_expr);
5418
    /* Will push bound __exit__ */
5419
83
    location loc = LOC(item->context_expr);
5420
83
    ADDOP_I(c, loc, COPY, 1);
5421
83
    ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___EXIT__);
5422
83
    ADDOP_I(c, loc, SWAP, 2);
5423
83
    ADDOP_I(c, loc, SWAP, 3);
5424
83
    ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___ENTER__);
5425
83
    ADDOP_I(c, loc, CALL, 0);
5426
83
    ADDOP_JUMP(c, loc, SETUP_WITH, final);
5427
5428
    /* SETUP_WITH pushes a finally block. */
5429
83
    USE_LABEL(c, block);
5430
83
    RETURN_IF_ERROR(_PyCompile_PushFBlock(c, loc, COMPILE_FBLOCK_WITH, block, final, s));
5431
5432
83
    if (item->optional_vars) {
5433
27
        VISIT(c, expr, item->optional_vars);
5434
27
    }
5435
56
    else {
5436
    /* Discard result from context.__enter__() */
5437
56
        ADDOP(c, loc, POP_TOP);
5438
56
    }
5439
5440
83
    pos++;
5441
83
    if (pos == asdl_seq_LEN(s->v.With.items)) {
5442
        /* BLOCK code */
5443
79
        VISIT_SEQ(c, stmt, s->v.With.body);
5444
79
    }
5445
4
    else {
5446
4
        RETURN_IF_ERROR(codegen_with_inner(c, s, pos));
5447
4
    }
5448
5449
83
    ADDOP(c, NO_LOCATION, POP_BLOCK);
5450
83
    _PyCompile_PopFBlock(c, COMPILE_FBLOCK_WITH, block);
5451
5452
    /* End of body; start the cleanup. */
5453
5454
    /* For successful outcome:
5455
     * call __exit__(None, None, None)
5456
     */
5457
83
    RETURN_IF_ERROR(codegen_call_exit_with_nones(c, loc));
5458
83
    ADDOP(c, loc, POP_TOP);
5459
83
    ADDOP_JUMP(c, loc, JUMP, exit);
5460
5461
    /* For exceptional outcome: */
5462
83
    USE_LABEL(c, final);
5463
5464
83
    ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup);
5465
83
    ADDOP(c, loc, PUSH_EXC_INFO);
5466
83
    ADDOP(c, loc, WITH_EXCEPT_START);
5467
83
    RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup));
5468
5469
83
    USE_LABEL(c, exit);
5470
83
    return SUCCESS;
5471
83
}
5472
5473
static int
5474
codegen_with(compiler *c, stmt_ty s)
5475
79
{
5476
79
    return codegen_with_inner(c, s, 0);
5477
79
}
5478
5479
static int
5480
codegen_visit_expr_impl(compiler *c, expr_ty e, bool result_is_unused)
5481
69.2k
{
5482
69.2k
    if (Py_EnterRecursiveCall(" during compilation")) {
5483
0
        return ERROR;
5484
0
    }
5485
69.2k
    location loc = LOC(e);
5486
69.2k
    switch (e->kind) {
5487
4
    case NamedExpr_kind:
5488
4
        VISIT(c, expr, e->v.NamedExpr.value);
5489
4
        ADDOP_I(c, loc, COPY, 1);
5490
4
        VISIT(c, expr, e->v.NamedExpr.target);
5491
4
        break;
5492
130
    case BoolOp_kind:
5493
130
        return codegen_boolop(c, e);
5494
481
    case BinOp_kind:
5495
481
        VISIT(c, expr, e->v.BinOp.left);
5496
481
        VISIT(c, expr, e->v.BinOp.right);
5497
481
        ADDOP_BINARY(c, loc, e->v.BinOp.op);
5498
481
        break;
5499
1.72k
    case UnaryOp_kind:
5500
1.72k
        VISIT(c, expr, e->v.UnaryOp.operand);
5501
1.72k
        if (e->v.UnaryOp.op == UAdd) {
5502
0
            ADDOP_I(c, loc, CALL_INTRINSIC_1, INTRINSIC_UNARY_POSITIVE);
5503
0
        }
5504
1.72k
        else if (e->v.UnaryOp.op == Not) {
5505
6
            ADDOP(c, loc, TO_BOOL);
5506
6
            ADDOP(c, loc, UNARY_NOT);
5507
6
        }
5508
1.72k
        else {
5509
1.72k
            ADDOP(c, loc, unaryop(e->v.UnaryOp.op));
5510
1.72k
        }
5511
1.72k
        break;
5512
1.72k
    case Lambda_kind:
5513
198
        return codegen_lambda(c, e);
5514
71
    case IfExp_kind:
5515
71
        return codegen_ifexp(c, e);
5516
92
    case Dict_kind:
5517
92
        return codegen_dict(c, e);
5518
131
    case Set_kind:
5519
131
        return codegen_set(c, e);
5520
24
    case GeneratorExp_kind:
5521
24
        return codegen_genexp(c, e);
5522
25
    case ListComp_kind:
5523
25
        return codegen_listcomp(c, e, result_is_unused);
5524
1
    case SetComp_kind:
5525
1
        return codegen_setcomp(c, e);
5526
5
    case DictComp_kind:
5527
5
        return codegen_dictcomp(c, e);
5528
39
    case Yield_kind:
5529
39
        if (!_PyST_IsFunctionLike(SYMTABLE_ENTRY(c))) {
5530
0
            return _PyCompile_Error(c, loc, "'yield' outside function");
5531
0
        }
5532
39
        if (e->v.Yield.value) {
5533
34
            VISIT(c, expr, e->v.Yield.value);
5534
34
        }
5535
5
        else {
5536
5
            ADDOP_LOAD_CONST(c, loc, Py_None);
5537
5
        }
5538
39
        ADDOP_YIELD(c, loc);
5539
39
        break;
5540
39
    case YieldFrom_kind:
5541
9
        if (!_PyST_IsFunctionLike(SYMTABLE_ENTRY(c))) {
5542
0
            return _PyCompile_Error(c, loc, "'yield from' outside function");
5543
0
        }
5544
9
        if (SCOPE_TYPE(c) == COMPILE_SCOPE_ASYNC_FUNCTION) {
5545
0
            return _PyCompile_Error(c, loc, "'yield from' inside async function");
5546
0
        }
5547
9
        VISIT(c, expr, e->v.YieldFrom.value);
5548
9
        ADDOP_I(c, loc, GET_ITER, GET_ITER_YIELD_FROM);
5549
9
        ADDOP_LOAD_CONST(c, loc, Py_None);
5550
9
        ADD_YIELD_FROM(c, loc, 0);
5551
9
        break;
5552
9
    case Await_kind:
5553
0
        VISIT(c, expr, e->v.Await.value);
5554
0
        ADDOP_I(c, loc, GET_AWAITABLE, 0);
5555
0
        ADD_YIELD_FROM(c, loc, 1);
5556
0
        break;
5557
1.83k
    case Compare_kind:
5558
1.83k
        return codegen_compare(c, e);
5559
6.04k
    case Call_kind:
5560
6.04k
        return codegen_call(c, e);
5561
21.7k
    case Constant_kind:
5562
21.7k
        ADDOP_LOAD_CONST(c, loc, e->v.Constant.value);
5563
21.7k
        break;
5564
21.7k
    case JoinedStr_kind:
5565
407
        return codegen_joined_str(c, e);
5566
1
    case TemplateStr_kind:
5567
1
        return codegen_template_str(c, e);
5568
1.12k
    case FormattedValue_kind:
5569
1.12k
        return codegen_formatted_value(c, e);
5570
1
    case Interpolation_kind:
5571
1
        return codegen_interpolation(c, e);
5572
    /* The following exprs can be assignment targets. */
5573
7.40k
    case Attribute_kind:
5574
7.40k
        if (e->v.Attribute.ctx == Load) {
5575
6.74k
            int ret = can_optimize_super_call(c, e);
5576
6.74k
            RETURN_IF_ERROR(ret);
5577
6.74k
            if (ret) {
5578
1
                RETURN_IF_ERROR(load_args_for_super(c, e->v.Attribute.value));
5579
1
                int opcode = asdl_seq_LEN(e->v.Attribute.value->v.Call.args) ?
5580
1
                    LOAD_SUPER_ATTR : LOAD_ZERO_SUPER_ATTR;
5581
1
                ADDOP_NAME(c, loc, opcode, e->v.Attribute.attr, names);
5582
1
                loc = update_start_location_to_match_attr(c, loc, e);
5583
1
                ADDOP(c, loc, NOP);
5584
1
                return SUCCESS;
5585
1
            }
5586
6.74k
        }
5587
7.40k
        RETURN_IF_ERROR(_PyCompile_MaybeAddStaticAttributeToClass(c, e));
5588
7.40k
        loc = LOC(e);
5589
7.40k
        loc = update_start_location_to_match_attr(c, loc, e);
5590
7.40k
        switch (e->v.Attribute.ctx) {
5591
6.74k
        case Load:
5592
6.74k
            VISIT(c, expr, e->v.Attribute.value);
5593
6.74k
            ADDOP_NAME(c, loc, LOAD_ATTR, e->v.Attribute.attr, names);
5594
6.74k
            break;
5595
6.74k
        case Store:
5596
641
            VISIT(c, expr, e->v.Attribute.value);
5597
641
            ADDOP_NAME(c, loc, STORE_ATTR, e->v.Attribute.attr, names);
5598
641
            break;
5599
641
        case Del:
5600
16
            ADDOP(c, loc, PUSH_NULL);
5601
16
            VISIT(c, expr, e->v.Attribute.value);
5602
16
            ADDOP_NAME(c, loc, STORE_ATTR, e->v.Attribute.attr, names);
5603
16
            break;
5604
7.40k
        }
5605
7.40k
        break;
5606
7.40k
    case Subscript_kind:
5607
610
        return codegen_subscript(c, e);
5608
0
    case Starred_kind:
5609
0
        switch (e->v.Starred.ctx) {
5610
0
        case Store:
5611
            /* In all legitimate cases, the Starred node was already replaced
5612
             * by codegen_list/codegen_tuple. XXX: is that okay? */
5613
0
            return _PyCompile_Error(c, loc,
5614
0
                "starred assignment target must be in a list or tuple");
5615
0
        default:
5616
0
            return _PyCompile_Error(c, loc,
5617
0
                "can't use starred expression here");
5618
0
        }
5619
0
        break;
5620
41
    case Slice_kind:
5621
41
        RETURN_IF_ERROR(codegen_slice(c, e));
5622
41
        break;
5623
26.0k
    case Name_kind:
5624
26.0k
        return codegen_nameop(c, loc, e->v.Name.id, e->v.Name.ctx);
5625
    /* child nodes of List and Tuple will have expr_context set */
5626
114
    case List_kind:
5627
114
        return codegen_list(c, e);
5628
844
    case Tuple_kind:
5629
844
        return codegen_tuple(c, e);
5630
69.2k
    }
5631
31.4k
    return SUCCESS;
5632
69.2k
}
5633
5634
static int
5635
codegen_visit_expr(compiler *c, expr_ty e)
5636
67.1k
{
5637
67.1k
    return codegen_visit_expr_impl(c, e, false);
5638
67.1k
}
5639
5640
static int
5641
codegen_visit_unused_expr(compiler *c, expr_ty e)
5642
2.03k
{
5643
2.03k
    return codegen_visit_expr_impl(c, e, true);
5644
2.03k
}
5645
5646
static bool
5647
is_constant_slice(expr_ty s)
5648
651
{
5649
651
    return s->kind == Slice_kind &&
5650
136
        (s->v.Slice.lower == NULL ||
5651
70
         s->v.Slice.lower->kind == Constant_kind) &&
5652
105
        (s->v.Slice.upper == NULL ||
5653
63
         s->v.Slice.upper->kind == Constant_kind) &&
5654
82
        (s->v.Slice.step == NULL ||
5655
0
         s->v.Slice.step->kind == Constant_kind);
5656
651
}
5657
5658
static bool
5659
should_apply_two_element_slice_optimization(expr_ty s)
5660
610
{
5661
610
    return !is_constant_slice(s) &&
5662
569
           s->kind == Slice_kind &&
5663
54
           s->v.Slice.step == NULL;
5664
610
}
5665
5666
static int
5667
codegen_augassign(compiler *c, stmt_ty s)
5668
100
{
5669
100
    assert(s->kind == AugAssign_kind);
5670
100
    expr_ty e = s->v.AugAssign.target;
5671
5672
100
    location loc = LOC(e);
5673
5674
100
    switch (e->kind) {
5675
14
    case Attribute_kind:
5676
14
        VISIT(c, expr, e->v.Attribute.value);
5677
14
        ADDOP_I(c, loc, COPY, 1);
5678
14
        loc = update_start_location_to_match_attr(c, loc, e);
5679
14
        ADDOP_NAME(c, loc, LOAD_ATTR, e->v.Attribute.attr, names);
5680
14
        break;
5681
14
    case Subscript_kind:
5682
0
        VISIT(c, expr, e->v.Subscript.value);
5683
0
        if (should_apply_two_element_slice_optimization(e->v.Subscript.slice)) {
5684
0
            RETURN_IF_ERROR(codegen_slice_two_parts(c, e->v.Subscript.slice));
5685
0
            ADDOP_I(c, loc, COPY, 3);
5686
0
            ADDOP_I(c, loc, COPY, 3);
5687
0
            ADDOP_I(c, loc, COPY, 3);
5688
0
            ADDOP(c, loc, BINARY_SLICE);
5689
0
        }
5690
0
        else {
5691
0
            VISIT(c, expr, e->v.Subscript.slice);
5692
0
            ADDOP_I(c, loc, COPY, 2);
5693
0
            ADDOP_I(c, loc, COPY, 2);
5694
0
            ADDOP_I(c, loc, BINARY_OP, NB_SUBSCR);
5695
0
        }
5696
0
        break;
5697
86
    case Name_kind:
5698
86
        RETURN_IF_ERROR(codegen_nameop(c, loc, e->v.Name.id, Load));
5699
86
        break;
5700
86
    default:
5701
0
        PyErr_Format(PyExc_SystemError,
5702
0
            "invalid node type (%d) for augmented assignment",
5703
0
            e->kind);
5704
0
        return ERROR;
5705
100
    }
5706
5707
100
    loc = LOC(s);
5708
5709
100
    VISIT(c, expr, s->v.AugAssign.value);
5710
100
    ADDOP_INPLACE(c, loc, s->v.AugAssign.op);
5711
5712
100
    loc = LOC(e);
5713
5714
100
    switch (e->kind) {
5715
14
    case Attribute_kind:
5716
14
        loc = update_start_location_to_match_attr(c, loc, e);
5717
14
        ADDOP_I(c, loc, SWAP, 2);
5718
14
        ADDOP_NAME(c, loc, STORE_ATTR, e->v.Attribute.attr, names);
5719
14
        break;
5720
14
    case Subscript_kind:
5721
0
        if (should_apply_two_element_slice_optimization(e->v.Subscript.slice)) {
5722
0
            ADDOP_I(c, loc, SWAP, 4);
5723
0
            ADDOP_I(c, loc, SWAP, 3);
5724
0
            ADDOP_I(c, loc, SWAP, 2);
5725
0
            ADDOP(c, loc, STORE_SLICE);
5726
0
        }
5727
0
        else {
5728
0
            ADDOP_I(c, loc, SWAP, 3);
5729
0
            ADDOP_I(c, loc, SWAP, 2);
5730
0
            ADDOP(c, loc, STORE_SUBSCR);
5731
0
        }
5732
0
        break;
5733
86
    case Name_kind:
5734
86
        return codegen_nameop(c, loc, e->v.Name.id, Store);
5735
0
    default:
5736
0
        Py_UNREACHABLE();
5737
100
    }
5738
14
    return SUCCESS;
5739
100
}
5740
5741
static int
5742
codegen_check_ann_expr(compiler *c, expr_ty e)
5743
0
{
5744
0
    VISIT(c, expr, e);
5745
0
    ADDOP(c, LOC(e), POP_TOP);
5746
0
    return SUCCESS;
5747
0
}
5748
5749
static int
5750
codegen_check_ann_subscr(compiler *c, expr_ty e)
5751
0
{
5752
    /* We check that everything in a subscript is defined at runtime. */
5753
0
    switch (e->kind) {
5754
0
    case Slice_kind:
5755
0
        if (e->v.Slice.lower && codegen_check_ann_expr(c, e->v.Slice.lower) < 0) {
5756
0
            return ERROR;
5757
0
        }
5758
0
        if (e->v.Slice.upper && codegen_check_ann_expr(c, e->v.Slice.upper) < 0) {
5759
0
            return ERROR;
5760
0
        }
5761
0
        if (e->v.Slice.step && codegen_check_ann_expr(c, e->v.Slice.step) < 0) {
5762
0
            return ERROR;
5763
0
        }
5764
0
        return SUCCESS;
5765
0
    case Tuple_kind: {
5766
        /* extended slice */
5767
0
        asdl_expr_seq *elts = e->v.Tuple.elts;
5768
0
        Py_ssize_t i, n = asdl_seq_LEN(elts);
5769
0
        for (i = 0; i < n; i++) {
5770
0
            RETURN_IF_ERROR(codegen_check_ann_subscr(c, asdl_seq_GET(elts, i)));
5771
0
        }
5772
0
        return SUCCESS;
5773
0
    }
5774
0
    default:
5775
0
        return codegen_check_ann_expr(c, e);
5776
0
    }
5777
0
}
5778
5779
static int
5780
codegen_annassign(compiler *c, stmt_ty s)
5781
8
{
5782
8
    location loc = LOC(s);
5783
8
    expr_ty targ = s->v.AnnAssign.target;
5784
8
    bool future_annotations = FUTURE_FEATURES(c) & CO_FUTURE_ANNOTATIONS;
5785
8
    PyObject *mangled;
5786
5787
8
    assert(s->kind == AnnAssign_kind);
5788
5789
    /* We perform the actual assignment first. */
5790
8
    if (s->v.AnnAssign.value) {
5791
8
        VISIT(c, expr, s->v.AnnAssign.value);
5792
8
        VISIT(c, expr, targ);
5793
8
    }
5794
8
    switch (targ->kind) {
5795
8
    case Name_kind:
5796
        /* If we have a simple name in a module or class, store annotation. */
5797
8
        if (s->v.AnnAssign.simple &&
5798
8
            (SCOPE_TYPE(c) == COMPILE_SCOPE_MODULE ||
5799
8
             SCOPE_TYPE(c) == COMPILE_SCOPE_CLASS)) {
5800
8
            if (future_annotations) {
5801
0
                VISIT(c, annexpr, s->v.AnnAssign.annotation);
5802
0
                ADDOP_NAME(c, loc, LOAD_NAME, &_Py_ID(__annotations__), names);
5803
0
                mangled = _PyCompile_MaybeMangle(c, targ->v.Name.id);
5804
0
                ADDOP_LOAD_CONST_NEW(c, loc, mangled);
5805
0
                ADDOP(c, loc, STORE_SUBSCR);
5806
0
            }
5807
8
            else {
5808
8
                PyObject *conditional_annotation_index = NULL;
5809
8
                RETURN_IF_ERROR(_PyCompile_AddDeferredAnnotation(
5810
8
                    c, s, &conditional_annotation_index));
5811
8
                if (conditional_annotation_index != NULL) {
5812
0
                    if (SCOPE_TYPE(c) == COMPILE_SCOPE_CLASS) {
5813
0
                        ADDOP_NAME(c, loc, LOAD_DEREF, &_Py_ID(__conditional_annotations__), cellvars);
5814
0
                    }
5815
0
                    else {
5816
0
                        ADDOP_NAME(c, loc, LOAD_NAME, &_Py_ID(__conditional_annotations__), names);
5817
0
                    }
5818
0
                    ADDOP_LOAD_CONST_NEW(c, loc, conditional_annotation_index);
5819
                    // gh-154902: change SET_ADD to new INTRINSIC_ADD_CONDITIONAL_ANNOTATION intrinsic
5820
0
                    ADDOP_I(c, loc, CALL_INTRINSIC_2,
5821
0
                            INTRINSIC_ADD_CONDITIONAL_ANNOTATION);
5822
0
                    ADDOP(c, loc, POP_TOP);
5823
0
                }
5824
8
            }
5825
8
        }
5826
8
        break;
5827
8
    case Attribute_kind:
5828
0
        if (!s->v.AnnAssign.value &&
5829
0
            codegen_check_ann_expr(c, targ->v.Attribute.value) < 0) {
5830
0
            return ERROR;
5831
0
        }
5832
0
        break;
5833
0
    case Subscript_kind:
5834
0
        if (!s->v.AnnAssign.value &&
5835
0
            (codegen_check_ann_expr(c, targ->v.Subscript.value) < 0 ||
5836
0
             codegen_check_ann_subscr(c, targ->v.Subscript.slice) < 0)) {
5837
0
                return ERROR;
5838
0
        }
5839
0
        break;
5840
0
    default:
5841
0
        PyErr_Format(PyExc_SystemError,
5842
0
                     "invalid node type (%d) for annotated assignment",
5843
0
                     targ->kind);
5844
0
        return ERROR;
5845
8
    }
5846
8
    return SUCCESS;
5847
8
}
5848
5849
static int
5850
codegen_subscript(compiler *c, expr_ty e)
5851
610
{
5852
610
    location loc = LOC(e);
5853
610
    expr_context_ty ctx = e->v.Subscript.ctx;
5854
5855
610
    if (ctx == Load) {
5856
493
        RETURN_IF_ERROR(check_subscripter(c, e->v.Subscript.value));
5857
493
        RETURN_IF_ERROR(check_index(c, e->v.Subscript.value, e->v.Subscript.slice));
5858
493
    }
5859
5860
610
    VISIT(c, expr, e->v.Subscript.value);
5861
610
    if (should_apply_two_element_slice_optimization(e->v.Subscript.slice) &&
5862
54
        ctx != Del
5863
610
    ) {
5864
54
        RETURN_IF_ERROR(codegen_slice_two_parts(c, e->v.Subscript.slice));
5865
54
        if (ctx == Load) {
5866
54
            ADDOP(c, loc, BINARY_SLICE);
5867
54
        }
5868
0
        else {
5869
0
            assert(ctx == Store);
5870
0
            ADDOP(c, loc, STORE_SLICE);
5871
0
        }
5872
54
    }
5873
556
    else {
5874
556
        VISIT(c, expr, e->v.Subscript.slice);
5875
556
        switch (ctx) {
5876
439
            case Load:
5877
439
                ADDOP_I(c, loc, BINARY_OP, NB_SUBSCR);
5878
439
                break;
5879
439
            case Store:
5880
109
                ADDOP(c, loc, STORE_SUBSCR);
5881
109
                break;
5882
109
            case Del:
5883
8
                ADDOP(c, loc, DELETE_SUBSCR);
5884
8
                break;
5885
556
        }
5886
556
    }
5887
610
    return SUCCESS;
5888
610
}
5889
5890
static int
5891
codegen_slice_two_parts(compiler *c, expr_ty s)
5892
54
{
5893
54
    if (s->v.Slice.lower) {
5894
34
        VISIT(c, expr, s->v.Slice.lower);
5895
34
    }
5896
20
    else {
5897
20
        ADDOP_LOAD_CONST(c, LOC(s), Py_None);
5898
20
    }
5899
5900
54
    if (s->v.Slice.upper) {
5901
40
        VISIT(c, expr, s->v.Slice.upper);
5902
40
    }
5903
14
    else {
5904
14
        ADDOP_LOAD_CONST(c, LOC(s), Py_None);
5905
14
    }
5906
5907
54
    return 0;
5908
54
}
5909
5910
static int
5911
codegen_slice(compiler *c, expr_ty s)
5912
41
{
5913
41
    int n = 2;
5914
41
    assert(s->kind == Slice_kind);
5915
5916
41
    if (is_constant_slice(s)) {
5917
41
        PyObject *start = NULL;
5918
41
        if (s->v.Slice.lower) {
5919
18
            start = s->v.Slice.lower->v.Constant.value;
5920
18
        }
5921
41
        PyObject *stop = NULL;
5922
41
        if (s->v.Slice.upper) {
5923
20
            stop = s->v.Slice.upper->v.Constant.value;
5924
20
        }
5925
41
        PyObject *step = NULL;
5926
41
        if (s->v.Slice.step) {
5927
0
            step = s->v.Slice.step->v.Constant.value;
5928
0
        }
5929
41
        PyObject *slice = PySlice_New(start, stop, step);
5930
41
        if (slice == NULL) {
5931
0
            return ERROR;
5932
0
        }
5933
41
        ADDOP_LOAD_CONST_NEW(c, LOC(s), slice);
5934
41
        return SUCCESS;
5935
41
    }
5936
5937
0
    RETURN_IF_ERROR(codegen_slice_two_parts(c, s));
5938
5939
0
    if (s->v.Slice.step) {
5940
0
        n++;
5941
0
        VISIT(c, expr, s->v.Slice.step);
5942
0
    }
5943
5944
0
    ADDOP_I(c, LOC(s), BUILD_SLICE, n);
5945
0
    return SUCCESS;
5946
0
}
5947
5948
5949
// PEP 634: Structural Pattern Matching
5950
5951
// To keep things simple, all codegen_pattern_* routines follow the convention
5952
// of consuming TOS (the subject for the given pattern) and calling
5953
// jump_to_fail_pop on failure (no match).
5954
5955
// When calling into these routines, it's important that pc->on_top be kept
5956
// updated to reflect the current number of items that we are using on the top
5957
// of the stack: they will be popped on failure, and any name captures will be
5958
// stored *underneath* them on success. This lets us defer all names stores
5959
// until the *entire* pattern matches.
5960
5961
#define WILDCARD_CHECK(N) \
5962
0
    ((N)->kind == MatchAs_kind && !(N)->v.MatchAs.name)
5963
5964
#define WILDCARD_STAR_CHECK(N) \
5965
0
    ((N)->kind == MatchStar_kind && !(N)->v.MatchStar.name)
5966
5967
// Limit permitted subexpressions, even if the parser & AST validator let them through
5968
#define MATCH_VALUE_EXPR(N) \
5969
0
    ((N)->kind == Constant_kind || (N)->kind == Attribute_kind)
5970
5971
// Allocate or resize pc->fail_pop to allow for n items to be popped on failure.
5972
static int
5973
ensure_fail_pop(compiler *c, pattern_context *pc, Py_ssize_t n)
5974
0
{
5975
0
    Py_ssize_t size = n + 1;
5976
0
    if (size <= pc->fail_pop_size) {
5977
0
        return SUCCESS;
5978
0
    }
5979
0
    Py_ssize_t needed = sizeof(jump_target_label) * size;
5980
0
    jump_target_label *resized = PyMem_Realloc(pc->fail_pop, needed);
5981
0
    if (resized == NULL) {
5982
0
        PyErr_NoMemory();
5983
0
        return ERROR;
5984
0
    }
5985
0
    pc->fail_pop = resized;
5986
0
    while (pc->fail_pop_size < size) {
5987
0
        NEW_JUMP_TARGET_LABEL(c, new_block);
5988
0
        pc->fail_pop[pc->fail_pop_size++] = new_block;
5989
0
    }
5990
0
    return SUCCESS;
5991
0
}
5992
5993
// Use op to jump to the correct fail_pop block.
5994
static int
5995
jump_to_fail_pop(compiler *c, location loc,
5996
                 pattern_context *pc, int op)
5997
0
{
5998
    // Pop any items on the top of the stack, plus any objects we were going to
5999
    // capture on success:
6000
0
    Py_ssize_t pops = pc->on_top + PyList_GET_SIZE(pc->stores);
6001
0
    RETURN_IF_ERROR(ensure_fail_pop(c, pc, pops));
6002
0
    ADDOP_JUMP(c, loc, op, pc->fail_pop[pops]);
6003
0
    return SUCCESS;
6004
0
}
6005
6006
// Build all of the fail_pop blocks and reset fail_pop.
6007
static int
6008
emit_and_reset_fail_pop(compiler *c, location loc,
6009
                        pattern_context *pc)
6010
0
{
6011
0
    if (!pc->fail_pop_size) {
6012
0
        assert(pc->fail_pop == NULL);
6013
0
        return SUCCESS;
6014
0
    }
6015
0
    while (--pc->fail_pop_size) {
6016
0
        USE_LABEL(c, pc->fail_pop[pc->fail_pop_size]);
6017
0
        if (codegen_addop_noarg(INSTR_SEQUENCE(c), POP_TOP, loc) < 0) {
6018
0
            pc->fail_pop_size = 0;
6019
0
            PyMem_Free(pc->fail_pop);
6020
0
            pc->fail_pop = NULL;
6021
0
            return ERROR;
6022
0
        }
6023
0
    }
6024
0
    USE_LABEL(c, pc->fail_pop[0]);
6025
0
    PyMem_Free(pc->fail_pop);
6026
0
    pc->fail_pop = NULL;
6027
0
    return SUCCESS;
6028
0
}
6029
6030
static int
6031
codegen_error_duplicate_store(compiler *c, location loc, identifier n)
6032
0
{
6033
0
    return _PyCompile_Error(c, loc,
6034
0
        "multiple assignments to name %R in pattern", n);
6035
0
}
6036
6037
// Duplicate the effect of 3.10's ROT_* instructions using SWAPs.
6038
static int
6039
codegen_pattern_helper_rotate(compiler *c, location loc, Py_ssize_t count)
6040
0
{
6041
0
    while (1 < count) {
6042
0
        ADDOP_I(c, loc, SWAP, count--);
6043
0
    }
6044
0
    return SUCCESS;
6045
0
}
6046
6047
static int
6048
codegen_pattern_helper_store_name(compiler *c, location loc,
6049
                                  identifier n, pattern_context *pc)
6050
0
{
6051
0
    if (n == NULL) {
6052
0
        ADDOP(c, loc, POP_TOP);
6053
0
        return SUCCESS;
6054
0
    }
6055
    // Can't assign to the same name twice:
6056
0
    int duplicate = PySequence_Contains(pc->stores, n);
6057
0
    RETURN_IF_ERROR(duplicate);
6058
0
    if (duplicate) {
6059
0
        return codegen_error_duplicate_store(c, loc, n);
6060
0
    }
6061
    // Rotate this object underneath any items we need to preserve:
6062
0
    Py_ssize_t rotations = pc->on_top + PyList_GET_SIZE(pc->stores) + 1;
6063
0
    RETURN_IF_ERROR(codegen_pattern_helper_rotate(c, loc, rotations));
6064
0
    RETURN_IF_ERROR(PyList_Append(pc->stores, n));
6065
0
    return SUCCESS;
6066
0
}
6067
6068
6069
static int
6070
codegen_pattern_unpack_helper(compiler *c, location loc,
6071
                              asdl_pattern_seq *elts)
6072
0
{
6073
0
    Py_ssize_t n = asdl_seq_LEN(elts);
6074
0
    int seen_star = 0;
6075
0
    for (Py_ssize_t i = 0; i < n; i++) {
6076
0
        pattern_ty elt = asdl_seq_GET(elts, i);
6077
0
        if (elt->kind == MatchStar_kind && !seen_star) {
6078
0
            if ((i >= (1 << 8)) ||
6079
0
                (n-i-1 >= (INT_MAX >> 8))) {
6080
0
                return _PyCompile_Error(c, loc,
6081
0
                    "too many expressions in "
6082
0
                    "star-unpacking sequence pattern");
6083
0
            }
6084
0
            ADDOP_I(c, loc, UNPACK_EX, (i + ((n-i-1) << 8)));
6085
0
            seen_star = 1;
6086
0
        }
6087
0
        else if (elt->kind == MatchStar_kind) {
6088
0
            return _PyCompile_Error(c, loc,
6089
0
                "multiple starred expressions in sequence pattern");
6090
0
        }
6091
0
    }
6092
0
    if (!seen_star) {
6093
0
        ADDOP_I(c, loc, UNPACK_SEQUENCE, n);
6094
0
    }
6095
0
    return SUCCESS;
6096
0
}
6097
6098
static int
6099
pattern_helper_sequence_unpack(compiler *c, location loc,
6100
                               asdl_pattern_seq *patterns, Py_ssize_t star,
6101
                               pattern_context *pc)
6102
0
{
6103
0
    RETURN_IF_ERROR(codegen_pattern_unpack_helper(c, loc, patterns));
6104
0
    Py_ssize_t size = asdl_seq_LEN(patterns);
6105
    // We've now got a bunch of new subjects on the stack. They need to remain
6106
    // there after each subpattern match:
6107
0
    pc->on_top += size;
6108
0
    for (Py_ssize_t i = 0; i < size; i++) {
6109
        // One less item to keep track of each time we loop through:
6110
0
        pc->on_top--;
6111
0
        pattern_ty pattern = asdl_seq_GET(patterns, i);
6112
0
        RETURN_IF_ERROR(codegen_pattern_subpattern(c, pattern, pc));
6113
0
    }
6114
0
    return SUCCESS;
6115
0
}
6116
6117
// Like pattern_helper_sequence_unpack, but uses BINARY_OP/NB_SUBSCR instead of
6118
// UNPACK_SEQUENCE / UNPACK_EX. This is more efficient for patterns with a
6119
// starred wildcard like [first, *_] / [first, *_, last] / [*_, last] / etc.
6120
static int
6121
pattern_helper_sequence_subscr(compiler *c, location loc,
6122
                               asdl_pattern_seq *patterns, Py_ssize_t star,
6123
                               pattern_context *pc)
6124
0
{
6125
    // We need to keep the subject around for extracting elements:
6126
0
    pc->on_top++;
6127
0
    Py_ssize_t size = asdl_seq_LEN(patterns);
6128
0
    for (Py_ssize_t i = 0; i < size; i++) {
6129
0
        pattern_ty pattern = asdl_seq_GET(patterns, i);
6130
0
        if (WILDCARD_CHECK(pattern)) {
6131
0
            continue;
6132
0
        }
6133
0
        if (i == star) {
6134
0
            assert(WILDCARD_STAR_CHECK(pattern));
6135
0
            continue;
6136
0
        }
6137
0
        ADDOP_I(c, loc, COPY, 1);
6138
0
        if (i < star) {
6139
0
            ADDOP_LOAD_CONST_NEW(c, loc, PyLong_FromSsize_t(i));
6140
0
        }
6141
0
        else {
6142
            // The subject may not support negative indexing! Compute a
6143
            // nonnegative index:
6144
0
            ADDOP(c, loc, GET_LEN);
6145
0
            ADDOP_LOAD_CONST_NEW(c, loc, PyLong_FromSsize_t(size - i));
6146
0
            ADDOP_BINARY(c, loc, Sub);
6147
0
        }
6148
0
        ADDOP_I(c, loc, BINARY_OP, NB_SUBSCR);
6149
0
        RETURN_IF_ERROR(codegen_pattern_subpattern(c, pattern, pc));
6150
0
    }
6151
    // Pop the subject, we're done with it:
6152
0
    pc->on_top--;
6153
0
    ADDOP(c, loc, POP_TOP);
6154
0
    return SUCCESS;
6155
0
}
6156
6157
// Like codegen_pattern, but turn off checks for irrefutability.
6158
static int
6159
codegen_pattern_subpattern(compiler *c,
6160
                            pattern_ty p, pattern_context *pc)
6161
0
{
6162
0
    int allow_irrefutable = pc->allow_irrefutable;
6163
0
    pc->allow_irrefutable = 1;
6164
0
    RETURN_IF_ERROR(codegen_pattern(c, p, pc));
6165
0
    pc->allow_irrefutable = allow_irrefutable;
6166
0
    return SUCCESS;
6167
0
}
6168
6169
static int
6170
codegen_pattern_as(compiler *c, pattern_ty p, pattern_context *pc)
6171
0
{
6172
0
    assert(p->kind == MatchAs_kind);
6173
0
    if (p->v.MatchAs.pattern == NULL) {
6174
        // An irrefutable match:
6175
0
        if (!pc->allow_irrefutable) {
6176
0
            if (p->v.MatchAs.name) {
6177
0
                const char *e = "name capture %R makes remaining patterns unreachable";
6178
0
                return _PyCompile_Error(c, LOC(p), e, p->v.MatchAs.name);
6179
0
            }
6180
0
            const char *e = "wildcard makes remaining patterns unreachable";
6181
0
            return _PyCompile_Error(c, LOC(p), e);
6182
0
        }
6183
0
        return codegen_pattern_helper_store_name(c, LOC(p), p->v.MatchAs.name, pc);
6184
0
    }
6185
    // Need to make a copy for (possibly) storing later:
6186
0
    pc->on_top++;
6187
0
    ADDOP_I(c, LOC(p), COPY, 1);
6188
0
    RETURN_IF_ERROR(codegen_pattern(c, p->v.MatchAs.pattern, pc));
6189
    // Success! Store it:
6190
0
    pc->on_top--;
6191
0
    RETURN_IF_ERROR(codegen_pattern_helper_store_name(c, LOC(p), p->v.MatchAs.name, pc));
6192
0
    return SUCCESS;
6193
0
}
6194
6195
static int
6196
codegen_pattern_star(compiler *c, pattern_ty p, pattern_context *pc)
6197
0
{
6198
0
    assert(p->kind == MatchStar_kind);
6199
0
    RETURN_IF_ERROR(
6200
0
        codegen_pattern_helper_store_name(c, LOC(p), p->v.MatchStar.name, pc));
6201
0
    return SUCCESS;
6202
0
}
6203
6204
static int
6205
validate_kwd_attrs(compiler *c, asdl_identifier_seq *attrs, asdl_pattern_seq* patterns)
6206
0
{
6207
    // Any errors will point to the pattern rather than the arg name as the
6208
    // parser is only supplying identifiers rather than Name or keyword nodes
6209
0
    Py_ssize_t nattrs = asdl_seq_LEN(attrs);
6210
0
    for (Py_ssize_t i = 0; i < nattrs; i++) {
6211
0
        identifier attr = ((identifier)asdl_seq_GET(attrs, i));
6212
0
        for (Py_ssize_t j = i + 1; j < nattrs; j++) {
6213
0
            identifier other = ((identifier)asdl_seq_GET(attrs, j));
6214
0
            if (!PyUnicode_Compare(attr, other)) {
6215
0
                location loc = LOC((pattern_ty) asdl_seq_GET(patterns, j));
6216
0
                return _PyCompile_Error(c, loc, "attribute name repeated "
6217
0
                                                "in class pattern: %U", attr);
6218
0
            }
6219
0
        }
6220
0
    }
6221
0
    return SUCCESS;
6222
0
}
6223
6224
static int
6225
codegen_pattern_class(compiler *c, pattern_ty p, pattern_context *pc)
6226
0
{
6227
0
    assert(p->kind == MatchClass_kind);
6228
0
    asdl_pattern_seq *patterns = p->v.MatchClass.patterns;
6229
0
    asdl_identifier_seq *kwd_attrs = p->v.MatchClass.kwd_attrs;
6230
0
    asdl_pattern_seq *kwd_patterns = p->v.MatchClass.kwd_patterns;
6231
0
    Py_ssize_t nargs = asdl_seq_LEN(patterns);
6232
0
    Py_ssize_t nattrs = asdl_seq_LEN(kwd_attrs);
6233
0
    Py_ssize_t nkwd_patterns = asdl_seq_LEN(kwd_patterns);
6234
0
    if (nattrs != nkwd_patterns) {
6235
        // AST validator shouldn't let this happen, but if it does,
6236
        // just fail, don't crash out of the interpreter
6237
0
        const char * e = "kwd_attrs (%d) / kwd_patterns (%d) length mismatch in class pattern";
6238
0
        return _PyCompile_Error(c, LOC(p), e, nattrs, nkwd_patterns);
6239
0
    }
6240
0
    if (INT_MAX < nargs || INT_MAX < nargs + nattrs - 1) {
6241
0
        const char *e = "too many sub-patterns in class pattern %R";
6242
0
        return _PyCompile_Error(c, LOC(p), e, p->v.MatchClass.cls);
6243
0
    }
6244
0
    if (nattrs) {
6245
0
        RETURN_IF_ERROR(validate_kwd_attrs(c, kwd_attrs, kwd_patterns));
6246
0
    }
6247
0
    if (nargs + nattrs == 0) {
6248
        // Fast path if there are no sub-patterns
6249
0
        VISIT(c, expr, p->v.MatchClass.cls);
6250
0
        ADDOP_I(c, LOC(p), CALL_INTRINSIC_2, INTRINSIC_MATCH_CLASS_ISINSTANCE);
6251
0
        RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6252
0
        return SUCCESS;
6253
0
    }
6254
0
    VISIT(c, expr, p->v.MatchClass.cls);
6255
0
    PyObject *attr_names = PyTuple_New(nattrs);
6256
0
    if (attr_names == NULL) {
6257
0
        return ERROR;
6258
0
    }
6259
0
    Py_ssize_t i;
6260
0
    for (i = 0; i < nattrs; i++) {
6261
0
        PyObject *name = asdl_seq_GET(kwd_attrs, i);
6262
0
        PyTuple_SET_ITEM(attr_names, i, Py_NewRef(name));
6263
0
    }
6264
0
    ADDOP_LOAD_CONST_NEW(c, LOC(p), attr_names);
6265
0
    ADDOP_I(c, LOC(p), MATCH_CLASS, nargs);
6266
0
    ADDOP_I(c, LOC(p), COPY, 1);
6267
0
    ADDOP_LOAD_CONST(c, LOC(p), Py_None);
6268
0
    ADDOP_I(c, LOC(p), IS_OP, 1);
6269
    // TOS is now a tuple of (nargs + nattrs) attributes (or None):
6270
0
    pc->on_top++;
6271
0
    RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6272
0
    ADDOP_I(c, LOC(p), UNPACK_SEQUENCE, nargs + nattrs);
6273
0
    pc->on_top += nargs + nattrs - 1;
6274
0
    for (i = 0; i < nargs + nattrs; i++) {
6275
0
        pc->on_top--;
6276
0
        pattern_ty pattern;
6277
0
        if (i < nargs) {
6278
            // Positional:
6279
0
            pattern = asdl_seq_GET(patterns, i);
6280
0
        }
6281
0
        else {
6282
            // Keyword:
6283
0
            pattern = asdl_seq_GET(kwd_patterns, i - nargs);
6284
0
        }
6285
0
        if (WILDCARD_CHECK(pattern)) {
6286
0
            ADDOP(c, LOC(p), POP_TOP);
6287
0
            continue;
6288
0
        }
6289
0
        RETURN_IF_ERROR(codegen_pattern_subpattern(c, pattern, pc));
6290
0
    }
6291
    // Success! Pop the tuple of attributes:
6292
0
    return SUCCESS;
6293
0
}
6294
6295
static int
6296
codegen_pattern_mapping_key(compiler *c, PyObject *seen, pattern_ty p, Py_ssize_t i)
6297
0
{
6298
0
    asdl_expr_seq *keys = p->v.MatchMapping.keys;
6299
0
    asdl_pattern_seq *patterns = p->v.MatchMapping.patterns;
6300
0
    expr_ty key = asdl_seq_GET(keys, i);
6301
0
    if (key == NULL) {
6302
0
        const char *e = "can't use NULL keys in MatchMapping "
6303
0
                        "(set 'rest' parameter instead)";
6304
0
        location loc = LOC((pattern_ty) asdl_seq_GET(patterns, i));
6305
0
        return _PyCompile_Error(c, loc, e);
6306
0
    }
6307
6308
0
    if (key->kind == Constant_kind) {
6309
0
        int in_seen = PySet_Contains(seen, key->v.Constant.value);
6310
0
        RETURN_IF_ERROR(in_seen);
6311
0
        if (in_seen) {
6312
0
            const char *e = "mapping pattern checks duplicate key (%R)";
6313
0
            return _PyCompile_Error(c, LOC(p), e, key->v.Constant.value);
6314
0
        }
6315
0
        RETURN_IF_ERROR(PySet_Add(seen, key->v.Constant.value));
6316
0
    }
6317
0
    else if (key->kind != Attribute_kind) {
6318
0
        const char *e = "mapping pattern keys may only match literals and attribute lookups";
6319
0
        return _PyCompile_Error(c, LOC(p), e);
6320
0
    }
6321
0
    VISIT(c, expr, key);
6322
0
    return SUCCESS;
6323
0
}
6324
6325
static int
6326
codegen_pattern_mapping(compiler *c, pattern_ty p,
6327
                        pattern_context *pc)
6328
0
{
6329
0
    assert(p->kind == MatchMapping_kind);
6330
0
    asdl_expr_seq *keys = p->v.MatchMapping.keys;
6331
0
    asdl_pattern_seq *patterns = p->v.MatchMapping.patterns;
6332
0
    Py_ssize_t size = asdl_seq_LEN(keys);
6333
0
    Py_ssize_t npatterns = asdl_seq_LEN(patterns);
6334
0
    if (size != npatterns) {
6335
        // AST validator shouldn't let this happen, but if it does,
6336
        // just fail, don't crash out of the interpreter
6337
0
        const char * e = "keys (%d) / patterns (%d) length mismatch in mapping pattern";
6338
0
        return _PyCompile_Error(c, LOC(p), e, size, npatterns);
6339
0
    }
6340
    // We have a double-star target if "rest" is set
6341
0
    PyObject *star_target = p->v.MatchMapping.rest;
6342
    // We need to keep the subject on top during the mapping and length checks:
6343
0
    pc->on_top++;
6344
0
    ADDOP(c, LOC(p), MATCH_MAPPING);
6345
0
    RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6346
0
    if (!size && !star_target) {
6347
        // If the pattern is just "{}", we're done! Pop the subject:
6348
0
        pc->on_top--;
6349
0
        ADDOP(c, LOC(p), POP_TOP);
6350
0
        return SUCCESS;
6351
0
    }
6352
0
    if (size) {
6353
        // If the pattern has any keys in it, perform a length check:
6354
0
        ADDOP(c, LOC(p), GET_LEN);
6355
0
        ADDOP_LOAD_CONST_NEW(c, LOC(p), PyLong_FromSsize_t(size));
6356
0
        ADDOP_COMPARE(c, LOC(p), GtE);
6357
0
        RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6358
0
    }
6359
0
    if (INT_MAX < size - 1) {
6360
0
        return _PyCompile_Error(c, LOC(p), "too many sub-patterns in mapping pattern");
6361
0
    }
6362
    // Collect all of the keys into a tuple for MATCH_KEYS and
6363
    // **rest. They can either be dotted names or literals:
6364
6365
    // Maintaining a set of Constant_kind kind keys allows us to raise a
6366
    // SyntaxError in the case of duplicates.
6367
0
    PyObject *seen = PySet_New(NULL);
6368
0
    if (seen == NULL) {
6369
0
        return ERROR;
6370
0
    }
6371
0
    for (Py_ssize_t i = 0; i < size; i++) {
6372
0
        if (codegen_pattern_mapping_key(c, seen, p, i) < 0) {
6373
0
            Py_DECREF(seen);
6374
0
            return ERROR;
6375
0
        }
6376
0
    }
6377
0
    Py_DECREF(seen);
6378
6379
    // all keys have been checked; there are no duplicates
6380
6381
0
    ADDOP_I(c, LOC(p), BUILD_TUPLE, size);
6382
0
    ADDOP(c, LOC(p), MATCH_KEYS);
6383
    // There's now a tuple of keys and a tuple of values on top of the subject:
6384
0
    pc->on_top += 2;
6385
0
    ADDOP_I(c, LOC(p), COPY, 1);
6386
0
    ADDOP_LOAD_CONST(c, LOC(p), Py_None);
6387
0
    ADDOP_I(c, LOC(p), IS_OP, 1);
6388
0
    RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6389
    // So far so good. Use that tuple of values on the stack to match
6390
    // sub-patterns against:
6391
0
    ADDOP_I(c, LOC(p), UNPACK_SEQUENCE, size);
6392
0
    pc->on_top += size - 1;
6393
0
    for (Py_ssize_t i = 0; i < size; i++) {
6394
0
        pc->on_top--;
6395
0
        pattern_ty pattern = asdl_seq_GET(patterns, i);
6396
0
        RETURN_IF_ERROR(codegen_pattern_subpattern(c, pattern, pc));
6397
0
    }
6398
    // If we get this far, it's a match! Whatever happens next should consume
6399
    // the tuple of keys and the subject:
6400
0
    pc->on_top -= 2;
6401
0
    if (star_target) {
6402
        // If we have a starred name, bind a dict of remaining items to it (this may
6403
        // seem a bit inefficient, but keys is rarely big enough to actually impact
6404
        // runtime):
6405
        // rest = dict(TOS1)
6406
        // for key in TOS:
6407
        //     del rest[key]
6408
0
        ADDOP_I(c, LOC(p), BUILD_MAP, 0);           // [subject, keys, empty]
6409
0
        ADDOP_I(c, LOC(p), SWAP, 3);                // [empty, keys, subject]
6410
0
        ADDOP_I(c, LOC(p), DICT_UPDATE, 2);         // [copy, keys]
6411
0
        ADDOP_I(c, LOC(p), UNPACK_SEQUENCE, size);  // [copy, keys...]
6412
0
        while (size) {
6413
0
            ADDOP_I(c, LOC(p), COPY, 1 + size--);   // [copy, keys..., copy]
6414
0
            ADDOP_I(c, LOC(p), SWAP, 2);            // [copy, keys..., copy, key]
6415
0
            ADDOP(c, LOC(p), DELETE_SUBSCR);        // [copy, keys...]
6416
0
        }
6417
0
        RETURN_IF_ERROR(codegen_pattern_helper_store_name(c, LOC(p), star_target, pc));
6418
0
    }
6419
0
    else {
6420
0
        ADDOP(c, LOC(p), POP_TOP);  // Tuple of keys.
6421
0
        ADDOP(c, LOC(p), POP_TOP);  // Subject.
6422
0
    }
6423
0
    return SUCCESS;
6424
0
}
6425
6426
static int
6427
codegen_pattern_or(compiler *c, pattern_ty p, pattern_context *pc)
6428
0
{
6429
0
    assert(p->kind == MatchOr_kind);
6430
0
    NEW_JUMP_TARGET_LABEL(c, end);
6431
0
    Py_ssize_t size = asdl_seq_LEN(p->v.MatchOr.patterns);
6432
0
    assert(size > 1);
6433
0
    PyObject *mismatched_names = NULL;
6434
0
    Py_ssize_t mismatch_index = 0;
6435
    // We're going to be messing with pc. Keep the original info handy:
6436
0
    pattern_context old_pc = *pc;
6437
0
    Py_INCREF(pc->stores);
6438
    // control is the list of names bound by the first alternative. It is used
6439
    // for checking different name bindings in alternatives, and for correcting
6440
    // the order in which extracted elements are placed on the stack.
6441
0
    PyObject *control = NULL;
6442
    // NOTE: We can't use returning macros anymore! goto error on error.
6443
0
    for (Py_ssize_t i = 0; i < size; i++) {
6444
0
        pattern_ty alt = asdl_seq_GET(p->v.MatchOr.patterns, i);
6445
0
        PyObject *pc_stores = PyList_New(0);
6446
0
        if (pc_stores == NULL) {
6447
0
            goto error;
6448
0
        }
6449
0
        Py_SETREF(pc->stores, pc_stores);
6450
        // An irrefutable sub-pattern must be last, if it is allowed at all:
6451
0
        pc->allow_irrefutable = (i == size - 1) && old_pc.allow_irrefutable;
6452
0
        pc->fail_pop = NULL;
6453
0
        pc->fail_pop_size = 0;
6454
0
        pc->on_top = 0;
6455
0
        if (codegen_addop_i(INSTR_SEQUENCE(c), COPY, 1, LOC(alt)) < 0 ||
6456
0
            codegen_pattern(c, alt, pc) < 0) {
6457
0
            goto error;
6458
0
        }
6459
        // Success!
6460
0
        Py_ssize_t nstores = PyList_GET_SIZE(pc->stores);
6461
0
        if (!i) {
6462
            // This is the first alternative, so save its stores as a "control"
6463
            // for the others (they can't bind a different set of names, and
6464
            // might need to be reordered):
6465
0
            assert(control == NULL);
6466
0
            control = Py_NewRef(pc->stores);
6467
0
        }
6468
0
        else if (nstores != PyList_GET_SIZE(control)) {
6469
0
            mismatch_index = i;
6470
0
            mismatched_names = Py_NewRef(pc->stores);
6471
0
            goto diff;
6472
0
        }
6473
0
        else if (nstores) {
6474
            // There were captures. Check to see if we differ from control:
6475
0
            Py_ssize_t icontrol = nstores;
6476
0
            while (icontrol--) {
6477
0
                PyObject *name = PyList_GET_ITEM(control, icontrol);
6478
0
                Py_ssize_t istores = PySequence_Index(pc->stores, name);
6479
0
                if (istores < 0) {
6480
0
                    PyErr_Clear();
6481
0
                    mismatch_index = i;
6482
0
                    mismatched_names = Py_NewRef(pc->stores);
6483
0
                    goto diff;
6484
0
                }
6485
0
                if (icontrol != istores) {
6486
                    // Reorder the names on the stack to match the order of the
6487
                    // names in control. There's probably a better way of doing
6488
                    // this; the current solution is potentially very
6489
                    // inefficient when each alternative subpattern binds lots
6490
                    // of names in different orders. It's fine for reasonable
6491
                    // cases, though, and the peephole optimizer will ensure
6492
                    // that the final code is as efficient as possible.
6493
0
                    assert(istores < icontrol);
6494
0
                    Py_ssize_t rotations = istores + 1;
6495
                    // Perform the same rotation on pc->stores:
6496
0
                    PyObject *rotated = PyList_GetSlice(pc->stores, 0,
6497
0
                                                        rotations);
6498
0
                    if (rotated == NULL ||
6499
0
                        PyList_SetSlice(pc->stores, 0, rotations, NULL) ||
6500
0
                        PyList_SetSlice(pc->stores, icontrol - istores,
6501
0
                                        icontrol - istores, rotated))
6502
0
                    {
6503
0
                        Py_XDECREF(rotated);
6504
0
                        goto error;
6505
0
                    }
6506
0
                    Py_DECREF(rotated);
6507
                    // That just did:
6508
                    // rotated = pc_stores[:rotations]
6509
                    // del pc_stores[:rotations]
6510
                    // pc_stores[icontrol-istores:icontrol-istores] = rotated
6511
                    // Do the same thing to the stack, using several
6512
                    // rotations:
6513
0
                    while (rotations--) {
6514
0
                        if (codegen_pattern_helper_rotate(c, LOC(alt), icontrol + 1) < 0) {
6515
0
                            goto error;
6516
0
                        }
6517
0
                    }
6518
0
                }
6519
0
            }
6520
0
        }
6521
0
        assert(control);
6522
0
        if (codegen_addop_j(INSTR_SEQUENCE(c), LOC(alt), JUMP, end) < 0 ||
6523
0
            emit_and_reset_fail_pop(c, LOC(alt), pc) < 0)
6524
0
        {
6525
0
            goto error;
6526
0
        }
6527
0
    }
6528
0
    Py_DECREF(pc->stores);
6529
0
    *pc = old_pc;
6530
0
    Py_INCREF(pc->stores);
6531
    // Need to NULL this for the PyMem_Free call in the error block.
6532
0
    old_pc.fail_pop = NULL;
6533
    // No match. Pop the remaining copy of the subject and fail:
6534
0
    if (codegen_addop_noarg(INSTR_SEQUENCE(c), POP_TOP, LOC(p)) < 0 ||
6535
0
        jump_to_fail_pop(c, LOC(p), pc, JUMP) < 0) {
6536
0
        goto error;
6537
0
    }
6538
6539
0
    USE_LABEL(c, end);
6540
0
    Py_ssize_t nstores = PyList_GET_SIZE(control);
6541
    // There's a bunch of stuff on the stack between where the new stores
6542
    // are and where they need to be:
6543
    // - The other stores.
6544
    // - A copy of the subject.
6545
    // - Anything else that may be on top of the stack.
6546
    // - Any previous stores we've already stashed away on the stack.
6547
0
    Py_ssize_t nrots = nstores + 1 + pc->on_top + PyList_GET_SIZE(pc->stores);
6548
0
    for (Py_ssize_t i = 0; i < nstores; i++) {
6549
        // Rotate this capture to its proper place on the stack:
6550
0
        if (codegen_pattern_helper_rotate(c, LOC(p), nrots) < 0) {
6551
0
            goto error;
6552
0
        }
6553
        // Update the list of previous stores with this new name, checking for
6554
        // duplicates:
6555
0
        PyObject *name = PyList_GET_ITEM(control, i);
6556
0
        int dupe = PySequence_Contains(pc->stores, name);
6557
0
        if (dupe < 0) {
6558
0
            goto error;
6559
0
        }
6560
0
        if (dupe) {
6561
0
            codegen_error_duplicate_store(c, LOC(p), name);
6562
0
            goto error;
6563
0
        }
6564
0
        if (PyList_Append(pc->stores, name)) {
6565
0
            goto error;
6566
0
        }
6567
0
    }
6568
0
    Py_DECREF(old_pc.stores);
6569
0
    Py_DECREF(control);
6570
    // NOTE: Returning macros are safe again.
6571
    // Pop the copy of the subject:
6572
0
    ADDOP(c, LOC(p), POP_TOP);
6573
0
    return SUCCESS;
6574
0
diff:;
6575
0
    int control_is_empty = PyList_GET_SIZE(control) == 0;
6576
0
    int pattern_is_empty = (
6577
0
        mismatched_names == NULL
6578
0
        || PyList_GET_SIZE(mismatched_names) == 0
6579
0
    );
6580
6581
0
    _PyCompile_Error(
6582
0
        c, LOC(p),
6583
0
        "alternative patterns bind different names "
6584
0
        "(pattern 1 binds %S, pattern %zd binds %S)",
6585
0
        control_is_empty ? &_Py_ID(nothing) : control,
6586
0
        mismatch_index + 1,
6587
0
        pattern_is_empty ? &_Py_ID(nothing) : mismatched_names
6588
0
    );
6589
0
error:
6590
0
    PyMem_Free(old_pc.fail_pop);
6591
0
    Py_XDECREF(mismatched_names);
6592
0
    Py_DECREF(old_pc.stores);
6593
0
    Py_XDECREF(control);
6594
0
    return ERROR;
6595
0
}
6596
6597
6598
static int
6599
codegen_pattern_sequence(compiler *c, pattern_ty p,
6600
                         pattern_context *pc)
6601
0
{
6602
0
    assert(p->kind == MatchSequence_kind);
6603
0
    asdl_pattern_seq *patterns = p->v.MatchSequence.patterns;
6604
0
    Py_ssize_t size = asdl_seq_LEN(patterns);
6605
0
    Py_ssize_t star = -1;
6606
0
    int only_wildcard = 1;
6607
0
    int star_wildcard = 0;
6608
    // Find a starred name, if it exists. There may be at most one:
6609
0
    for (Py_ssize_t i = 0; i < size; i++) {
6610
0
        pattern_ty pattern = asdl_seq_GET(patterns, i);
6611
0
        if (pattern->kind == MatchStar_kind) {
6612
0
            if (star >= 0) {
6613
0
                const char *e = "multiple starred names in sequence pattern";
6614
0
                return _PyCompile_Error(c, LOC(p), e);
6615
0
            }
6616
0
            star_wildcard = WILDCARD_STAR_CHECK(pattern);
6617
0
            only_wildcard &= star_wildcard;
6618
0
            star = i;
6619
0
            continue;
6620
0
        }
6621
0
        only_wildcard &= WILDCARD_CHECK(pattern);
6622
0
    }
6623
    // We need to keep the subject on top during the sequence and length checks:
6624
0
    pc->on_top++;
6625
0
    ADDOP(c, LOC(p), MATCH_SEQUENCE);
6626
0
    RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6627
0
    if (star < 0) {
6628
        // No star: len(subject) == size
6629
0
        ADDOP(c, LOC(p), GET_LEN);
6630
0
        ADDOP_LOAD_CONST_NEW(c, LOC(p), PyLong_FromSsize_t(size));
6631
0
        ADDOP_COMPARE(c, LOC(p), Eq);
6632
0
        RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6633
0
    }
6634
0
    else if (size > 1) {
6635
        // Star: len(subject) >= size - 1
6636
0
        ADDOP(c, LOC(p), GET_LEN);
6637
0
        ADDOP_LOAD_CONST_NEW(c, LOC(p), PyLong_FromSsize_t(size - 1));
6638
0
        ADDOP_COMPARE(c, LOC(p), GtE);
6639
0
        RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6640
0
    }
6641
    // Whatever comes next should consume the subject:
6642
0
    pc->on_top--;
6643
0
    if (only_wildcard) {
6644
        // Patterns like: [] / [_] / [_, _] / [*_] / [_, *_] / [_, _, *_] / etc.
6645
0
        ADDOP(c, LOC(p), POP_TOP);
6646
0
    }
6647
0
    else if (star_wildcard) {
6648
0
        RETURN_IF_ERROR(pattern_helper_sequence_subscr(c, LOC(p), patterns, star, pc));
6649
0
    }
6650
0
    else {
6651
0
        RETURN_IF_ERROR(pattern_helper_sequence_unpack(c, LOC(p), patterns, star, pc));
6652
0
    }
6653
0
    return SUCCESS;
6654
0
}
6655
6656
static int
6657
codegen_pattern_value(compiler *c, pattern_ty p, pattern_context *pc)
6658
0
{
6659
0
    assert(p->kind == MatchValue_kind);
6660
0
    expr_ty value = p->v.MatchValue.value;
6661
0
    if (!MATCH_VALUE_EXPR(value)) {
6662
0
        const char *e = "patterns may only match literals and attribute lookups";
6663
0
        return _PyCompile_Error(c, LOC(p), e);
6664
0
    }
6665
0
    VISIT(c, expr, value);
6666
0
    ADDOP_COMPARE(c, LOC(p), Eq);
6667
0
    ADDOP(c, LOC(p), TO_BOOL);
6668
0
    RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6669
0
    return SUCCESS;
6670
0
}
6671
6672
static int
6673
codegen_pattern_singleton(compiler *c, pattern_ty p, pattern_context *pc)
6674
0
{
6675
0
    assert(p->kind == MatchSingleton_kind);
6676
0
    ADDOP_LOAD_CONST(c, LOC(p), p->v.MatchSingleton.value);
6677
0
    ADDOP_COMPARE(c, LOC(p), Is);
6678
0
    RETURN_IF_ERROR(jump_to_fail_pop(c, LOC(p), pc, POP_JUMP_IF_FALSE));
6679
0
    return SUCCESS;
6680
0
}
6681
6682
static int
6683
codegen_pattern(compiler *c, pattern_ty p, pattern_context *pc)
6684
0
{
6685
0
    switch (p->kind) {
6686
0
        case MatchValue_kind:
6687
0
            return codegen_pattern_value(c, p, pc);
6688
0
        case MatchSingleton_kind:
6689
0
            return codegen_pattern_singleton(c, p, pc);
6690
0
        case MatchSequence_kind:
6691
0
            return codegen_pattern_sequence(c, p, pc);
6692
0
        case MatchMapping_kind:
6693
0
            return codegen_pattern_mapping(c, p, pc);
6694
0
        case MatchClass_kind:
6695
0
            return codegen_pattern_class(c, p, pc);
6696
0
        case MatchStar_kind:
6697
0
            return codegen_pattern_star(c, p, pc);
6698
0
        case MatchAs_kind:
6699
0
            return codegen_pattern_as(c, p, pc);
6700
0
        case MatchOr_kind:
6701
0
            return codegen_pattern_or(c, p, pc);
6702
0
    }
6703
    // AST validator shouldn't let this happen, but if it does,
6704
    // just fail, don't crash out of the interpreter
6705
0
    const char *e = "invalid match pattern node in AST (kind=%d)";
6706
0
    return _PyCompile_Error(c, LOC(p), e, p->kind);
6707
0
}
6708
6709
static int
6710
codegen_match_inner(compiler *c, stmt_ty s, pattern_context *pc)
6711
0
{
6712
0
    VISIT(c, expr, s->v.Match.subject);
6713
0
    NEW_JUMP_TARGET_LABEL(c, end);
6714
0
    Py_ssize_t cases = asdl_seq_LEN(s->v.Match.cases);
6715
0
    assert(cases > 0);
6716
0
    match_case_ty m = asdl_seq_GET(s->v.Match.cases, cases - 1);
6717
0
    int has_default = WILDCARD_CHECK(m->pattern) && 1 < cases;
6718
0
    for (Py_ssize_t i = 0; i < cases - has_default; i++) {
6719
0
        m = asdl_seq_GET(s->v.Match.cases, i);
6720
        // Only copy the subject if we're *not* on the last case:
6721
0
        if (i != cases - has_default - 1) {
6722
0
            ADDOP_I(c, LOC(m->pattern), COPY, 1);
6723
0
        }
6724
0
        pc->stores = PyList_New(0);
6725
0
        if (pc->stores == NULL) {
6726
0
            return ERROR;
6727
0
        }
6728
        // Irrefutable cases must be either guarded, last, or both:
6729
0
        pc->allow_irrefutable = m->guard != NULL || i == cases - 1;
6730
0
        pc->fail_pop = NULL;
6731
0
        pc->fail_pop_size = 0;
6732
0
        pc->on_top = 0;
6733
        // NOTE: Can't use returning macros here (they'll leak pc->stores)!
6734
0
        if (codegen_pattern(c, m->pattern, pc) < 0) {
6735
0
            Py_DECREF(pc->stores);
6736
0
            return ERROR;
6737
0
        }
6738
0
        assert(!pc->on_top);
6739
        // It's a match! Store all of the captured names (they're on the stack).
6740
0
        Py_ssize_t nstores = PyList_GET_SIZE(pc->stores);
6741
0
        for (Py_ssize_t n = 0; n < nstores; n++) {
6742
0
            PyObject *name = PyList_GET_ITEM(pc->stores, n);
6743
0
            if (codegen_nameop(c, LOC(m->pattern), name, Store) < 0) {
6744
0
                Py_DECREF(pc->stores);
6745
0
                return ERROR;
6746
0
            }
6747
0
        }
6748
0
        Py_DECREF(pc->stores);
6749
        // NOTE: Returning macros are safe again.
6750
0
        if (m->guard) {
6751
0
            RETURN_IF_ERROR(ensure_fail_pop(c, pc, 0));
6752
0
            RETURN_IF_ERROR(codegen_jump_if(c, LOC(m->pattern), m->guard, pc->fail_pop[0], 0));
6753
0
        }
6754
        // Success! Pop the subject off, we're done with it:
6755
0
        if (i != cases - has_default - 1) {
6756
            /* Use the next location to give better locations for branch events */
6757
0
            ADDOP(c, NEXT_LOCATION, POP_TOP);
6758
0
        }
6759
0
        VISIT_SEQ(c, stmt, m->body);
6760
0
        ADDOP_JUMP(c, NO_LOCATION, JUMP, end);
6761
        // If the pattern fails to match, we want the line number of the
6762
        // cleanup to be associated with the failed pattern, not the last line
6763
        // of the body
6764
0
        RETURN_IF_ERROR(emit_and_reset_fail_pop(c, LOC(m->pattern), pc));
6765
0
    }
6766
0
    if (has_default) {
6767
        // A trailing "case _" is common, and lets us save a bit of redundant
6768
        // pushing and popping in the loop above:
6769
0
        m = asdl_seq_GET(s->v.Match.cases, cases - 1);
6770
0
        if (cases == 1) {
6771
            // No matches. Done with the subject:
6772
0
            ADDOP(c, LOC(m->pattern), POP_TOP);
6773
0
        }
6774
0
        else {
6775
            // Show line coverage for default case (it doesn't create bytecode)
6776
0
            ADDOP(c, LOC(m->pattern), NOP);
6777
0
        }
6778
0
        if (m->guard) {
6779
0
            RETURN_IF_ERROR(codegen_jump_if(c, LOC(m->pattern), m->guard, end, 0));
6780
0
        }
6781
0
        VISIT_SEQ(c, stmt, m->body);
6782
0
    }
6783
0
    USE_LABEL(c, end);
6784
0
    return SUCCESS;
6785
0
}
6786
6787
static int
6788
codegen_match(compiler *c, stmt_ty s)
6789
0
{
6790
0
    pattern_context pc;
6791
0
    pc.fail_pop = NULL;
6792
0
    int result = codegen_match_inner(c, s, &pc);
6793
0
    PyMem_Free(pc.fail_pop);
6794
0
    return result;
6795
0
}
6796
6797
#undef WILDCARD_CHECK
6798
#undef WILDCARD_STAR_CHECK
6799
6800
6801
int
6802
_PyCodegen_AddReturnAtEnd(compiler *c, int addNone)
6803
3.84k
{
6804
    /* Make sure every instruction stream that falls off the end returns None.
6805
     * This also ensures that no jump target offsets are out of bounds.
6806
     */
6807
3.84k
    if (addNone) {
6808
3.67k
        ADDOP_LOAD_CONST(c, NO_LOCATION, Py_None);
6809
3.67k
    }
6810
3.84k
    ADDOP(c, NO_LOCATION, RETURN_VALUE);
6811
3.84k
    return SUCCESS;
6812
3.84k
}