blob: 7dc04923af88112fa69d040f9a001ef43217f64d [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
Victor Stinnera81fca62021-03-24 00:51:50 +01004 * The primary entry point is _PyAST_Compile(), which returns a
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Mark Shannon6e8128f2020-07-30 10:03:00 +010012 * 5. Optimize the byte code (peephole optimizations).
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Victor Stinner526fdeb2021-03-17 23:50:50 +010025#include "pycore_ast.h" // _PyAST_GetDocString()
Victor Stinnera81fca62021-03-24 00:51:50 +010026#include "pycore_compile.h" // _PyFuture_FromAST()
Victor Stinnerba7a99d2021-01-30 01:46:44 +010027#include "pycore_pymem.h" // _PyMem_IsPtrFreed()
Victor Stinnerc9bc2902020-10-27 02:24:34 +010028#include "pycore_long.h" // _PyLong_GetZero()
Victor Stinner28ad12f2021-03-19 12:41:49 +010029#include "pycore_symtable.h" // PySTEntryObject
Guido van Rossum3f5da241990-12-20 15:06:42 +000030
Mark Shannon582aaf12020-08-04 17:30:11 +010031#define NEED_OPCODE_JUMP_TABLES
Victor Stinner526fdeb2021-03-17 23:50:50 +010032#include "opcode.h" // EXTENDED_ARG
33#include "wordcode_helpers.h" // instrsize()
34
Guido van Rossumb05a5c71997-05-07 17:46:13 +000035
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000036#define DEFAULT_BLOCK_SIZE 16
37#define DEFAULT_BLOCKS 8
38#define DEFAULT_CODE_SIZE 128
39#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000040
Nick Coghlan650f0d02007-04-15 12:05:43 +000041#define COMP_GENEXP 0
42#define COMP_LISTCOMP 1
43#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000044#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000045
Mark Shannon11e0b292021-04-15 14:28:56 +010046/* A soft limit for stack use, to avoid excessive
47 * memory use for large constants, etc.
48 *
49 * The value 30 is plucked out of thin air.
50 * Code that could use more stack than this is
51 * rare, so the exact value is unimportant.
52 */
53#define STACK_USE_GUIDELINE 30
54
55/* If we exceed this limit, it should
56 * be considered a compiler bug.
57 * Currently it should be impossible
58 * to exceed STACK_USE_GUIDELINE * 100,
59 * as 100 is the maximum parse depth.
60 * For performance reasons we will
61 * want to reduce this to a
62 * few hundred in the future.
63 *
64 * NOTE: Whatever MAX_ALLOWED_STACK_USE is
65 * set to, it should never restrict what Python
66 * we can write, just how we compile it.
67 */
68#define MAX_ALLOWED_STACK_USE (STACK_USE_GUIDELINE * 100)
69
Pablo Galindo90235812020-03-15 04:29:22 +000070#define IS_TOP_LEVEL_AWAIT(c) ( \
71 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
72 && (c->u->u_ste->ste_type == ModuleBlock))
73
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000074struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 unsigned char i_opcode;
76 int i_oparg;
77 struct basicblock_ *i_target; /* target block (if jump instruction) */
78 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000079};
80
Mark Shannon582aaf12020-08-04 17:30:11 +010081#define LOG_BITS_PER_INT 5
82#define MASK_LOW_LOG_BITS 31
83
84static inline int
85is_bit_set_in_table(uint32_t *table, int bitindex) {
86 /* Is the relevant bit set in the relevant word? */
87 /* 256 bits fit into 8 32-bits words.
88 * Word is indexed by (bitindex>>ln(size of int in bits)).
89 * Bit within word is the low bits of bitindex.
90 */
91 uint32_t word = table[bitindex >> LOG_BITS_PER_INT];
92 return (word >> (bitindex & MASK_LOW_LOG_BITS)) & 1;
93}
94
95static inline int
96is_relative_jump(struct instr *i)
97{
98 return is_bit_set_in_table(_PyOpcode_RelativeJump, i->i_opcode);
99}
100
101static inline int
102is_jump(struct instr *i)
103{
104 return is_bit_set_in_table(_PyOpcode_Jump, i->i_opcode);
105}
106
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000108 /* Each basicblock in a compilation unit is linked via b_list in the
109 reverse order that the block are allocated. b_list points to the next
110 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 struct basicblock_ *b_list;
112 /* number of instructions used */
113 int b_iused;
114 /* length of instruction array (b_instr) */
115 int b_ialloc;
116 /* pointer to an array of instructions, initially NULL */
117 struct instr *b_instr;
118 /* If b_next is non-NULL, it is a pointer to the next
119 block reached by normal control flow. */
120 struct basicblock_ *b_next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 /* b_return is true if a RETURN_VALUE opcode is inserted. */
122 unsigned b_return : 1;
Mark Shannon3bd60352021-01-13 12:05:43 +0000123 /* Number of predecssors that a block has. */
124 int b_predecessors;
Mark Shannoncc75ab72020-11-12 19:49:33 +0000125 /* Basic block has no fall through (it ends with a return, raise or jump) */
126 unsigned b_nofallthrough : 1;
127 /* Basic block exits scope (it ends with a return or raise) */
128 unsigned b_exit : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 /* depth of stack upon entry of block, computed by stackdepth() */
130 int b_startdepth;
131 /* instruction offset for block, computed by assemble_jump_offsets() */
132 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000133} basicblock;
134
135/* fblockinfo tracks the current frame block.
136
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000137A frame block is used to handle loops, try/except, and try/finally.
138It's called a frame block to distinguish it from a basic block in the
139compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140*/
141
Mark Shannon02d126a2020-09-25 14:04:19 +0100142enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
tomKPZ7a7ba3d2021-04-07 07:43:45 -0700143 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER,
144 ASYNC_COMPREHENSION_GENERATOR };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
146struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 enum fblocktype fb_type;
148 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200149 /* (optional) type-specific exit or cleanup block */
150 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +0000151 /* (optional) additional information required for unwinding */
152 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000153};
154
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100155enum {
156 COMPILER_SCOPE_MODULE,
157 COMPILER_SCOPE_CLASS,
158 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400159 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400160 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100161 COMPILER_SCOPE_COMPREHENSION,
162};
163
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000164/* The following items change on entry and exit of code blocks.
165 They must be saved and restored when returning to a block.
166*/
167struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400171 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100172 int u_scope_type;
173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 /* The following fields are dicts that map objects to
175 the index of them in co_XXX. The index is used as
176 the argument for opcodes that refer to those collections.
177 */
178 PyObject *u_consts; /* all constants */
179 PyObject *u_names; /* all names */
180 PyObject *u_varnames; /* local variables */
181 PyObject *u_cellvars; /* cell variables */
182 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185
Victor Stinnerf8e32212013-11-19 23:56:34 +0100186 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100187 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100188 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 /* Pointer to the most recently allocated block. By following b_list
190 members, you can reach all early allocated blocks. */
191 basicblock *u_blocks;
192 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 int u_nfblocks;
195 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 int u_firstlineno; /* the first lineno of the block */
198 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000199 int u_col_offset; /* the offset of the current stmt */
Pablo Galindoa77aac42021-04-23 14:27:05 +0100200 int u_end_lineno; /* the end line of the current stmt */
201 int u_end_col_offset; /* the end offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202};
203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000206The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000208managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000209
210Note that we don't track recursion levels during compilation - the
211task of detecting and rejecting excessive levels of nesting is
212handled by the symbol analysis pass.
213
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214*/
215
216struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200217 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 struct symtable *c_st;
219 PyFutureFeatures *c_future; /* pointer to module's __future__ */
220 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221
Georg Brandl8334fd92010-12-04 10:26:46 +0000222 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 int c_interactive; /* true if in interactive mode */
224 int c_nestlevel;
INADA Naokic2e16072018-11-26 21:23:22 +0900225 PyObject *c_const_cache; /* Python dict holding all constants,
226 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 struct compiler_unit *u; /* compiler state for current block */
228 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
229 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230};
231
Brandt Bucher145bf262021-02-26 14:51:55 -0800232typedef struct {
Brandt Bucher0ad1e032021-05-02 13:02:10 -0700233 // A list of strings corresponding to name captures. It is used to track:
234 // - Repeated name assignments in the same pattern.
235 // - Different name assignments in alternatives.
236 // - The order of name assignments in alternatives.
Brandt Bucher145bf262021-02-26 14:51:55 -0800237 PyObject *stores;
Brandt Bucher0ad1e032021-05-02 13:02:10 -0700238 // If 0, any name captures against our subject will raise.
Brandt Bucher145bf262021-02-26 14:51:55 -0800239 int allow_irrefutable;
Brandt Bucher0ad1e032021-05-02 13:02:10 -0700240 // An array of blocks to jump to on failure. Jumping to fail_pop[i] will pop
241 // i items off of the stack. The end result looks like this (with each block
242 // falling through to the next):
243 // fail_pop[4]: POP_TOP
244 // fail_pop[3]: POP_TOP
245 // fail_pop[2]: POP_TOP
246 // fail_pop[1]: POP_TOP
247 // fail_pop[0]: NOP
248 basicblock **fail_pop;
249 // The current length of fail_pop.
250 Py_ssize_t fail_pop_size;
251 // The number of items on top of the stack that need to *stay* on top of the
252 // stack. Variable captures go beneath these. All of them will be popped on
253 // failure.
254 Py_ssize_t on_top;
Brandt Bucher145bf262021-02-26 14:51:55 -0800255} pattern_context;
256
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100257static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000258static void compiler_free(struct compiler *);
259static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500260static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100262static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100263static int compiler_addop_j(struct compiler *, int, basicblock *);
Mark Shannon127dde52021-01-04 18:06:55 +0000264static int compiler_addop_j_noline(struct compiler *, int, basicblock *);
Brandt Bucher145bf262021-02-26 14:51:55 -0800265static int compiler_error(struct compiler *, const char *, ...);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200266static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
268
269static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
270static int compiler_visit_stmt(struct compiler *, stmt_ty);
271static int compiler_visit_keyword(struct compiler *, keyword_ty);
272static int compiler_visit_expr(struct compiler *, expr_ty);
273static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700274static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200275static int compiler_subscript(struct compiler *, expr_ty);
276static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277
Andy Lester76d58772020-03-10 21:18:12 -0500278static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100279static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Mark Shannon8473cf82020-12-15 11:07:50 +0000280
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000281
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500282static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400283static int compiler_async_with(struct compiler *, stmt_ty, int);
284static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100285static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100286 asdl_expr_seq *args,
287 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500288static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400289static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000290
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700291static int compiler_sync_comprehension_generator(
292 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100293 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200294 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700295 expr_ty elt, expr_ty val, int type);
296
297static int compiler_async_comprehension_generator(
298 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100299 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200300 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700301 expr_ty elt, expr_ty val, int type);
302
Nick Coghlan1e7b8582021-04-29 15:58:44 +1000303static int compiler_pattern(struct compiler *, pattern_ty, pattern_context *);
Brandt Bucher145bf262021-02-26 14:51:55 -0800304static int compiler_match(struct compiler *, stmt_ty);
Nick Coghlan1e7b8582021-04-29 15:58:44 +1000305static int compiler_pattern_subpattern(struct compiler *, pattern_ty,
Brandt Bucher145bf262021-02-26 14:51:55 -0800306 pattern_context *);
307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000309static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000310
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400311#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000312
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000313PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000314_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 /* Name mangling: __private becomes _classname__private.
317 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200318 PyObject *result;
319 size_t nlen, plen, ipriv;
320 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200322 PyUnicode_READ_CHAR(ident, 0) != '_' ||
323 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 Py_INCREF(ident);
325 return ident;
326 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200327 nlen = PyUnicode_GET_LENGTH(ident);
328 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 The only time a name with a dot can occur is when
332 we are compiling an import statement that has a
333 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 TODO(jhylton): Decide whether we want to support
336 mangling of the module name, e.g. __M.X.
337 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200338 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
339 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
340 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 Py_INCREF(ident);
342 return ident; /* Don't mangle __whatever__ */
343 }
344 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200345 ipriv = 0;
346 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
347 ipriv++;
348 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 Py_INCREF(ident);
350 return ident; /* Don't mangle if class is just underscores */
351 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200352 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000353
Antoine Pitrou55bff892013-04-06 21:21:04 +0200354 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
355 PyErr_SetString(PyExc_OverflowError,
356 "private identifier too large to be mangled");
357 return NULL;
358 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200360 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
361 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
362 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
363
364 result = PyUnicode_New(1 + nlen + plen, maxchar);
365 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200367 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
368 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200369 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
370 Py_DECREF(result);
371 return NULL;
372 }
373 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
374 Py_DECREF(result);
375 return NULL;
376 }
Victor Stinner8f825062012-04-27 13:55:39 +0200377 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200378 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000379}
380
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000381static int
382compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000385
INADA Naokic2e16072018-11-26 21:23:22 +0900386 c->c_const_cache = PyDict_New();
387 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900389 }
390
391 c->c_stack = PyList_New(0);
392 if (!c->c_stack) {
393 Py_CLEAR(c->c_const_cache);
394 return 0;
395 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398}
399
400PyCodeObject *
Victor Stinnera81fca62021-03-24 00:51:50 +0100401_PyAST_Compile(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
402 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 struct compiler c;
405 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200406 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (!__doc__) {
410 __doc__ = PyUnicode_InternFromString("__doc__");
411 if (!__doc__)
412 return NULL;
413 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000414 if (!__annotations__) {
415 __annotations__ = PyUnicode_InternFromString("__annotations__");
416 if (!__annotations__)
417 return NULL;
418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (!compiler_init(&c))
420 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200421 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 c.c_filename = filename;
423 c.c_arena = arena;
Victor Stinnera81fca62021-03-24 00:51:50 +0100424 c.c_future = _PyFuture_FromAST(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (c.c_future == NULL)
426 goto finally;
427 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 flags = &local_flags;
429 }
430 merged = c.c_future->ff_features | flags->cf_flags;
431 c.c_future->ff_features = merged;
432 flags->cf_flags = merged;
433 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200434 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000436
Pablo Galindod112c602020-03-18 23:02:09 +0000437 _PyASTOptimizeState state;
438 state.optimize = c.c_optimize;
439 state.ff_features = merged;
440
441 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900442 goto finally;
443 }
444
Victor Stinner28ad12f2021-03-19 12:41:49 +0100445 c.c_st = _PySymtable_Build(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 if (c.c_st == NULL) {
447 if (!PyErr_Occurred())
448 PyErr_SetString(PyExc_SystemError, "no symtable");
449 goto finally;
450 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453
Thomas Wouters1175c432006-02-27 22:49:54 +0000454 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 compiler_free(&c);
456 assert(co || PyErr_Occurred());
457 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458}
459
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000460static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (c->c_st)
Victor Stinner28ad12f2021-03-19 12:41:49 +0100464 _PySymtable_Free(c->c_st);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (c->c_future)
466 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200467 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900468 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000470}
471
Guido van Rossum79f25d91997-04-29 20:08:16 +0000472static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_ssize_t i, n;
476 PyObject *v, *k;
477 PyObject *dict = PyDict_New();
478 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 n = PyList_Size(list);
481 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100482 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 if (!v) {
484 Py_DECREF(dict);
485 return NULL;
486 }
487 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300488 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 Py_DECREF(v);
490 Py_DECREF(dict);
491 return NULL;
492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 Py_DECREF(v);
494 }
495 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496}
497
498/* Return new dict containing names from src that match scope(s).
499
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000500src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000502values are integers, starting at offset and increasing by one for
503each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504*/
505
506static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100507dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000508{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700509 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500511 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 assert(offset >= 0);
514 if (dest == NULL)
515 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000516
Meador Inge2ca63152012-07-18 14:20:11 -0500517 /* Sort the keys so that we have a deterministic order on the indexes
518 saved in the returned dictionary. These indexes are used as indexes
519 into the free and cell var storage. Therefore if they aren't
520 deterministic, then the generated bytecode is not deterministic.
521 */
522 sorted_keys = PyDict_Keys(src);
523 if (sorted_keys == NULL)
524 return NULL;
525 if (PyList_Sort(sorted_keys) != 0) {
526 Py_DECREF(sorted_keys);
527 return NULL;
528 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500529 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500530
531 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 /* XXX this should probably be a macro in symtable.h */
533 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500534 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200535 v = PyDict_GetItemWithError(src, k);
536 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 vi = PyLong_AS_LONG(v);
538 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300541 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500543 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 Py_DECREF(dest);
545 return NULL;
546 }
547 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300548 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500549 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 Py_DECREF(item);
551 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 return NULL;
553 }
554 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 }
556 }
Meador Inge2ca63152012-07-18 14:20:11 -0500557 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000559}
560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561static void
562compiler_unit_check(struct compiler_unit *u)
563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 basicblock *block;
565 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +0100566 assert(!_PyMem_IsPtrFreed(block));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (block->b_instr != NULL) {
568 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100569 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 assert(block->b_ialloc >= block->b_iused);
571 }
572 else {
573 assert (block->b_iused == 0);
574 assert (block->b_ialloc == 0);
575 }
576 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000577}
578
579static void
580compiler_unit_free(struct compiler_unit *u)
581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 compiler_unit_check(u);
585 b = u->u_blocks;
586 while (b != NULL) {
587 if (b->b_instr)
588 PyObject_Free((void *)b->b_instr);
589 next = b->b_list;
590 PyObject_Free((void *)b);
591 b = next;
592 }
593 Py_CLEAR(u->u_ste);
594 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400595 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 Py_CLEAR(u->u_consts);
597 Py_CLEAR(u->u_names);
598 Py_CLEAR(u->u_varnames);
599 Py_CLEAR(u->u_freevars);
600 Py_CLEAR(u->u_cellvars);
601 Py_CLEAR(u->u_private);
602 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000603}
604
605static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100606compiler_enter_scope(struct compiler *c, identifier name,
607 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100610 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000611
Andy Lester7668a8b2020-03-24 23:26:44 -0500612 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 struct compiler_unit));
614 if (!u) {
615 PyErr_NoMemory();
616 return 0;
617 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100618 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100620 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 u->u_kwonlyargcount = 0;
622 u->u_ste = PySymtable_Lookup(c->c_st, key);
623 if (!u->u_ste) {
624 compiler_unit_free(u);
625 return 0;
626 }
627 Py_INCREF(name);
628 u->u_name = name;
629 u->u_varnames = list2dict(u->u_ste->ste_varnames);
630 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
631 if (!u->u_varnames || !u->u_cellvars) {
632 compiler_unit_free(u);
633 return 0;
634 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500635 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000636 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500637 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300638 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500639 int res;
640 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200641 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500642 name = _PyUnicode_FromId(&PyId___class__);
643 if (!name) {
644 compiler_unit_free(u);
645 return 0;
646 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100647 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500648 if (res < 0) {
649 compiler_unit_free(u);
650 return 0;
651 }
652 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200655 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (!u->u_freevars) {
657 compiler_unit_free(u);
658 return 0;
659 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 u->u_blocks = NULL;
662 u->u_nfblocks = 0;
663 u->u_firstlineno = lineno;
664 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000665 u->u_col_offset = 0;
Pablo Galindoa77aac42021-04-23 14:27:05 +0100666 u->u_end_lineno = 0;
667 u->u_end_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 u->u_consts = PyDict_New();
669 if (!u->u_consts) {
670 compiler_unit_free(u);
671 return 0;
672 }
673 u->u_names = PyDict_New();
674 if (!u->u_names) {
675 compiler_unit_free(u);
676 return 0;
677 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 /* Push the old compiler_unit on the stack. */
682 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400683 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
685 Py_XDECREF(capsule);
686 compiler_unit_free(u);
687 return 0;
688 }
689 Py_DECREF(capsule);
690 u->u_private = c->u->u_private;
691 Py_XINCREF(u->u_private);
692 }
693 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100696
697 block = compiler_new_block(c);
698 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100700 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000701
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400702 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
703 if (!compiler_set_qualname(c))
704 return 0;
705 }
706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000708}
709
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000710static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000711compiler_exit_scope(struct compiler *c)
712{
Victor Stinnera6192632021-01-29 16:53:03 +0100713 // Don't call PySequence_DelItem() with an exception raised
714 PyObject *exc_type, *exc_val, *exc_tb;
715 PyErr_Fetch(&exc_type, &exc_val, &exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 c->c_nestlevel--;
718 compiler_unit_free(c->u);
719 /* Restore c->u to the parent unit. */
Victor Stinnera6192632021-01-29 16:53:03 +0100720 Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (n >= 0) {
Victor Stinnera6192632021-01-29 16:53:03 +0100722 PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400723 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 assert(c->u);
725 /* we are deleting from a list so this really shouldn't fail */
Victor Stinnera6192632021-01-29 16:53:03 +0100726 if (PySequence_DelItem(c->c_stack, n) < 0) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +0100727 _PyErr_WriteUnraisableMsg("on removing the last compiler "
728 "stack item", NULL);
Victor Stinnera6192632021-01-29 16:53:03 +0100729 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 compiler_unit_check(c->u);
731 }
Victor Stinnera6192632021-01-29 16:53:03 +0100732 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 c->u = NULL;
Victor Stinnera6192632021-01-29 16:53:03 +0100734 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000735
Victor Stinnera6192632021-01-29 16:53:03 +0100736 PyErr_Restore(exc_type, exc_val, exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737}
738
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400739static int
740compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100742 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400743 _Py_static_string(dot_locals, ".<locals>");
744 Py_ssize_t stack_size;
745 struct compiler_unit *u = c->u;
746 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100747
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400748 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100749 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400750 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400751 if (stack_size > 1) {
752 int scope, force_global = 0;
753 struct compiler_unit *parent;
754 PyObject *mangled, *capsule;
755
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400756 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400757 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400758 assert(parent);
759
Yury Selivanov75445082015-05-11 22:57:16 -0400760 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
761 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
762 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400763 assert(u->u_name);
764 mangled = _Py_Mangle(parent->u_private, u->u_name);
765 if (!mangled)
766 return 0;
Victor Stinner28ad12f2021-03-19 12:41:49 +0100767 scope = _PyST_GetScope(parent->u_ste, mangled);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400768 Py_DECREF(mangled);
769 assert(scope != GLOBAL_IMPLICIT);
770 if (scope == GLOBAL_EXPLICIT)
771 force_global = 1;
772 }
773
774 if (!force_global) {
775 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400776 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400777 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
778 dot_locals_str = _PyUnicode_FromId(&dot_locals);
779 if (dot_locals_str == NULL)
780 return 0;
781 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
782 if (base == NULL)
783 return 0;
784 }
785 else {
786 Py_INCREF(parent->u_qualname);
787 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400788 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100789 }
790 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400791
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400792 if (base != NULL) {
793 dot_str = _PyUnicode_FromId(&dot);
794 if (dot_str == NULL) {
795 Py_DECREF(base);
796 return 0;
797 }
798 name = PyUnicode_Concat(base, dot_str);
799 Py_DECREF(base);
800 if (name == NULL)
801 return 0;
802 PyUnicode_Append(&name, u->u_name);
803 if (name == NULL)
804 return 0;
805 }
806 else {
807 Py_INCREF(u->u_name);
808 name = u->u_name;
809 }
810 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100811
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400812 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100813}
814
Eric V. Smith235a6f02015-09-19 14:51:32 -0400815
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000816/* Allocate a new block and return a pointer to it.
817 Returns NULL on error.
818*/
819
820static basicblock *
821compiler_new_block(struct compiler *c)
822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 basicblock *b;
824 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500827 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (b == NULL) {
829 PyErr_NoMemory();
830 return NULL;
831 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 /* Extend the singly linked list of blocks with new block. */
833 b->b_list = u->u_blocks;
834 u->u_blocks = b;
835 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000836}
837
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000839compiler_next_block(struct compiler *c)
840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 basicblock *block = compiler_new_block(c);
842 if (block == NULL)
843 return NULL;
844 c->u->u_curblock->b_next = block;
845 c->u->u_curblock = block;
846 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000847}
848
849static basicblock *
850compiler_use_next_block(struct compiler *c, basicblock *block)
851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 assert(block != NULL);
853 c->u->u_curblock->b_next = block;
854 c->u->u_curblock = block;
855 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000856}
857
Mark Shannon5977a792020-12-02 13:31:40 +0000858static basicblock *
859compiler_copy_block(struct compiler *c, basicblock *block)
860{
861 /* Cannot copy a block if it has a fallthrough, since
862 * a block can only have one fallthrough predecessor.
863 */
864 assert(block->b_nofallthrough);
865 basicblock *result = compiler_next_block(c);
866 if (result == NULL) {
867 return NULL;
868 }
869 for (int i = 0; i < block->b_iused; i++) {
870 int n = compiler_next_instr(result);
871 if (n < 0) {
872 return NULL;
873 }
874 result->b_instr[n] = block->b_instr[i];
875 }
876 result->b_exit = block->b_exit;
Mark Shannon3bd60352021-01-13 12:05:43 +0000877 result->b_nofallthrough = 1;
Mark Shannon5977a792020-12-02 13:31:40 +0000878 return result;
879}
880
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000881/* Returns the offset of the next instruction in the current block's
882 b_instr array. Resizes the b_instr as necessary.
883 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000884*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000885
886static int
Andy Lester76d58772020-03-10 21:18:12 -0500887compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 assert(b != NULL);
890 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500891 b->b_instr = (struct instr *)PyObject_Calloc(
892 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (b->b_instr == NULL) {
894 PyErr_NoMemory();
895 return -1;
896 }
897 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 }
899 else if (b->b_iused == b->b_ialloc) {
900 struct instr *tmp;
901 size_t oldsize, newsize;
902 oldsize = b->b_ialloc * sizeof(struct instr);
903 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000904
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700905 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyErr_NoMemory();
907 return -1;
908 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 if (newsize == 0) {
911 PyErr_NoMemory();
912 return -1;
913 }
914 b->b_ialloc <<= 1;
915 tmp = (struct instr *)PyObject_Realloc(
916 (void *)b->b_instr, newsize);
917 if (tmp == NULL) {
918 PyErr_NoMemory();
919 return -1;
920 }
921 b->b_instr = tmp;
922 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
923 }
924 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000925}
926
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200927/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000928
Christian Heimes2202f872008-02-06 14:31:34 +0000929 The line number is reset in the following cases:
930 - when entering a new scope
931 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200932 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200933 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000934*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000935
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200936#define SET_LOC(c, x) \
937 (c)->u->u_lineno = (x)->lineno; \
Pablo Galindoa77aac42021-04-23 14:27:05 +0100938 (c)->u->u_col_offset = (x)->col_offset; \
939 (c)->u->u_end_lineno = (x)->end_lineno; \
940 (c)->u->u_end_col_offset = (x)->end_col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200942/* Return the stack effect of opcode with argument oparg.
943
944 Some opcodes have different stack effect when jump to the target and
945 when not jump. The 'jump' parameter specifies the case:
946
947 * 0 -- when not jump
948 * 1 -- when jump
949 * -1 -- maximal
950 */
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200951static int
952stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300955 case NOP:
956 case EXTENDED_ARG:
957 return 0;
958
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200959 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case POP_TOP:
961 return -1;
962 case ROT_TWO:
963 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200964 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return 0;
966 case DUP_TOP:
967 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000968 case DUP_TOP_TWO:
969 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200971 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 case UNARY_POSITIVE:
973 case UNARY_NEGATIVE:
974 case UNARY_NOT:
975 case UNARY_INVERT:
976 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 case SET_ADD:
979 case LIST_APPEND:
980 return -1;
981 case MAP_ADD:
982 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000983
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200984 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 case BINARY_POWER:
986 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400987 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case BINARY_MODULO:
989 case BINARY_ADD:
990 case BINARY_SUBTRACT:
991 case BINARY_SUBSCR:
992 case BINARY_FLOOR_DIVIDE:
993 case BINARY_TRUE_DIVIDE:
994 return -1;
995 case INPLACE_FLOOR_DIVIDE:
996 case INPLACE_TRUE_DIVIDE:
997 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case INPLACE_ADD:
1000 case INPLACE_SUBTRACT:
1001 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -04001002 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 case INPLACE_MODULO:
1004 return -1;
1005 case STORE_SUBSCR:
1006 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 case DELETE_SUBSCR:
1008 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 case BINARY_LSHIFT:
1011 case BINARY_RSHIFT:
1012 case BINARY_AND:
1013 case BINARY_XOR:
1014 case BINARY_OR:
1015 return -1;
1016 case INPLACE_POWER:
1017 return -1;
1018 case GET_ITER:
1019 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case PRINT_EXPR:
1022 return -1;
1023 case LOAD_BUILD_CLASS:
1024 return 1;
1025 case INPLACE_LSHIFT:
1026 case INPLACE_RSHIFT:
1027 case INPLACE_AND:
1028 case INPLACE_XOR:
1029 case INPLACE_OR:
1030 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001033 /* 1 in the normal flow.
1034 * Restore the stack position and push 6 values before jumping to
1035 * the handler if an exception be raised. */
1036 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 case RETURN_VALUE:
1038 return -1;
1039 case IMPORT_STAR:
1040 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001041 case SETUP_ANNOTATIONS:
1042 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case YIELD_VALUE:
1044 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05001045 case YIELD_FROM:
1046 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 case POP_BLOCK:
1048 return 0;
1049 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001050 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 case STORE_NAME:
1053 return -1;
1054 case DELETE_NAME:
1055 return 0;
1056 case UNPACK_SEQUENCE:
1057 return oparg-1;
1058 case UNPACK_EX:
1059 return (oparg&0xFF) + (oparg>>8);
1060 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001061 /* -1 at end of iterator, 1 if continue iterating. */
1062 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 case STORE_ATTR:
1065 return -2;
1066 case DELETE_ATTR:
1067 return -1;
1068 case STORE_GLOBAL:
1069 return -1;
1070 case DELETE_GLOBAL:
1071 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 case LOAD_CONST:
1073 return 1;
1074 case LOAD_NAME:
1075 return 1;
1076 case BUILD_TUPLE:
1077 case BUILD_LIST:
1078 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001079 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 return 1-oparg;
1081 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001082 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001083 case BUILD_CONST_KEY_MAP:
1084 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 case LOAD_ATTR:
1086 return 0;
1087 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001088 case IS_OP:
1089 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001091 case JUMP_IF_NOT_EXC_MATCH:
1092 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 case IMPORT_NAME:
1094 return -1;
1095 case IMPORT_FROM:
1096 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001097
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001098 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 case JUMP_ABSOLUTE:
1101 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001102
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001103 case JUMP_IF_TRUE_OR_POP:
1104 case JUMP_IF_FALSE_OR_POP:
1105 return jump ? 0 : -1;
1106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 case POP_JUMP_IF_FALSE:
1108 case POP_JUMP_IF_TRUE:
1109 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 case LOAD_GLOBAL:
1112 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001113
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001114 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001116 /* 0 in the normal flow.
1117 * Restore the stack position and push 6 values before jumping to
1118 * the handler if an exception be raised. */
1119 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001120 case RERAISE:
1121 return -3;
1122
1123 case WITH_EXCEPT_START:
1124 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 case LOAD_FAST:
1127 return 1;
1128 case STORE_FAST:
1129 return -1;
1130 case DELETE_FAST:
1131 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 case RAISE_VARARGS:
1134 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001135
1136 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001138 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001139 case CALL_METHOD:
1140 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001142 return -oparg-1;
1143 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001144 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001145 case MAKE_FUNCTION:
1146 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1147 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 case BUILD_SLICE:
1149 if (oparg == 3)
1150 return -2;
1151 else
1152 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001154 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 case LOAD_CLOSURE:
1156 return 1;
1157 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001158 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 return 1;
1160 case STORE_DEREF:
1161 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001162 case DELETE_DEREF:
1163 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001164
1165 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001166 case GET_AWAITABLE:
1167 return 0;
1168 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001169 /* 0 in the normal flow.
1170 * Restore the stack position to the position before the result
1171 * of __aenter__ and push 6 values before jumping to the handler
1172 * if an exception be raised. */
1173 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001174 case BEFORE_ASYNC_WITH:
1175 return 1;
1176 case GET_AITER:
1177 return 0;
1178 case GET_ANEXT:
1179 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001180 case GET_YIELD_FROM_ITER:
1181 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001182 case END_ASYNC_FOR:
1183 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001184 case FORMAT_VALUE:
1185 /* If there's a fmt_spec on the stack, we go from 2->1,
1186 else 1->1. */
1187 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001188 case LOAD_METHOD:
1189 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001190 case LOAD_ASSERTION_ERROR:
1191 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001192 case LIST_TO_TUPLE:
1193 return 0;
Mark Shannonb37181e2021-04-06 11:48:59 +01001194 case GEN_START:
1195 return -1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001196 case LIST_EXTEND:
1197 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001198 case DICT_MERGE:
1199 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001200 return -1;
Brandt Bucher145bf262021-02-26 14:51:55 -08001201 case COPY_DICT_WITHOUT_KEYS:
1202 return 0;
1203 case MATCH_CLASS:
1204 return -1;
1205 case GET_LEN:
1206 case MATCH_MAPPING:
1207 case MATCH_SEQUENCE:
1208 return 1;
1209 case MATCH_KEYS:
1210 return 2;
Brandt Bucher0ad1e032021-05-02 13:02:10 -07001211 case ROT_N:
1212 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001214 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 }
Larry Hastings3a907972013-11-23 14:49:22 -08001216 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217}
1218
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001219int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001220PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1221{
1222 return stack_effect(opcode, oparg, jump);
1223}
1224
1225int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001226PyCompile_OpcodeStackEffect(int opcode, int oparg)
1227{
1228 return stack_effect(opcode, oparg, -1);
1229}
1230
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001231/* Add an opcode with no argument.
1232 Returns 0 on failure, 1 on success.
1233*/
1234
1235static int
Mark Shannon3bd60352021-01-13 12:05:43 +00001236compiler_addop_line(struct compiler *c, int opcode, int line)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 basicblock *b;
1239 struct instr *i;
1240 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001241 assert(!HAS_ARG(opcode));
Andy Lester76d58772020-03-10 21:18:12 -05001242 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (off < 0)
1244 return 0;
1245 b = c->u->u_curblock;
1246 i = &b->b_instr[off];
1247 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001248 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (opcode == RETURN_VALUE)
1250 b->b_return = 1;
Mark Shannon3bd60352021-01-13 12:05:43 +00001251 i->i_lineno = line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001253}
1254
Mark Shannon3bd60352021-01-13 12:05:43 +00001255static int
1256compiler_addop(struct compiler *c, int opcode)
1257{
1258 return compiler_addop_line(c, opcode, c->u->u_lineno);
1259}
1260
1261static int
1262compiler_addop_noline(struct compiler *c, int opcode)
1263{
1264 return compiler_addop_line(c, opcode, -1);
1265}
1266
1267
Victor Stinnerf8e32212013-11-19 23:56:34 +01001268static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001269compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001270{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001271 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001273
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001274 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001276 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001278 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001279 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001280 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 return -1;
1283 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001284 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 Py_DECREF(v);
1286 return -1;
1287 }
1288 Py_DECREF(v);
1289 }
1290 else
1291 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001292 return arg;
1293}
1294
INADA Naokic2e16072018-11-26 21:23:22 +09001295// Merge const *o* recursively and return constant key object.
1296static PyObject*
1297merge_consts_recursive(struct compiler *c, PyObject *o)
1298{
1299 // None and Ellipsis are singleton, and key is the singleton.
1300 // No need to merge object and key.
1301 if (o == Py_None || o == Py_Ellipsis) {
1302 Py_INCREF(o);
1303 return o;
1304 }
1305
1306 PyObject *key = _PyCode_ConstantKey(o);
1307 if (key == NULL) {
1308 return NULL;
1309 }
1310
1311 // t is borrowed reference
1312 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1313 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001314 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001315 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001316 Py_DECREF(key);
1317 return t;
1318 }
1319
INADA Naokif7e4d362018-11-29 00:58:46 +09001320 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001321 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001322 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001323 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001324 Py_ssize_t len = PyTuple_GET_SIZE(o);
1325 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001326 PyObject *item = PyTuple_GET_ITEM(o, i);
1327 PyObject *u = merge_consts_recursive(c, item);
1328 if (u == NULL) {
1329 Py_DECREF(key);
1330 return NULL;
1331 }
1332
1333 // See _PyCode_ConstantKey()
1334 PyObject *v; // borrowed
1335 if (PyTuple_CheckExact(u)) {
1336 v = PyTuple_GET_ITEM(u, 1);
1337 }
1338 else {
1339 v = u;
1340 }
1341 if (v != item) {
1342 Py_INCREF(v);
1343 PyTuple_SET_ITEM(o, i, v);
1344 Py_DECREF(item);
1345 }
1346
1347 Py_DECREF(u);
1348 }
1349 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001350 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001351 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001352 // constant keys.
1353 // See _PyCode_ConstantKey() for detail.
1354 assert(PyTuple_CheckExact(key));
1355 assert(PyTuple_GET_SIZE(key) == 2);
1356
1357 Py_ssize_t len = PySet_GET_SIZE(o);
1358 if (len == 0) { // empty frozenset should not be re-created.
1359 return key;
1360 }
1361 PyObject *tuple = PyTuple_New(len);
1362 if (tuple == NULL) {
1363 Py_DECREF(key);
1364 return NULL;
1365 }
1366 Py_ssize_t i = 0, pos = 0;
1367 PyObject *item;
1368 Py_hash_t hash;
1369 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1370 PyObject *k = merge_consts_recursive(c, item);
1371 if (k == NULL) {
1372 Py_DECREF(tuple);
1373 Py_DECREF(key);
1374 return NULL;
1375 }
1376 PyObject *u;
1377 if (PyTuple_CheckExact(k)) {
1378 u = PyTuple_GET_ITEM(k, 1);
1379 Py_INCREF(u);
1380 Py_DECREF(k);
1381 }
1382 else {
1383 u = k;
1384 }
1385 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1386 i++;
1387 }
1388
1389 // Instead of rewriting o, we create new frozenset and embed in the
1390 // key tuple. Caller should get merged frozenset from the key tuple.
1391 PyObject *new = PyFrozenSet_New(tuple);
1392 Py_DECREF(tuple);
1393 if (new == NULL) {
1394 Py_DECREF(key);
1395 return NULL;
1396 }
1397 assert(PyTuple_GET_ITEM(key, 1) == o);
1398 Py_DECREF(o);
1399 PyTuple_SET_ITEM(key, 1, new);
1400 }
INADA Naokic2e16072018-11-26 21:23:22 +09001401
1402 return key;
1403}
1404
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001405static Py_ssize_t
1406compiler_add_const(struct compiler *c, PyObject *o)
1407{
INADA Naokic2e16072018-11-26 21:23:22 +09001408 PyObject *key = merge_consts_recursive(c, o);
1409 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001410 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001411 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001412
Andy Lester76d58772020-03-10 21:18:12 -05001413 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001414 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001416}
1417
1418static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001419compiler_addop_load_const(struct compiler *c, PyObject *o)
1420{
1421 Py_ssize_t arg = compiler_add_const(c, o);
1422 if (arg < 0)
1423 return 0;
1424 return compiler_addop_i(c, LOAD_CONST, arg);
1425}
1426
1427static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001430{
Andy Lester76d58772020-03-10 21:18:12 -05001431 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001432 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001433 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001434 return compiler_addop_i(c, opcode, arg);
1435}
1436
1437static int
1438compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001441 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001442
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1444 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001445 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001446 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447 Py_DECREF(mangled);
1448 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001449 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450 return compiler_addop_i(c, opcode, arg);
1451}
1452
1453/* Add an opcode with an integer argument.
1454 Returns 0 on failure, 1 on success.
1455*/
1456
1457static int
Mark Shannon11e0b292021-04-15 14:28:56 +01001458compiler_addop_i_line(struct compiler *c, int opcode, Py_ssize_t oparg, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 struct instr *i;
1461 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001462
Victor Stinner2ad474b2016-03-01 23:34:47 +01001463 /* oparg value is unsigned, but a signed C int is usually used to store
1464 it in the C code (like Python/ceval.c).
1465
1466 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1467
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001468 The argument of a concrete bytecode instruction is limited to 8-bit.
1469 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1470 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001471 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001472
Andy Lester76d58772020-03-10 21:18:12 -05001473 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (off < 0)
1475 return 0;
1476 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001477 i->i_opcode = opcode;
1478 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Mark Shannon11e0b292021-04-15 14:28:56 +01001479 i->i_lineno = lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001481}
1482
Mark Shannon11e0b292021-04-15 14:28:56 +01001483static int
1484compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
1485{
1486 return compiler_addop_i_line(c, opcode, oparg, c->u->u_lineno);
1487}
1488
1489static int
1490compiler_addop_i_noline(struct compiler *c, int opcode, Py_ssize_t oparg)
1491{
1492 return compiler_addop_i_line(c, opcode, oparg, -1);
1493}
1494
Mark Shannon28b75c82020-12-23 11:43:10 +00001495static int add_jump_to_block(basicblock *b, int opcode, int lineno, basicblock *target)
1496{
1497 assert(HAS_ARG(opcode));
1498 assert(b != NULL);
1499 assert(target != NULL);
1500
1501 int off = compiler_next_instr(b);
1502 struct instr *i = &b->b_instr[off];
1503 if (off < 0) {
1504 return 0;
1505 }
1506 i->i_opcode = opcode;
1507 i->i_target = target;
1508 i->i_lineno = lineno;
1509 return 1;
1510}
1511
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001513compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001514{
Mark Shannon28b75c82020-12-23 11:43:10 +00001515 return add_jump_to_block(c->u->u_curblock, opcode, c->u->u_lineno, b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516}
1517
Mark Shannon127dde52021-01-04 18:06:55 +00001518static int
1519compiler_addop_j_noline(struct compiler *c, int opcode, basicblock *b)
1520{
1521 return add_jump_to_block(c->u->u_curblock, opcode, -1, b);
1522}
1523
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001524/* NEXT_BLOCK() creates an implicit jump from the current block
1525 to the new block.
1526
1527 The returns inside this macro make it impossible to decref objects
1528 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (compiler_next_block((C)) == NULL) \
1532 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533}
1534
1535#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (!compiler_addop((C), (OP))) \
1537 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001538}
1539
Mark Shannon3bd60352021-01-13 12:05:43 +00001540#define ADDOP_NOLINE(C, OP) { \
1541 if (!compiler_addop_noline((C), (OP))) \
1542 return 0; \
1543}
1544
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001545#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (!compiler_addop((C), (OP))) { \
1547 compiler_exit_scope(c); \
1548 return 0; \
1549 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001550}
1551
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001552#define ADDOP_LOAD_CONST(C, O) { \
1553 if (!compiler_addop_load_const((C), (O))) \
1554 return 0; \
1555}
1556
1557/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1558#define ADDOP_LOAD_CONST_NEW(C, O) { \
1559 PyObject *__new_const = (O); \
1560 if (__new_const == NULL) { \
1561 return 0; \
1562 } \
1563 if (!compiler_addop_load_const((C), __new_const)) { \
1564 Py_DECREF(__new_const); \
1565 return 0; \
1566 } \
1567 Py_DECREF(__new_const); \
1568}
1569
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001570#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1572 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001573}
1574
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001575/* Same as ADDOP_O, but steals a reference. */
1576#define ADDOP_N(C, OP, O, TYPE) { \
1577 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1578 Py_DECREF((O)); \
1579 return 0; \
1580 } \
1581 Py_DECREF((O)); \
1582}
1583
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001584#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1586 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001587}
1588
1589#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 if (!compiler_addop_i((C), (OP), (O))) \
1591 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001592}
1593
Mark Shannon11e0b292021-04-15 14:28:56 +01001594#define ADDOP_I_NOLINE(C, OP, O) { \
1595 if (!compiler_addop_i_noline((C), (OP), (O))) \
1596 return 0; \
1597}
1598
Mark Shannon582aaf12020-08-04 17:30:11 +01001599#define ADDOP_JUMP(C, OP, O) { \
1600 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001602}
1603
Mark Shannon127dde52021-01-04 18:06:55 +00001604/* Add a jump with no line number.
1605 * Used for artificial jumps that have no corresponding
1606 * token in the source code. */
1607#define ADDOP_JUMP_NOLINE(C, OP, O) { \
1608 if (!compiler_addop_j_noline((C), (OP), (O))) \
1609 return 0; \
1610}
1611
Mark Shannon9af0e472020-01-14 10:12:45 +00001612#define ADDOP_COMPARE(C, CMP) { \
1613 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1614 return 0; \
1615}
1616
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001617/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1618 the ASDL name to synthesize the name of the C type and the visit function.
1619*/
1620
1621#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (!compiler_visit_ ## TYPE((C), (V))) \
1623 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624}
1625
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001626#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (!compiler_visit_ ## TYPE((C), (V))) { \
1628 compiler_exit_scope(c); \
1629 return 0; \
1630 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001631}
1632
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (!compiler_visit_slice((C), (V), (CTX))) \
1635 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001636}
1637
1638#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001640 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1642 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1643 if (!compiler_visit_ ## TYPE((C), elt)) \
1644 return 0; \
1645 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001646}
1647
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001648#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001650 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1652 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1653 if (!compiler_visit_ ## TYPE((C), elt)) { \
1654 compiler_exit_scope(c); \
1655 return 0; \
1656 } \
1657 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001658}
1659
Brandt Bucher145bf262021-02-26 14:51:55 -08001660#define RETURN_IF_FALSE(X) \
1661 if (!(X)) { \
1662 return 0; \
1663 }
1664
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001665/* Search if variable annotations are present statically in a block. */
1666
1667static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001668find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001669{
1670 int i, j, res = 0;
1671 stmt_ty st;
1672
1673 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1674 st = (stmt_ty)asdl_seq_GET(stmts, i);
1675 switch (st->kind) {
1676 case AnnAssign_kind:
1677 return 1;
1678 case For_kind:
1679 res = find_ann(st->v.For.body) ||
1680 find_ann(st->v.For.orelse);
1681 break;
1682 case AsyncFor_kind:
1683 res = find_ann(st->v.AsyncFor.body) ||
1684 find_ann(st->v.AsyncFor.orelse);
1685 break;
1686 case While_kind:
1687 res = find_ann(st->v.While.body) ||
1688 find_ann(st->v.While.orelse);
1689 break;
1690 case If_kind:
1691 res = find_ann(st->v.If.body) ||
1692 find_ann(st->v.If.orelse);
1693 break;
1694 case With_kind:
1695 res = find_ann(st->v.With.body);
1696 break;
1697 case AsyncWith_kind:
1698 res = find_ann(st->v.AsyncWith.body);
1699 break;
1700 case Try_kind:
1701 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1702 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1703 st->v.Try.handlers, j);
1704 if (find_ann(handler->v.ExceptHandler.body)) {
1705 return 1;
1706 }
1707 }
1708 res = find_ann(st->v.Try.body) ||
1709 find_ann(st->v.Try.finalbody) ||
1710 find_ann(st->v.Try.orelse);
1711 break;
1712 default:
1713 res = 0;
1714 }
1715 if (res) {
1716 break;
1717 }
1718 }
1719 return res;
1720}
1721
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001722/*
1723 * Frame block handling functions
1724 */
1725
1726static int
1727compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001728 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001729{
1730 struct fblockinfo *f;
1731 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001732 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001733 }
1734 f = &c->u->u_fblock[c->u->u_nfblocks++];
1735 f->fb_type = t;
1736 f->fb_block = b;
1737 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001738 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001739 return 1;
1740}
1741
1742static void
1743compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1744{
1745 struct compiler_unit *u = c->u;
1746 assert(u->u_nfblocks > 0);
1747 u->u_nfblocks--;
1748 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1749 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1750}
1751
Mark Shannonfee55262019-11-21 09:11:43 +00001752static int
1753compiler_call_exit_with_nones(struct compiler *c) {
1754 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1755 ADDOP(c, DUP_TOP);
1756 ADDOP(c, DUP_TOP);
1757 ADDOP_I(c, CALL_FUNCTION, 3);
1758 return 1;
1759}
1760
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001761/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001762 * popping the blocks will be restored afterwards, unless another
1763 * return, break or continue is found. In which case, the TOS will
1764 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001765 */
1766static int
1767compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1768 int preserve_tos)
1769{
1770 switch (info->fb_type) {
1771 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001772 case EXCEPTION_HANDLER:
tomKPZ7a7ba3d2021-04-07 07:43:45 -07001773 case ASYNC_COMPREHENSION_GENERATOR:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001774 return 1;
1775
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001776 case FOR_LOOP:
1777 /* Pop the iterator */
1778 if (preserve_tos) {
1779 ADDOP(c, ROT_TWO);
1780 }
1781 ADDOP(c, POP_TOP);
1782 return 1;
1783
Mark Shannon02d126a2020-09-25 14:04:19 +01001784 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001785 ADDOP(c, POP_BLOCK);
1786 return 1;
1787
1788 case FINALLY_TRY:
Mark Shannon5274b682020-12-16 13:07:01 +00001789 /* This POP_BLOCK gets the line number of the unwinding statement */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001790 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001791 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001792 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1793 return 0;
1794 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001795 }
Mark Shannon5274b682020-12-16 13:07:01 +00001796 /* Emit the finally block */
Mark Shannonfee55262019-11-21 09:11:43 +00001797 VISIT_SEQ(c, stmt, info->fb_datum);
1798 if (preserve_tos) {
1799 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001800 }
Mark Shannon5274b682020-12-16 13:07:01 +00001801 /* The finally block should appear to execute after the
1802 * statement causing the unwinding, so make the unwinding
1803 * instruction artificial */
1804 c->u->u_lineno = -1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001805 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001806
Mark Shannonfee55262019-11-21 09:11:43 +00001807 case FINALLY_END:
1808 if (preserve_tos) {
1809 ADDOP(c, ROT_FOUR);
1810 }
1811 ADDOP(c, POP_TOP);
1812 ADDOP(c, POP_TOP);
1813 ADDOP(c, POP_TOP);
1814 if (preserve_tos) {
1815 ADDOP(c, ROT_FOUR);
1816 }
1817 ADDOP(c, POP_EXCEPT);
1818 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001819
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001820 case WITH:
1821 case ASYNC_WITH:
Mark Shannon5979e812021-04-30 14:32:47 +01001822 SET_LOC(c, (stmt_ty)info->fb_datum);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001823 ADDOP(c, POP_BLOCK);
1824 if (preserve_tos) {
1825 ADDOP(c, ROT_TWO);
1826 }
Mark Shannonfee55262019-11-21 09:11:43 +00001827 if(!compiler_call_exit_with_nones(c)) {
1828 return 0;
1829 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001830 if (info->fb_type == ASYNC_WITH) {
1831 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001832 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001833 ADDOP(c, YIELD_FROM);
1834 }
Mark Shannonfee55262019-11-21 09:11:43 +00001835 ADDOP(c, POP_TOP);
Mark Shannoncea05852021-06-03 19:57:31 +01001836 /* The exit block should appear to execute after the
1837 * statement causing the unwinding, so make the unwinding
1838 * instruction artificial */
1839 c->u->u_lineno = -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001840 return 1;
1841
1842 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001843 if (info->fb_datum) {
1844 ADDOP(c, POP_BLOCK);
1845 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001846 if (preserve_tos) {
1847 ADDOP(c, ROT_FOUR);
1848 }
Mark Shannonfee55262019-11-21 09:11:43 +00001849 ADDOP(c, POP_EXCEPT);
1850 if (info->fb_datum) {
1851 ADDOP_LOAD_CONST(c, Py_None);
1852 compiler_nameop(c, info->fb_datum, Store);
1853 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001854 }
Mark Shannonfee55262019-11-21 09:11:43 +00001855 return 1;
1856
1857 case POP_VALUE:
1858 if (preserve_tos) {
1859 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001860 }
Mark Shannonfee55262019-11-21 09:11:43 +00001861 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001862 return 1;
1863 }
1864 Py_UNREACHABLE();
1865}
1866
Mark Shannonfee55262019-11-21 09:11:43 +00001867/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1868static int
1869compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1870 if (c->u->u_nfblocks == 0) {
1871 return 1;
1872 }
1873 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1874 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1875 *loop = top;
1876 return 1;
1877 }
1878 struct fblockinfo copy = *top;
1879 c->u->u_nfblocks--;
1880 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1881 return 0;
1882 }
1883 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1884 return 0;
1885 }
1886 c->u->u_fblock[c->u->u_nfblocks] = copy;
1887 c->u->u_nfblocks++;
1888 return 1;
1889}
1890
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001891/* Compile a sequence of statements, checking for a docstring
1892 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001893
1894static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001895compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001897 int i = 0;
1898 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001899 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001900
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001901 /* Set current line number to the line number of first statement.
1902 This way line number for SETUP_ANNOTATIONS will always
1903 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301904 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001905 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001906 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001907 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001908 }
1909 /* Every annotated class and module should have __annotations__. */
1910 if (find_ann(stmts)) {
1911 ADDOP(c, SETUP_ANNOTATIONS);
1912 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001913 if (!asdl_seq_LEN(stmts))
1914 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001915 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001916 if (c->c_optimize < 2) {
1917 docstring = _PyAST_GetDocString(stmts);
1918 if (docstring) {
1919 i = 1;
1920 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1921 assert(st->kind == Expr_kind);
1922 VISIT(c, expr, st->v.Expr.value);
1923 if (!compiler_nameop(c, __doc__, Store))
1924 return 0;
1925 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001927 for (; i < asdl_seq_LEN(stmts); i++)
1928 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930}
1931
1932static PyCodeObject *
1933compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyCodeObject *co;
1936 int addNone = 1;
1937 static PyObject *module;
1938 if (!module) {
1939 module = PyUnicode_InternFromString("<module>");
1940 if (!module)
1941 return NULL;
1942 }
1943 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001944 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 return NULL;
1946 switch (mod->kind) {
1947 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001948 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 compiler_exit_scope(c);
1950 return 0;
1951 }
1952 break;
1953 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001954 if (find_ann(mod->v.Interactive.body)) {
1955 ADDOP(c, SETUP_ANNOTATIONS);
1956 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001958 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 break;
1960 case Expression_kind:
1961 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1962 addNone = 0;
1963 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 default:
1965 PyErr_Format(PyExc_SystemError,
1966 "module kind %d should not be possible",
1967 mod->kind);
1968 return 0;
1969 }
1970 co = assemble(c, addNone);
1971 compiler_exit_scope(c);
1972 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001973}
1974
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975/* The test for LOCAL must come before the test for FREE in order to
1976 handle classes where name is both local and free. The local var is
1977 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001978*/
1979
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980static int
1981get_ref_type(struct compiler *c, PyObject *name)
1982{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001983 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001984 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001985 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001986 return CELL;
Victor Stinner28ad12f2021-03-19 12:41:49 +01001987 scope = _PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (scope == 0) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001989 PyErr_Format(PyExc_SystemError,
Victor Stinner28ad12f2021-03-19 12:41:49 +01001990 "_PyST_GetScope(name=%R) failed: "
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001991 "unknown scope in unit %S (%R); "
1992 "symbols: %R; locals: %R; globals: %R",
1993 name,
1994 c->u->u_name, c->u->u_ste->ste_id,
1995 c->u->u_ste->ste_symbols, c->u->u_varnames, c->u->u_names);
1996 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999}
2000
2001static int
2002compiler_lookup_arg(PyObject *dict, PyObject *name)
2003{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002004 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02002005 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002006 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00002007 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00002008 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002009}
2010
2011static int
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002012compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags,
2013 PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002014{
Victor Stinnerad9a0662013-11-19 22:23:20 +01002015 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002016 if (qualname == NULL)
2017 qualname = co->co_name;
2018
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002019 if (free) {
2020 for (i = 0; i < free; ++i) {
2021 /* Bypass com_addop_varname because it will generate
2022 LOAD_DEREF but LOAD_CLOSURE is needed.
2023 */
2024 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002026 /* Special case: If a class contains a method with a
2027 free variable that has the same name as a method,
2028 the name will be considered free *and* local in the
2029 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10002030 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002031 */
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002032 int reftype = get_ref_type(c, name);
2033 if (reftype == -1) {
2034 return 0;
2035 }
2036 int arg;
2037 if (reftype == CELL) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002038 arg = compiler_lookup_arg(c->u->u_cellvars, name);
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002039 }
2040 else {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002041 arg = compiler_lookup_arg(c->u->u_freevars, name);
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002042 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002043 if (arg == -1) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002044 PyErr_Format(PyExc_SystemError,
2045 "compiler_lookup_arg(name=%R) with reftype=%d failed in %S; "
2046 "freevars of code %S: %R",
2047 name,
2048 reftype,
2049 c->u->u_name,
2050 co->co_name,
2051 co->co_freevars);
2052 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002053 }
2054 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002056 flags |= 0x08;
2057 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002059 ADDOP_LOAD_CONST(c, (PyObject*)co);
2060 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002061 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002063}
2064
2065static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002066compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (!decos)
2071 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2074 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
2075 }
2076 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077}
2078
2079static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002080compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
2081 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00002082{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002083 /* Push a dict of keyword-only default values.
2084
2085 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
2086 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002087 int i;
2088 PyObject *keys = NULL;
2089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
2091 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
2092 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
2093 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04002094 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002095 if (!mangled) {
2096 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002098 if (keys == NULL) {
2099 keys = PyList_New(1);
2100 if (keys == NULL) {
2101 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002102 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002103 }
2104 PyList_SET_ITEM(keys, 0, mangled);
2105 }
2106 else {
2107 int res = PyList_Append(keys, mangled);
2108 Py_DECREF(mangled);
2109 if (res == -1) {
2110 goto error;
2111 }
2112 }
2113 if (!compiler_visit_expr(c, default_)) {
2114 goto error;
2115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 }
2117 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002118 if (keys != NULL) {
2119 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2120 PyObject *keys_tuple = PyList_AsTuple(keys);
2121 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002122 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002123 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002124 assert(default_count > 0);
2125 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002126 }
2127 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002128 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002129 }
2130
2131error:
2132 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002133 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002134}
2135
2136static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002137compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2138{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002139 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002140 return 1;
2141}
2142
2143static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002144compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002145 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002146{
Pablo Galindob0544ba2021-04-21 12:41:19 +01002147 if (!annotation) {
2148 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 }
Pablo Galindob0544ba2021-04-21 12:41:19 +01002150
2151 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
2152 if (!mangled) {
2153 return 0;
2154 }
2155 ADDOP_LOAD_CONST(c, mangled);
2156 Py_DECREF(mangled);
2157
2158 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
2159 VISIT(c, annexpr, annotation)
2160 }
2161 else {
2162 VISIT(c, expr, annotation);
2163 }
2164 *annotations_len += 2;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002165 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002166}
2167
2168static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002169compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002170 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002171{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002172 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 for (i = 0; i < asdl_seq_LEN(args); i++) {
2174 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002175 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 c,
2177 arg->arg,
2178 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002179 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002180 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002182 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002183}
2184
2185static int
2186compiler_visit_annotations(struct compiler *c, arguments_ty args,
2187 expr_ty returns)
2188{
Yurii Karabas73019792020-11-25 12:43:18 +02002189 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002190 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002191
Yurii Karabas73019792020-11-25 12:43:18 +02002192 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 */
2194 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002195 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002196
Yurii Karabas73019792020-11-25 12:43:18 +02002197 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2198 return 0;
2199 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2200 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002201 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002202 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002203 args->vararg->annotation, &annotations_len))
2204 return 0;
2205 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2206 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002207 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002208 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002209 args->kwarg->annotation, &annotations_len))
2210 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (!return_str) {
2213 return_str = PyUnicode_InternFromString("return");
2214 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002215 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 }
Yurii Karabas73019792020-11-25 12:43:18 +02002217 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2218 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 }
2220
Yurii Karabas73019792020-11-25 12:43:18 +02002221 if (annotations_len) {
2222 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002223 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002225
Yurii Karabas73019792020-11-25 12:43:18 +02002226 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002227}
2228
2229static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002230compiler_visit_defaults(struct compiler *c, arguments_ty args)
2231{
2232 VISIT_SEQ(c, expr, args->defaults);
2233 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2234 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235}
2236
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002237static Py_ssize_t
2238compiler_default_arguments(struct compiler *c, arguments_ty args)
2239{
2240 Py_ssize_t funcflags = 0;
2241 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002242 if (!compiler_visit_defaults(c, args))
2243 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002244 funcflags |= 0x01;
2245 }
2246 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002247 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002248 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002249 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002250 return -1;
2251 }
2252 else if (res > 0) {
2253 funcflags |= 0x02;
2254 }
2255 }
2256 return funcflags;
2257}
2258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002259static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002260forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2261{
2262
2263 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2264 compiler_error(c, "cannot assign to __debug__");
2265 return 1;
2266 }
2267 return 0;
2268}
2269
2270static int
2271compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2272{
2273 if (arg != NULL) {
2274 if (forbidden_name(c, arg->arg, Store))
2275 return 0;
2276 }
2277 return 1;
2278}
2279
2280static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002281compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002282{
2283 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002284 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002285 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2286 return 0;
2287 }
2288 }
2289 return 1;
2290}
2291
2292static int
2293compiler_check_debug_args(struct compiler *c, arguments_ty args)
2294{
2295 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2296 return 0;
2297 if (!compiler_check_debug_args_seq(c, args->args))
2298 return 0;
2299 if (!compiler_check_debug_one_arg(c, args->vararg))
2300 return 0;
2301 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2302 return 0;
2303 if (!compiler_check_debug_one_arg(c, args->kwarg))
2304 return 0;
2305 return 1;
2306}
2307
2308static int
Yury Selivanov75445082015-05-11 22:57:16 -04002309compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002312 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002313 arguments_ty args;
2314 expr_ty returns;
2315 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002316 asdl_expr_seq* decos;
2317 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002318 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002319 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002320 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002321 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002322
Yury Selivanov75445082015-05-11 22:57:16 -04002323 if (is_async) {
2324 assert(s->kind == AsyncFunctionDef_kind);
2325
2326 args = s->v.AsyncFunctionDef.args;
2327 returns = s->v.AsyncFunctionDef.returns;
2328 decos = s->v.AsyncFunctionDef.decorator_list;
2329 name = s->v.AsyncFunctionDef.name;
2330 body = s->v.AsyncFunctionDef.body;
2331
2332 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2333 } else {
2334 assert(s->kind == FunctionDef_kind);
2335
2336 args = s->v.FunctionDef.args;
2337 returns = s->v.FunctionDef.returns;
2338 decos = s->v.FunctionDef.decorator_list;
2339 name = s->v.FunctionDef.name;
2340 body = s->v.FunctionDef.body;
2341
2342 scope_type = COMPILER_SCOPE_FUNCTION;
2343 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002344
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002345 if (!compiler_check_debug_args(c, args))
2346 return 0;
2347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 if (!compiler_decorators(c, decos))
2349 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002350
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002351 firstlineno = s->lineno;
2352 if (asdl_seq_LEN(decos)) {
2353 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2354 }
2355
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002356 funcflags = compiler_default_arguments(c, args);
2357 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002359 }
2360
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002361 annotations = compiler_visit_annotations(c, args, returns);
2362 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002363 return 0;
2364 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002365 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002366 funcflags |= 0x04;
2367 }
2368
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002369 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002370 return 0;
2371 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372
INADA Naokicb41b272017-02-23 00:31:59 +09002373 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002374 if (c->c_optimize < 2) {
2375 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002376 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002377 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 compiler_exit_scope(c);
2379 return 0;
2380 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002383 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002385 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002386 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002387 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002389 qualname = c->u->u_qualname;
2390 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002392 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002393 Py_XDECREF(qualname);
2394 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002396 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002398 if (!compiler_make_closure(c, co, funcflags, qualname)) {
2399 Py_DECREF(qualname);
2400 Py_DECREF(co);
2401 return 0;
2402 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002403 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 /* decorators */
2407 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2408 ADDOP_I(c, CALL_FUNCTION, 1);
2409 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002410
Yury Selivanov75445082015-05-11 22:57:16 -04002411 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412}
2413
2414static int
2415compiler_class(struct compiler *c, stmt_ty s)
2416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 PyCodeObject *co;
2418 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002419 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002420 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 if (!compiler_decorators(c, decos))
2423 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002424
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002425 firstlineno = s->lineno;
2426 if (asdl_seq_LEN(decos)) {
2427 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2428 }
2429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 /* ultimately generate code for:
2431 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2432 where:
2433 <func> is a function/closure created from the class body;
2434 it has a single argument (__locals__) where the dict
2435 (or MutableSequence) representing the locals is passed
2436 <name> is the class name
2437 <bases> is the positional arguments and *varargs argument
2438 <keywords> is the keyword arguments and **kwds argument
2439 This borrows from compiler_call.
2440 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002443 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002444 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 return 0;
2446 /* this block represents what we do in the new scope */
2447 {
2448 /* use the class name for name mangling */
2449 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002450 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* load (global) __name__ ... */
2452 str = PyUnicode_InternFromString("__name__");
2453 if (!str || !compiler_nameop(c, str, Load)) {
2454 Py_XDECREF(str);
2455 compiler_exit_scope(c);
2456 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 Py_DECREF(str);
2459 /* ... and store it as __module__ */
2460 str = PyUnicode_InternFromString("__module__");
2461 if (!str || !compiler_nameop(c, str, Store)) {
2462 Py_XDECREF(str);
2463 compiler_exit_scope(c);
2464 return 0;
2465 }
2466 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002467 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002468 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002469 str = PyUnicode_InternFromString("__qualname__");
2470 if (!str || !compiler_nameop(c, str, Store)) {
2471 Py_XDECREF(str);
2472 compiler_exit_scope(c);
2473 return 0;
2474 }
2475 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002477 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 compiler_exit_scope(c);
2479 return 0;
2480 }
Mark Shannone56d54e2021-01-15 13:52:00 +00002481 /* The following code is artificial */
2482 c->u->u_lineno = -1;
Nick Coghlan19d24672016-12-05 16:47:55 +10002483 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002484 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002485 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002486 str = PyUnicode_InternFromString("__class__");
2487 if (str == NULL) {
2488 compiler_exit_scope(c);
2489 return 0;
2490 }
2491 i = compiler_lookup_arg(c->u->u_cellvars, str);
2492 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002493 if (i < 0) {
2494 compiler_exit_scope(c);
2495 return 0;
2496 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002497 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002500 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002501 str = PyUnicode_InternFromString("__classcell__");
2502 if (!str || !compiler_nameop(c, str, Store)) {
2503 Py_XDECREF(str);
2504 compiler_exit_scope(c);
2505 return 0;
2506 }
2507 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002509 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002510 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002511 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002512 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002513 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002514 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 /* create the code object */
2516 co = assemble(c, 1);
2517 }
2518 /* leave the new scope */
2519 compiler_exit_scope(c);
2520 if (co == NULL)
2521 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 /* 2. load the 'build_class' function */
2524 ADDOP(c, LOAD_BUILD_CLASS);
2525
2526 /* 3. load a function (or closure) made from the code object */
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002527 if (!compiler_make_closure(c, co, 0, NULL)) {
2528 Py_DECREF(co);
2529 return 0;
2530 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 Py_DECREF(co);
2532
2533 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002534 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535
2536 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002537 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 return 0;
2539
2540 /* 6. apply decorators */
2541 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2542 ADDOP_I(c, CALL_FUNCTION, 1);
2543 }
2544
2545 /* 7. store into <name> */
2546 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2547 return 0;
2548 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002549}
2550
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002551/* Return 0 if the expression is a constant value except named singletons.
2552 Return 1 otherwise. */
2553static int
2554check_is_arg(expr_ty e)
2555{
2556 if (e->kind != Constant_kind) {
2557 return 1;
2558 }
2559 PyObject *value = e->v.Constant.value;
2560 return (value == Py_None
2561 || value == Py_False
2562 || value == Py_True
2563 || value == Py_Ellipsis);
2564}
2565
2566/* Check operands of identity chacks ("is" and "is not").
2567 Emit a warning if any operand is a constant except named singletons.
2568 Return 0 on error.
2569 */
2570static int
2571check_compare(struct compiler *c, expr_ty e)
2572{
2573 Py_ssize_t i, n;
2574 int left = check_is_arg(e->v.Compare.left);
2575 n = asdl_seq_LEN(e->v.Compare.ops);
2576 for (i = 0; i < n; i++) {
2577 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2578 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2579 if (op == Is || op == IsNot) {
2580 if (!right || !left) {
2581 const char *msg = (op == Is)
2582 ? "\"is\" with a literal. Did you mean \"==\"?"
2583 : "\"is not\" with a literal. Did you mean \"!=\"?";
2584 return compiler_warn(c, msg);
2585 }
2586 }
2587 left = right;
2588 }
2589 return 1;
2590}
2591
Mark Shannon9af0e472020-01-14 10:12:45 +00002592static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002593{
Mark Shannon9af0e472020-01-14 10:12:45 +00002594 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002595 switch (op) {
2596 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002597 cmp = Py_EQ;
2598 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002599 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002600 cmp = Py_NE;
2601 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002602 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002603 cmp = Py_LT;
2604 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002605 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002606 cmp = Py_LE;
2607 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002608 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002609 cmp = Py_GT;
2610 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002611 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002612 cmp = Py_GE;
2613 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002614 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002615 ADDOP_I(c, IS_OP, 0);
2616 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002617 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002618 ADDOP_I(c, IS_OP, 1);
2619 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002620 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002621 ADDOP_I(c, CONTAINS_OP, 0);
2622 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002623 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002624 ADDOP_I(c, CONTAINS_OP, 1);
2625 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002626 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002627 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002628 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002629 ADDOP_I(c, COMPARE_OP, cmp);
2630 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002631}
2632
Mark Shannon9af0e472020-01-14 10:12:45 +00002633
2634
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002635static int
2636compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2637{
2638 switch (e->kind) {
2639 case UnaryOp_kind:
2640 if (e->v.UnaryOp.op == Not)
2641 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2642 /* fallback to general implementation */
2643 break;
2644 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002645 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002646 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2647 assert(n >= 0);
2648 int cond2 = e->v.BoolOp.op == Or;
2649 basicblock *next2 = next;
2650 if (!cond2 != !cond) {
2651 next2 = compiler_new_block(c);
2652 if (next2 == NULL)
2653 return 0;
2654 }
2655 for (i = 0; i < n; ++i) {
2656 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2657 return 0;
2658 }
2659 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2660 return 0;
2661 if (next2 != next)
2662 compiler_use_next_block(c, next2);
2663 return 1;
2664 }
2665 case IfExp_kind: {
2666 basicblock *end, *next2;
2667 end = compiler_new_block(c);
2668 if (end == NULL)
2669 return 0;
2670 next2 = compiler_new_block(c);
2671 if (next2 == NULL)
2672 return 0;
2673 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2674 return 0;
2675 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2676 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002677 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002678 compiler_use_next_block(c, next2);
2679 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2680 return 0;
2681 compiler_use_next_block(c, end);
2682 return 1;
2683 }
2684 case Compare_kind: {
2685 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2686 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002687 if (!check_compare(c, e)) {
2688 return 0;
2689 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002690 basicblock *cleanup = compiler_new_block(c);
2691 if (cleanup == NULL)
2692 return 0;
2693 VISIT(c, expr, e->v.Compare.left);
2694 for (i = 0; i < n; i++) {
2695 VISIT(c, expr,
2696 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2697 ADDOP(c, DUP_TOP);
2698 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002699 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002700 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002701 NEXT_BLOCK(c);
2702 }
2703 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002704 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002705 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002706 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002707 basicblock *end = compiler_new_block(c);
2708 if (end == NULL)
2709 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002710 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002711 compiler_use_next_block(c, cleanup);
2712 ADDOP(c, POP_TOP);
2713 if (!cond) {
Mark Shannon127dde52021-01-04 18:06:55 +00002714 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002715 }
2716 compiler_use_next_block(c, end);
2717 return 1;
2718 }
2719 /* fallback to general implementation */
2720 break;
2721 }
2722 default:
2723 /* fallback to general implementation */
2724 break;
2725 }
2726
2727 /* general implementation */
2728 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002729 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002730 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002731 return 1;
2732}
2733
2734static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002735compiler_ifexp(struct compiler *c, expr_ty e)
2736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 basicblock *end, *next;
2738
2739 assert(e->kind == IfExp_kind);
2740 end = compiler_new_block(c);
2741 if (end == NULL)
2742 return 0;
2743 next = compiler_new_block(c);
2744 if (next == NULL)
2745 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002746 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2747 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon127dde52021-01-04 18:06:55 +00002749 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 compiler_use_next_block(c, next);
2751 VISIT(c, expr, e->v.IfExp.orelse);
2752 compiler_use_next_block(c, end);
2753 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002754}
2755
2756static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002757compiler_lambda(struct compiler *c, expr_ty e)
2758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002760 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002762 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 arguments_ty args = e->v.Lambda.args;
2764 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002765
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002766 if (!compiler_check_debug_args(c, args))
2767 return 0;
2768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 if (!name) {
2770 name = PyUnicode_InternFromString("<lambda>");
2771 if (!name)
2772 return 0;
2773 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002775 funcflags = compiler_default_arguments(c, args);
2776 if (funcflags == -1) {
2777 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002779
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002780 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002781 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 /* Make None the first constant, so the lambda can't have a
2785 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002786 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002790 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2792 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2793 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002794 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 }
2796 else {
2797 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002798 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002800 qualname = c->u->u_qualname;
2801 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 compiler_exit_scope(c);
Pablo Galindo7fdab832021-01-29 22:40:59 +00002803 if (co == NULL) {
2804 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 return 0;
Pablo Galindo7fdab832021-01-29 22:40:59 +00002806 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002807
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002808 if (!compiler_make_closure(c, co, funcflags, qualname)) {
2809 Py_DECREF(qualname);
2810 Py_DECREF(co);
2811 return 0;
2812 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002813 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002814 Py_DECREF(co);
2815
2816 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817}
2818
2819static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820compiler_if(struct compiler *c, stmt_ty s)
2821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 assert(s->kind == If_kind);
2824 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002825 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002827 }
2828 if (asdl_seq_LEN(s->v.If.orelse)) {
2829 next = compiler_new_block(c);
2830 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002831 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002832 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002833 }
2834 else {
2835 next = end;
2836 }
2837 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2838 return 0;
2839 }
2840 VISIT_SEQ(c, stmt, s->v.If.body);
2841 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon127dde52021-01-04 18:06:55 +00002842 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Mark Shannon8473cf82020-12-15 11:07:50 +00002843 compiler_use_next_block(c, next);
2844 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 }
2846 compiler_use_next_block(c, end);
2847 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848}
2849
2850static int
2851compiler_for(struct compiler *c, stmt_ty s)
2852{
Mark Shannon5977a792020-12-02 13:31:40 +00002853 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002856 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 cleanup = compiler_new_block(c);
2858 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002859 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002861 }
2862 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 VISIT(c, expr, s->v.For.iter);
2866 ADDOP(c, GET_ITER);
2867 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002868 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002869 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 VISIT(c, expr, s->v.For.target);
2871 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002872 /* Mark jump as artificial */
2873 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002874 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002876
2877 compiler_pop_fblock(c, FOR_LOOP, start);
2878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 VISIT_SEQ(c, stmt, s->v.For.orelse);
2880 compiler_use_next_block(c, end);
2881 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882}
2883
Yury Selivanov75445082015-05-11 22:57:16 -04002884
2885static int
2886compiler_async_for(struct compiler *c, stmt_ty s)
2887{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002888 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002889 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002890 c->u->u_ste->ste_coroutine = 1;
2891 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002892 return compiler_error(c, "'async for' outside async function");
2893 }
2894
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002895 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002896 except = compiler_new_block(c);
2897 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002898
Mark Shannonfee55262019-11-21 09:11:43 +00002899 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002900 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002901 }
Yury Selivanov75445082015-05-11 22:57:16 -04002902 VISIT(c, expr, s->v.AsyncFor.iter);
2903 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002904
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002905 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002906 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002907 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002908 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002909 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002910 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002911 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002912 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002913 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002914 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002915
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002916 /* Success block for __anext__ */
2917 VISIT(c, expr, s->v.AsyncFor.target);
2918 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002919 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002920
2921 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002922
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002923 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002924 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002925
2926 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002927 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002928
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002929 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002930 VISIT_SEQ(c, stmt, s->v.For.orelse);
2931
2932 compiler_use_next_block(c, end);
2933
2934 return 1;
2935}
2936
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937static int
2938compiler_while(struct compiler *c, stmt_ty s)
2939{
Mark Shannon266b4622020-11-17 19:30:14 +00002940 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002942 body = compiler_new_block(c);
2943 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002945 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002946 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002949 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002952 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2953 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002954 }
2955
2956 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002957 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002958 SET_LOC(c, s);
2959 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2960 return 0;
2961 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002963 compiler_pop_fblock(c, WHILE_LOOP, loop);
2964
Mark Shannon266b4622020-11-17 19:30:14 +00002965 compiler_use_next_block(c, anchor);
2966 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002968 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972}
2973
2974static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002975compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002977 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002978 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002979 if (c->u->u_ste->ste_type != FunctionBlock)
2980 return compiler_error(c, "'return' outside function");
2981 if (s->v.Return.value != NULL &&
2982 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2983 {
2984 return compiler_error(
2985 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002987 if (preserve_tos) {
2988 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002989 } else {
Mark Shannoncea05852021-06-03 19:57:31 +01002990 /* Emit instruction with line number for return value */
Mark Shannon5274b682020-12-16 13:07:01 +00002991 if (s->v.Return.value != NULL) {
2992 SET_LOC(c, s->v.Return.value);
2993 ADDOP(c, NOP);
2994 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002995 }
Mark Shannoncea05852021-06-03 19:57:31 +01002996 if (s->v.Return.value == NULL || s->v.Return.value->lineno != s->lineno) {
2997 SET_LOC(c, s);
2998 ADDOP(c, NOP);
2999 }
3000
Mark Shannonfee55262019-11-21 09:11:43 +00003001 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
3002 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003003 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003004 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003005 }
3006 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00003007 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003008 }
3009 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00003010 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013}
3014
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003015static int
3016compiler_break(struct compiler *c)
3017{
Mark Shannonfee55262019-11-21 09:11:43 +00003018 struct fblockinfo *loop = NULL;
Mark Shannoncea05852021-06-03 19:57:31 +01003019 /* Emit instruction with line number */
3020 ADDOP(c, NOP);
Mark Shannonfee55262019-11-21 09:11:43 +00003021 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
3022 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003023 }
Mark Shannonfee55262019-11-21 09:11:43 +00003024 if (loop == NULL) {
3025 return compiler_error(c, "'break' outside loop");
3026 }
3027 if (!compiler_unwind_fblock(c, loop, 0)) {
3028 return 0;
3029 }
Mark Shannon582aaf12020-08-04 17:30:11 +01003030 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00003031 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00003032 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003033}
3034
3035static int
3036compiler_continue(struct compiler *c)
3037{
Mark Shannonfee55262019-11-21 09:11:43 +00003038 struct fblockinfo *loop = NULL;
Mark Shannoncea05852021-06-03 19:57:31 +01003039 /* Emit instruction with line number */
3040 ADDOP(c, NOP);
Mark Shannonfee55262019-11-21 09:11:43 +00003041 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
3042 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003043 }
Mark Shannonfee55262019-11-21 09:11:43 +00003044 if (loop == NULL) {
3045 return compiler_error(c, "'continue' not properly in loop");
3046 }
Mark Shannon582aaf12020-08-04 17:30:11 +01003047 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00003048 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00003049 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003050}
3051
3052
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054
3055 SETUP_FINALLY L
3056 <code for body>
3057 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00003058 <code for finalbody>
3059 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003060 L:
3061 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00003062 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003064 The special instructions use the block stack. Each block
3065 stack entry contains the instruction that created it (here
3066 SETUP_FINALLY), the level of the value stack at the time the
3067 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003069 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 Pushes the current value stack level and the label
3071 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003072 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003073 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003075 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003076 when a SETUP_FINALLY entry is found, the raised and the caught
3077 exceptions are pushed onto the value stack (and the exception
3078 condition is cleared), and the interpreter jumps to the label
3079 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003080*/
3081
3082static int
3083compiler_try_finally(struct compiler *c, stmt_ty s)
3084{
Mark Shannonfee55262019-11-21 09:11:43 +00003085 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 body = compiler_new_block(c);
3088 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00003089 exit = compiler_new_block(c);
3090 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003091 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003092
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003093 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01003094 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003096 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003098 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
3099 if (!compiler_try_except(c, s))
3100 return 0;
3101 }
3102 else {
3103 VISIT_SEQ(c, stmt, s->v.Try.body);
3104 }
Mark Shannon3bd60352021-01-13 12:05:43 +00003105 ADDOP_NOLINE(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00003106 compiler_pop_fblock(c, FINALLY_TRY, body);
3107 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon127dde52021-01-04 18:06:55 +00003108 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00003109 /* `finally` block */
3110 compiler_use_next_block(c, end);
3111 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
3112 return 0;
3113 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3114 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00003115 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00003116 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003118}
3119
3120/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003121 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003122 (The contents of the value stack is shown in [], with the top
3123 at the right; 'tb' is trace-back info, 'val' the exception's
3124 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125
3126 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003127 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 [] <code for S>
3129 [] POP_BLOCK
3130 [] JUMP_FORWARD L0
3131
3132 [tb, val, exc] L1: DUP )
3133 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003134 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 [tb, val, exc] POP
3136 [tb, val] <assign to V1> (or POP if no V1)
3137 [tb] POP
3138 [] <code for S1>
3139 JUMP_FORWARD L0
3140
3141 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003142 .............................etc.......................
3143
Mark Shannonfee55262019-11-21 09:11:43 +00003144 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145
3146 [] L0: <next statement>
3147
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003148 Of course, parts are not generated if Vi or Ei is not present.
3149*/
3150static int
3151compiler_try_except(struct compiler *c, stmt_ty s)
3152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003154 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 body = compiler_new_block(c);
3157 except = compiler_new_block(c);
3158 orelse = compiler_new_block(c);
3159 end = compiler_new_block(c);
3160 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3161 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003162 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003164 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003166 VISIT_SEQ(c, stmt, s->v.Try.body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003167 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon3bd60352021-01-13 12:05:43 +00003168 ADDOP_NOLINE(c, POP_BLOCK);
3169 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003170 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003172 /* Runtime will push a block here, so we need to account for that */
3173 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3174 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 for (i = 0; i < n; i++) {
3176 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003177 s->v.Try.handlers, i);
Mark Shannon8d4b1842021-05-06 13:38:50 +01003178 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 if (!handler->v.ExceptHandler.type && i < n-1)
3180 return compiler_error(c, "default 'except:' must be last");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 except = compiler_new_block(c);
3182 if (except == NULL)
3183 return 0;
3184 if (handler->v.ExceptHandler.type) {
3185 ADDOP(c, DUP_TOP);
3186 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003187 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003188 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 }
3190 ADDOP(c, POP_TOP);
3191 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003192 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003193
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003194 cleanup_end = compiler_new_block(c);
3195 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003196 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003197 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003198 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003199
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003200 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3201 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003203 /*
3204 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003205 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003206 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003207 try:
3208 # body
3209 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003210 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003211 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003212 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003214 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003215 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003216 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003217 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003218 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003220 /* second # body */
3221 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003222 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003223 ADDOP(c, POP_BLOCK);
3224 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003225 /* name = None; del name; # Mark as artificial */
3226 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003227 ADDOP_LOAD_CONST(c, Py_None);
3228 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3229 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003230 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231
Mark Shannonfee55262019-11-21 09:11:43 +00003232 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003233 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234
Mark Shannon877df852020-11-12 09:43:29 +00003235 /* name = None; del name; # Mark as artificial */
3236 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003237 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003238 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003239 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240
Mark Shannonbf353f32020-12-17 13:55:28 +00003241 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 }
3243 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003244 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003246 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003247 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003248 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249
Guido van Rossumb940e112007-01-10 16:19:56 +00003250 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003251 ADDOP(c, POP_TOP);
3252 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003253 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003254 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003256 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannon127dde52021-01-04 18:06:55 +00003257 /* name = None; del name; # Mark as artificial */
3258 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003259 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003260 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 compiler_use_next_block(c, except);
3263 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003264 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003265 /* Mark as artificial */
3266 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003267 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003269 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 compiler_use_next_block(c, end);
3271 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003272}
3273
3274static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003275compiler_try(struct compiler *c, stmt_ty s) {
3276 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3277 return compiler_try_finally(c, s);
3278 else
3279 return compiler_try_except(c, s);
3280}
3281
3282
3283static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284compiler_import_as(struct compiler *c, identifier name, identifier asname)
3285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 /* The IMPORT_NAME opcode was already generated. This function
3287 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003290 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003292 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3293 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003294 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003295 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003296 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003298 while (1) {
3299 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003301 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003302 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003303 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003304 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003305 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003306 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003307 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003308 if (dot == -1) {
3309 break;
3310 }
3311 ADDOP(c, ROT_TWO);
3312 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003314 if (!compiler_nameop(c, asname, Store)) {
3315 return 0;
3316 }
3317 ADDOP(c, POP_TOP);
3318 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 }
3320 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321}
3322
3323static int
3324compiler_import(struct compiler *c, stmt_ty s)
3325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 /* The Import node stores a module name like a.b.c as a single
3327 string. This is convenient for all cases except
3328 import a.b.c as d
3329 where we need to parse that string to extract the individual
3330 module names.
3331 XXX Perhaps change the representation to make this case simpler?
3332 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003333 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003334
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003335 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 for (i = 0; i < n; i++) {
3337 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3338 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003340 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003341 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 if (alias->asname) {
3345 r = compiler_import_as(c, alias->name, alias->asname);
3346 if (!r)
3347 return r;
3348 }
3349 else {
3350 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003351 Py_ssize_t dot = PyUnicode_FindChar(
3352 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003353 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003354 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003355 if (tmp == NULL)
3356 return 0;
3357 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003358 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003359 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 Py_DECREF(tmp);
3361 }
3362 if (!r)
3363 return r;
3364 }
3365 }
3366 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003367}
3368
3369static int
3370compiler_from_import(struct compiler *c, stmt_ty s)
3371{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003372 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003373 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003374 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 if (!empty_string) {
3377 empty_string = PyUnicode_FromString("");
3378 if (!empty_string)
3379 return 0;
3380 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003381
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003382 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003383
3384 names = PyTuple_New(n);
3385 if (!names)
3386 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 /* build up the names */
3389 for (i = 0; i < n; i++) {
3390 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3391 Py_INCREF(alias->name);
3392 PyTuple_SET_ITEM(names, i, alias->name);
3393 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003395 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003396 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003397 Py_DECREF(names);
3398 return compiler_error(c, "from __future__ imports must occur "
3399 "at the beginning of the file");
3400 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003401 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 if (s->v.ImportFrom.module) {
3404 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3405 }
3406 else {
3407 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3408 }
3409 for (i = 0; i < n; i++) {
3410 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3411 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003412
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003413 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 assert(n == 1);
3415 ADDOP(c, IMPORT_STAR);
3416 return 1;
3417 }
3418
3419 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3420 store_name = alias->name;
3421 if (alias->asname)
3422 store_name = alias->asname;
3423
3424 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 return 0;
3426 }
3427 }
3428 /* remove imported module */
3429 ADDOP(c, POP_TOP);
3430 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003431}
3432
3433static int
3434compiler_assert(struct compiler *c, stmt_ty s)
3435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003437
tsukasa-aua8ef4572021-03-16 22:14:41 +11003438 /* Always emit a warning if the test is a non-zero length tuple */
3439 if ((s->v.Assert.test->kind == Tuple_kind &&
3440 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) ||
3441 (s->v.Assert.test->kind == Constant_kind &&
3442 PyTuple_Check(s->v.Assert.test->v.Constant.value) &&
3443 PyTuple_Size(s->v.Assert.test->v.Constant.value) > 0))
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003444 {
3445 if (!compiler_warn(c, "assertion is always true, "
3446 "perhaps remove parentheses?"))
3447 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003448 return 0;
3449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003450 }
tsukasa-aua8ef4572021-03-16 22:14:41 +11003451 if (c->c_optimize)
3452 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003453 end = compiler_new_block(c);
3454 if (end == NULL)
3455 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003456 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3457 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003458 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 if (s->v.Assert.msg) {
3460 VISIT(c, expr, s->v.Assert.msg);
3461 ADDOP_I(c, CALL_FUNCTION, 1);
3462 }
3463 ADDOP_I(c, RAISE_VARARGS, 1);
3464 compiler_use_next_block(c, end);
3465 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466}
3467
3468static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003469compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3470{
3471 if (c->c_interactive && c->c_nestlevel <= 1) {
3472 VISIT(c, expr, value);
3473 ADDOP(c, PRINT_EXPR);
3474 return 1;
3475 }
3476
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003477 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003478 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003479 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003480 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003481 }
3482
3483 VISIT(c, expr, value);
Mark Shannonc5440932021-03-15 14:24:25 +00003484 /* Mark POP_TOP as artificial */
3485 c->u->u_lineno = -1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003486 ADDOP(c, POP_TOP);
3487 return 1;
3488}
3489
3490static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003491compiler_visit_stmt(struct compiler *c, stmt_ty s)
3492{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003493 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003496 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 switch (s->kind) {
3499 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003500 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003501 case ClassDef_kind:
3502 return compiler_class(c, s);
3503 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003504 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 case Delete_kind:
3506 VISIT_SEQ(c, expr, s->v.Delete.targets)
3507 break;
3508 case Assign_kind:
3509 n = asdl_seq_LEN(s->v.Assign.targets);
3510 VISIT(c, expr, s->v.Assign.value);
3511 for (i = 0; i < n; i++) {
3512 if (i < n - 1)
3513 ADDOP(c, DUP_TOP);
3514 VISIT(c, expr,
3515 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3516 }
3517 break;
3518 case AugAssign_kind:
3519 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003520 case AnnAssign_kind:
3521 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 case For_kind:
3523 return compiler_for(c, s);
3524 case While_kind:
3525 return compiler_while(c, s);
3526 case If_kind:
3527 return compiler_if(c, s);
Brandt Bucher145bf262021-02-26 14:51:55 -08003528 case Match_kind:
3529 return compiler_match(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003530 case Raise_kind:
3531 n = 0;
3532 if (s->v.Raise.exc) {
3533 VISIT(c, expr, s->v.Raise.exc);
3534 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003535 if (s->v.Raise.cause) {
3536 VISIT(c, expr, s->v.Raise.cause);
3537 n++;
3538 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003540 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003541 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003543 case Try_kind:
3544 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 case Assert_kind:
3546 return compiler_assert(c, s);
3547 case Import_kind:
3548 return compiler_import(c, s);
3549 case ImportFrom_kind:
3550 return compiler_from_import(c, s);
3551 case Global_kind:
3552 case Nonlocal_kind:
3553 break;
3554 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003555 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003556 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003557 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003558 break;
3559 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003560 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 case Continue_kind:
3562 return compiler_continue(c);
3563 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003564 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003565 case AsyncFunctionDef_kind:
3566 return compiler_function(c, s, 1);
3567 case AsyncWith_kind:
3568 return compiler_async_with(c, s, 0);
3569 case AsyncFor_kind:
3570 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 }
Yury Selivanov75445082015-05-11 22:57:16 -04003572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574}
3575
3576static int
3577unaryop(unaryop_ty op)
3578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003579 switch (op) {
3580 case Invert:
3581 return UNARY_INVERT;
3582 case Not:
3583 return UNARY_NOT;
3584 case UAdd:
3585 return UNARY_POSITIVE;
3586 case USub:
3587 return UNARY_NEGATIVE;
3588 default:
3589 PyErr_Format(PyExc_SystemError,
3590 "unary op %d should not be possible", op);
3591 return 0;
3592 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003593}
3594
3595static int
Andy Lester76d58772020-03-10 21:18:12 -05003596binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 switch (op) {
3599 case Add:
3600 return BINARY_ADD;
3601 case Sub:
3602 return BINARY_SUBTRACT;
3603 case Mult:
3604 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003605 case MatMult:
3606 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 case Div:
3608 return BINARY_TRUE_DIVIDE;
3609 case Mod:
3610 return BINARY_MODULO;
3611 case Pow:
3612 return BINARY_POWER;
3613 case LShift:
3614 return BINARY_LSHIFT;
3615 case RShift:
3616 return BINARY_RSHIFT;
3617 case BitOr:
3618 return BINARY_OR;
3619 case BitXor:
3620 return BINARY_XOR;
3621 case BitAnd:
3622 return BINARY_AND;
3623 case FloorDiv:
3624 return BINARY_FLOOR_DIVIDE;
3625 default:
3626 PyErr_Format(PyExc_SystemError,
3627 "binary op %d should not be possible", op);
3628 return 0;
3629 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630}
3631
3632static int
Andy Lester76d58772020-03-10 21:18:12 -05003633inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 switch (op) {
3636 case Add:
3637 return INPLACE_ADD;
3638 case Sub:
3639 return INPLACE_SUBTRACT;
3640 case Mult:
3641 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003642 case MatMult:
3643 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 case Div:
3645 return INPLACE_TRUE_DIVIDE;
3646 case Mod:
3647 return INPLACE_MODULO;
3648 case Pow:
3649 return INPLACE_POWER;
3650 case LShift:
3651 return INPLACE_LSHIFT;
3652 case RShift:
3653 return INPLACE_RSHIFT;
3654 case BitOr:
3655 return INPLACE_OR;
3656 case BitXor:
3657 return INPLACE_XOR;
3658 case BitAnd:
3659 return INPLACE_AND;
3660 case FloorDiv:
3661 return INPLACE_FLOOR_DIVIDE;
3662 default:
3663 PyErr_Format(PyExc_SystemError,
3664 "inplace binary op %d should not be possible", op);
3665 return 0;
3666 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003667}
3668
3669static int
3670compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3671{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003672 int op, scope;
3673 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003674 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003676 PyObject *dict = c->u->u_names;
3677 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003678
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003679 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3680 !_PyUnicode_EqualToASCIIString(name, "True") &&
3681 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003682
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003683 if (forbidden_name(c, name, ctx))
3684 return 0;
3685
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003686 mangled = _Py_Mangle(c->u->u_private, name);
3687 if (!mangled)
3688 return 0;
3689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003690 op = 0;
3691 optype = OP_NAME;
Victor Stinner28ad12f2021-03-19 12:41:49 +01003692 scope = _PyST_GetScope(c->u->u_ste, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003693 switch (scope) {
3694 case FREE:
3695 dict = c->u->u_freevars;
3696 optype = OP_DEREF;
3697 break;
3698 case CELL:
3699 dict = c->u->u_cellvars;
3700 optype = OP_DEREF;
3701 break;
3702 case LOCAL:
3703 if (c->u->u_ste->ste_type == FunctionBlock)
3704 optype = OP_FAST;
3705 break;
3706 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003707 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003708 optype = OP_GLOBAL;
3709 break;
3710 case GLOBAL_EXPLICIT:
3711 optype = OP_GLOBAL;
3712 break;
3713 default:
3714 /* scope can be 0 */
3715 break;
3716 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003718 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003719 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003721 switch (optype) {
3722 case OP_DEREF:
3723 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003724 case Load:
3725 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3726 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003727 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003728 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003729 }
3730 break;
3731 case OP_FAST:
3732 switch (ctx) {
3733 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003734 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003735 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003736 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003737 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003738 return 1;
3739 case OP_GLOBAL:
3740 switch (ctx) {
3741 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003742 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003743 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003744 }
3745 break;
3746 case OP_NAME:
3747 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003748 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003749 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003750 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003751 }
3752 break;
3753 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003755 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003756 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003757 Py_DECREF(mangled);
3758 if (arg < 0)
3759 return 0;
3760 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003761}
3762
3763static int
3764compiler_boolop(struct compiler *c, expr_ty e)
3765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003766 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003767 int jumpi;
3768 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003769 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003771 assert(e->kind == BoolOp_kind);
3772 if (e->v.BoolOp.op == And)
3773 jumpi = JUMP_IF_FALSE_OR_POP;
3774 else
3775 jumpi = JUMP_IF_TRUE_OR_POP;
3776 end = compiler_new_block(c);
3777 if (end == NULL)
3778 return 0;
3779 s = e->v.BoolOp.values;
3780 n = asdl_seq_LEN(s) - 1;
3781 assert(n >= 0);
3782 for (i = 0; i < n; ++i) {
3783 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003784 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003785 basicblock *next = compiler_new_block(c);
3786 if (next == NULL) {
3787 return 0;
3788 }
3789 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003790 }
3791 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3792 compiler_use_next_block(c, end);
3793 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794}
3795
3796static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003797starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003798 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003799{
3800 Py_ssize_t n = asdl_seq_LEN(elts);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003801 if (n > 2 && are_all_items_const(elts, 0, n)) {
3802 PyObject *folded = PyTuple_New(n);
3803 if (folded == NULL) {
3804 return 0;
3805 }
3806 PyObject *val;
Mark Shannon11e0b292021-04-15 14:28:56 +01003807 for (Py_ssize_t i = 0; i < n; i++) {
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003808 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3809 Py_INCREF(val);
3810 PyTuple_SET_ITEM(folded, i, val);
3811 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003812 if (tuple) {
3813 ADDOP_LOAD_CONST_NEW(c, folded);
3814 } else {
3815 if (add == SET_ADD) {
3816 Py_SETREF(folded, PyFrozenSet_New(folded));
3817 if (folded == NULL) {
3818 return 0;
3819 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003820 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003821 ADDOP_I(c, build, pushed);
3822 ADDOP_LOAD_CONST_NEW(c, folded);
3823 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003824 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003825 return 1;
3826 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003827
Mark Shannon11e0b292021-04-15 14:28:56 +01003828 int big = n+pushed > STACK_USE_GUIDELINE;
3829 int seen_star = 0;
3830 for (Py_ssize_t i = 0; i < n; i++) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003831 expr_ty elt = asdl_seq_GET(elts, i);
3832 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003833 seen_star = 1;
3834 }
3835 }
Mark Shannon11e0b292021-04-15 14:28:56 +01003836 if (!seen_star && !big) {
3837 for (Py_ssize_t i = 0; i < n; i++) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003838 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003839 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003840 }
3841 if (tuple) {
3842 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3843 } else {
3844 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003845 }
Mark Shannon11e0b292021-04-15 14:28:56 +01003846 return 1;
3847 }
3848 int sequence_built = 0;
3849 if (big) {
3850 ADDOP_I(c, build, pushed);
3851 sequence_built = 1;
3852 }
3853 for (Py_ssize_t i = 0; i < n; i++) {
3854 expr_ty elt = asdl_seq_GET(elts, i);
3855 if (elt->kind == Starred_kind) {
3856 if (sequence_built == 0) {
3857 ADDOP_I(c, build, i+pushed);
3858 sequence_built = 1;
3859 }
3860 VISIT(c, expr, elt->v.Starred.value);
3861 ADDOP_I(c, extend, 1);
3862 }
3863 else {
3864 VISIT(c, expr, elt);
3865 if (sequence_built) {
3866 ADDOP_I(c, add, 1);
3867 }
3868 }
3869 }
3870 assert(sequence_built);
3871 if (tuple) {
3872 ADDOP(c, LIST_TO_TUPLE);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003873 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003874 return 1;
3875}
3876
3877static int
Brandt Bucher145bf262021-02-26 14:51:55 -08003878unpack_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003879{
3880 Py_ssize_t n = asdl_seq_LEN(elts);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003881 int seen_star = 0;
Brandt Bucher145bf262021-02-26 14:51:55 -08003882 for (Py_ssize_t i = 0; i < n; i++) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003883 expr_ty elt = asdl_seq_GET(elts, i);
3884 if (elt->kind == Starred_kind && !seen_star) {
3885 if ((i >= (1 << 8)) ||
3886 (n-i-1 >= (INT_MAX >> 8)))
3887 return compiler_error(c,
3888 "too many expressions in "
3889 "star-unpacking assignment");
3890 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3891 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003892 }
3893 else if (elt->kind == Starred_kind) {
3894 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003895 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003896 }
3897 }
3898 if (!seen_star) {
3899 ADDOP_I(c, UNPACK_SEQUENCE, n);
3900 }
Brandt Bucher145bf262021-02-26 14:51:55 -08003901 return 1;
3902}
3903
3904static int
3905assignment_helper(struct compiler *c, asdl_expr_seq *elts)
3906{
3907 Py_ssize_t n = asdl_seq_LEN(elts);
3908 RETURN_IF_FALSE(unpack_helper(c, elts));
3909 for (Py_ssize_t i = 0; i < n; i++) {
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003910 expr_ty elt = asdl_seq_GET(elts, i);
3911 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3912 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003913 return 1;
3914}
3915
3916static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003917compiler_list(struct compiler *c, expr_ty e)
3918{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003919 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003920 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003921 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003922 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003923 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003924 return starunpack_helper(c, elts, 0, BUILD_LIST,
3925 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003927 else
3928 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930}
3931
3932static int
3933compiler_tuple(struct compiler *c, expr_ty e)
3934{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003935 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003936 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003937 return assignment_helper(c, elts);
3938 }
3939 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003940 return starunpack_helper(c, elts, 0, BUILD_LIST,
3941 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003942 }
3943 else
3944 VISIT_SEQ(c, expr, elts);
3945 return 1;
3946}
3947
3948static int
3949compiler_set(struct compiler *c, expr_ty e)
3950{
Mark Shannon13bc1392020-01-23 09:25:17 +00003951 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3952 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003953}
3954
3955static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003956are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003957{
3958 Py_ssize_t i;
3959 for (i = begin; i < end; i++) {
3960 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003961 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003962 return 0;
3963 }
3964 return 1;
3965}
3966
3967static int
3968compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3969{
3970 Py_ssize_t i, n = end - begin;
3971 PyObject *keys, *key;
Mark Shannon11e0b292021-04-15 14:28:56 +01003972 int big = n*2 > STACK_USE_GUIDELINE;
3973 if (n > 1 && !big && are_all_items_const(e->v.Dict.keys, begin, end)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003974 for (i = begin; i < end; i++) {
3975 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3976 }
3977 keys = PyTuple_New(n);
3978 if (keys == NULL) {
3979 return 0;
3980 }
3981 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003982 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003983 Py_INCREF(key);
3984 PyTuple_SET_ITEM(keys, i - begin, key);
3985 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003986 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003987 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
Mark Shannon11e0b292021-04-15 14:28:56 +01003988 return 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003989 }
Mark Shannon11e0b292021-04-15 14:28:56 +01003990 if (big) {
3991 ADDOP_I(c, BUILD_MAP, 0);
3992 }
3993 for (i = begin; i < end; i++) {
3994 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3995 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3996 if (big) {
3997 ADDOP_I(c, MAP_ADD, 1);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003998 }
Mark Shannon11e0b292021-04-15 14:28:56 +01003999 }
4000 if (!big) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004001 ADDOP_I(c, BUILD_MAP, n);
4002 }
4003 return 1;
4004}
4005
4006static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004007compiler_dict(struct compiler *c, expr_ty e)
4008{
Victor Stinner976bb402016-03-23 11:36:19 +01004009 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004010 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004011 int is_unpacking = 0;
4012 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004013 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004014 elements = 0;
4015 for (i = 0; i < n; i++) {
4016 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004017 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004018 if (elements) {
4019 if (!compiler_subdict(c, e, i - elements, i)) {
4020 return 0;
4021 }
4022 if (have_dict) {
4023 ADDOP_I(c, DICT_UPDATE, 1);
4024 }
4025 have_dict = 1;
4026 elements = 0;
4027 }
4028 if (have_dict == 0) {
4029 ADDOP_I(c, BUILD_MAP, 0);
4030 have_dict = 1;
4031 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004032 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00004033 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004034 }
4035 else {
Mark Shannon11e0b292021-04-15 14:28:56 +01004036 if (elements*2 > STACK_USE_GUIDELINE) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01004037 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004038 return 0;
4039 }
4040 if (have_dict) {
4041 ADDOP_I(c, DICT_UPDATE, 1);
4042 }
4043 have_dict = 1;
4044 elements = 0;
4045 }
4046 else {
4047 elements++;
4048 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004049 }
4050 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004051 if (elements) {
4052 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004053 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004054 }
4055 if (have_dict) {
4056 ADDOP_I(c, DICT_UPDATE, 1);
4057 }
4058 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004059 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004060 if (!have_dict) {
4061 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004062 }
4063 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004064}
4065
4066static int
4067compiler_compare(struct compiler *c, expr_ty e)
4068{
Victor Stinnerad9a0662013-11-19 22:23:20 +01004069 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004070
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02004071 if (!check_compare(c, e)) {
4072 return 0;
4073 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004074 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02004075 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
4076 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
4077 if (n == 0) {
4078 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00004079 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02004080 }
4081 else {
4082 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004083 if (cleanup == NULL)
4084 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02004085 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004086 VISIT(c, expr,
4087 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02004088 ADDOP(c, DUP_TOP);
4089 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00004090 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01004091 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02004092 NEXT_BLOCK(c);
4093 }
4094 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00004095 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004096 basicblock *end = compiler_new_block(c);
4097 if (end == NULL)
4098 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00004099 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004100 compiler_use_next_block(c, cleanup);
4101 ADDOP(c, ROT_TWO);
4102 ADDOP(c, POP_TOP);
4103 compiler_use_next_block(c, end);
4104 }
4105 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004106}
4107
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004108static PyTypeObject *
4109infer_type(expr_ty e)
4110{
4111 switch (e->kind) {
4112 case Tuple_kind:
4113 return &PyTuple_Type;
4114 case List_kind:
4115 case ListComp_kind:
4116 return &PyList_Type;
4117 case Dict_kind:
4118 case DictComp_kind:
4119 return &PyDict_Type;
4120 case Set_kind:
4121 case SetComp_kind:
4122 return &PySet_Type;
4123 case GeneratorExp_kind:
4124 return &PyGen_Type;
4125 case Lambda_kind:
4126 return &PyFunction_Type;
4127 case JoinedStr_kind:
4128 case FormattedValue_kind:
4129 return &PyUnicode_Type;
4130 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01004131 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004132 default:
4133 return NULL;
4134 }
4135}
4136
4137static int
4138check_caller(struct compiler *c, expr_ty e)
4139{
4140 switch (e->kind) {
4141 case Constant_kind:
4142 case Tuple_kind:
4143 case List_kind:
4144 case ListComp_kind:
4145 case Dict_kind:
4146 case DictComp_kind:
4147 case Set_kind:
4148 case SetComp_kind:
4149 case GeneratorExp_kind:
4150 case JoinedStr_kind:
4151 case FormattedValue_kind:
4152 return compiler_warn(c, "'%.200s' object is not callable; "
4153 "perhaps you missed a comma?",
4154 infer_type(e)->tp_name);
4155 default:
4156 return 1;
4157 }
4158}
4159
4160static int
4161check_subscripter(struct compiler *c, expr_ty e)
4162{
4163 PyObject *v;
4164
4165 switch (e->kind) {
4166 case Constant_kind:
4167 v = e->v.Constant.value;
4168 if (!(v == Py_None || v == Py_Ellipsis ||
4169 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4170 PyAnySet_Check(v)))
4171 {
4172 return 1;
4173 }
4174 /* fall through */
4175 case Set_kind:
4176 case SetComp_kind:
4177 case GeneratorExp_kind:
4178 case Lambda_kind:
4179 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4180 "perhaps you missed a comma?",
4181 infer_type(e)->tp_name);
4182 default:
4183 return 1;
4184 }
4185}
4186
4187static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004188check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004189{
4190 PyObject *v;
4191
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004192 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004193 if (index_type == NULL
4194 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4195 || index_type == &PySlice_Type) {
4196 return 1;
4197 }
4198
4199 switch (e->kind) {
4200 case Constant_kind:
4201 v = e->v.Constant.value;
4202 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4203 return 1;
4204 }
4205 /* fall through */
4206 case Tuple_kind:
4207 case List_kind:
4208 case ListComp_kind:
4209 case JoinedStr_kind:
4210 case FormattedValue_kind:
4211 return compiler_warn(c, "%.200s indices must be integers or slices, "
4212 "not %.200s; "
4213 "perhaps you missed a comma?",
4214 infer_type(e)->tp_name,
4215 index_type->tp_name);
4216 default:
4217 return 1;
4218 }
4219}
4220
Zackery Spytz97f5de02019-03-22 01:30:32 -06004221// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004222static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004223maybe_optimize_method_call(struct compiler *c, expr_ty e)
4224{
4225 Py_ssize_t argsl, i;
4226 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004227 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004228
4229 /* Check that the call node is an attribute access, and that
4230 the call doesn't have keyword parameters. */
4231 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
Mark Shannon11e0b292021-04-15 14:28:56 +01004232 asdl_seq_LEN(e->v.Call.keywords)) {
Yury Selivanovf2392132016-12-13 19:03:51 -05004233 return -1;
Mark Shannon11e0b292021-04-15 14:28:56 +01004234 }
4235 /* Check that there aren't too many arguments */
Yury Selivanovf2392132016-12-13 19:03:51 -05004236 argsl = asdl_seq_LEN(args);
Mark Shannon11e0b292021-04-15 14:28:56 +01004237 if (argsl >= STACK_USE_GUIDELINE) {
4238 return -1;
4239 }
4240 /* Check that there are no *varargs types of arguments. */
Yury Selivanovf2392132016-12-13 19:03:51 -05004241 for (i = 0; i < argsl; i++) {
4242 expr_ty elt = asdl_seq_GET(args, i);
4243 if (elt->kind == Starred_kind) {
4244 return -1;
4245 }
4246 }
4247
4248 /* Alright, we can optimize the code. */
4249 VISIT(c, expr, meth->v.Attribute.value);
Mark Shannond48848c2021-03-14 18:01:30 +00004250 int old_lineno = c->u->u_lineno;
4251 c->u->u_lineno = meth->end_lineno;
Yury Selivanovf2392132016-12-13 19:03:51 -05004252 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4253 VISIT_SEQ(c, expr, e->v.Call.args);
4254 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
Mark Shannond48848c2021-03-14 18:01:30 +00004255 c->u->u_lineno = old_lineno;
Yury Selivanovf2392132016-12-13 19:03:51 -05004256 return 1;
4257}
4258
4259static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004260validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004261{
4262 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4263 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004264 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4265 if (key->arg == NULL) {
4266 continue;
4267 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004268 if (forbidden_name(c, key->arg, Store)) {
4269 return -1;
4270 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004271 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004272 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4273 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07004274 SET_LOC(c, other);
Brandt Bucher145bf262021-02-26 14:51:55 -08004275 compiler_error(c, "keyword argument repeated: %U", key->arg);
Pablo Galindo254ec782020-04-03 20:37:13 +01004276 return -1;
4277 }
4278 }
4279 }
4280 return 0;
4281}
4282
4283static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004284compiler_call(struct compiler *c, expr_ty e)
4285{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004286 int ret = maybe_optimize_method_call(c, e);
4287 if (ret >= 0) {
4288 return ret;
4289 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004290 if (!check_caller(c, e->v.Call.func)) {
4291 return 0;
4292 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004293 VISIT(c, expr, e->v.Call.func);
4294 return compiler_call_helper(c, 0,
4295 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004296 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004297}
4298
Eric V. Smith235a6f02015-09-19 14:51:32 -04004299static int
4300compiler_joined_str(struct compiler *c, expr_ty e)
4301{
Mark Shannon11e0b292021-04-15 14:28:56 +01004302
4303 Py_ssize_t value_count = asdl_seq_LEN(e->v.JoinedStr.values);
4304 if (value_count > STACK_USE_GUIDELINE) {
4305 ADDOP_LOAD_CONST_NEW(c, _PyUnicode_FromASCII("", 0));
4306 PyObject *join = _PyUnicode_FromASCII("join", 4);
4307 if (join == NULL) {
4308 return 0;
4309 }
4310 ADDOP_NAME(c, LOAD_METHOD, join, names);
4311 Py_DECREF(join);
4312 ADDOP_I(c, BUILD_LIST, 0);
4313 for (Py_ssize_t i = 0; i < asdl_seq_LEN(e->v.JoinedStr.values); i++) {
4314 VISIT(c, expr, asdl_seq_GET(e->v.JoinedStr.values, i));
4315 ADDOP_I(c, LIST_APPEND, 1);
4316 }
4317 ADDOP_I(c, CALL_METHOD, 1);
4318 }
4319 else {
4320 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
4321 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1) {
4322 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
4323 }
4324 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004325 return 1;
4326}
4327
Eric V. Smitha78c7952015-11-03 12:45:05 -05004328/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004329static int
4330compiler_formatted_value(struct compiler *c, expr_ty e)
4331{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004332 /* Our oparg encodes 2 pieces of information: the conversion
4333 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004334
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004335 Convert the conversion char to 3 bits:
4336 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004337 !s : 001 0x1 FVC_STR
4338 !r : 010 0x2 FVC_REPR
4339 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004340
Eric V. Smitha78c7952015-11-03 12:45:05 -05004341 next bit is whether or not we have a format spec:
4342 yes : 100 0x4
4343 no : 000 0x0
4344 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004345
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004346 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004347 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004348
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004349 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004350 VISIT(c, expr, e->v.FormattedValue.value);
4351
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004352 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004353 case 's': oparg = FVC_STR; break;
4354 case 'r': oparg = FVC_REPR; break;
4355 case 'a': oparg = FVC_ASCII; break;
4356 case -1: oparg = FVC_NONE; break;
4357 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004358 PyErr_Format(PyExc_SystemError,
4359 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004360 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004361 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004362 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004363 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004364 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004365 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004366 }
4367
Eric V. Smitha78c7952015-11-03 12:45:05 -05004368 /* And push our opcode and oparg */
4369 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004370
Eric V. Smith235a6f02015-09-19 14:51:32 -04004371 return 1;
4372}
4373
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004374static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004375compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004376{
4377 Py_ssize_t i, n = end - begin;
4378 keyword_ty kw;
4379 PyObject *keys, *key;
4380 assert(n > 0);
Mark Shannon11e0b292021-04-15 14:28:56 +01004381 int big = n*2 > STACK_USE_GUIDELINE;
4382 if (n > 1 && !big) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004383 for (i = begin; i < end; i++) {
4384 kw = asdl_seq_GET(keywords, i);
4385 VISIT(c, expr, kw->value);
4386 }
4387 keys = PyTuple_New(n);
4388 if (keys == NULL) {
4389 return 0;
4390 }
4391 for (i = begin; i < end; i++) {
4392 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4393 Py_INCREF(key);
4394 PyTuple_SET_ITEM(keys, i - begin, key);
4395 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004396 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004397 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
Mark Shannon11e0b292021-04-15 14:28:56 +01004398 return 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004399 }
Mark Shannon11e0b292021-04-15 14:28:56 +01004400 if (big) {
4401 ADDOP_I_NOLINE(c, BUILD_MAP, 0);
4402 }
4403 for (i = begin; i < end; i++) {
4404 kw = asdl_seq_GET(keywords, i);
4405 ADDOP_LOAD_CONST(c, kw->arg);
4406 VISIT(c, expr, kw->value);
4407 if (big) {
4408 ADDOP_I_NOLINE(c, MAP_ADD, 1);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004409 }
Mark Shannon11e0b292021-04-15 14:28:56 +01004410 }
4411 if (!big) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004412 ADDOP_I(c, BUILD_MAP, n);
4413 }
4414 return 1;
4415}
4416
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004417/* shared code between compiler_call and compiler_class */
4418static int
4419compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004420 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004421 asdl_expr_seq *args,
4422 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004423{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004424 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004425
Pablo Galindo254ec782020-04-03 20:37:13 +01004426 if (validate_keywords(c, keywords) == -1) {
4427 return 0;
4428 }
4429
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004430 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004431 nkwelts = asdl_seq_LEN(keywords);
4432
Mark Shannon11e0b292021-04-15 14:28:56 +01004433 if (nelts + nkwelts*2 > STACK_USE_GUIDELINE) {
4434 goto ex_call;
4435 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004436 for (i = 0; i < nelts; i++) {
4437 expr_ty elt = asdl_seq_GET(args, i);
4438 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004439 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004440 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004441 }
4442 for (i = 0; i < nkwelts; i++) {
4443 keyword_ty kw = asdl_seq_GET(keywords, i);
4444 if (kw->arg == NULL) {
4445 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004448
Mark Shannon13bc1392020-01-23 09:25:17 +00004449 /* No * or ** args, so can use faster calling sequence */
4450 for (i = 0; i < nelts; i++) {
4451 expr_ty elt = asdl_seq_GET(args, i);
4452 assert(elt->kind != Starred_kind);
4453 VISIT(c, expr, elt);
4454 }
4455 if (nkwelts) {
4456 PyObject *names;
4457 VISIT_SEQ(c, keyword, keywords);
4458 names = PyTuple_New(nkwelts);
4459 if (names == NULL) {
4460 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004461 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004462 for (i = 0; i < nkwelts; i++) {
4463 keyword_ty kw = asdl_seq_GET(keywords, i);
4464 Py_INCREF(kw->arg);
4465 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004466 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004467 ADDOP_LOAD_CONST_NEW(c, names);
4468 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4469 return 1;
4470 }
4471 else {
4472 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4473 return 1;
4474 }
4475
4476ex_call:
4477
4478 /* Do positional arguments. */
4479 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4480 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4481 }
4482 else if (starunpack_helper(c, args, n, BUILD_LIST,
4483 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4484 return 0;
4485 }
4486 /* Then keyword arguments */
4487 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004488 /* Has a new dict been pushed */
4489 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004490
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004491 nseen = 0; /* the number of keyword arguments on the stack following */
4492 for (i = 0; i < nkwelts; i++) {
4493 keyword_ty kw = asdl_seq_GET(keywords, i);
4494 if (kw->arg == NULL) {
4495 /* A keyword argument unpacking. */
4496 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004497 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004498 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004499 }
Mark Shannondb64f122020-06-01 10:42:42 +01004500 if (have_dict) {
4501 ADDOP_I(c, DICT_MERGE, 1);
4502 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004503 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004504 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004505 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004506 if (!have_dict) {
4507 ADDOP_I(c, BUILD_MAP, 0);
4508 have_dict = 1;
4509 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004510 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004511 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004512 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004513 else {
4514 nseen++;
4515 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004516 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004517 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004518 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004519 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004520 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004521 }
4522 if (have_dict) {
4523 ADDOP_I(c, DICT_MERGE, 1);
4524 }
4525 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004526 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004527 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004529 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4530 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004531}
4532
Nick Coghlan650f0d02007-04-15 12:05:43 +00004533
4534/* List and set comprehensions and generator expressions work by creating a
4535 nested function to perform the actual iteration. This means that the
4536 iteration variables don't leak into the current scope.
4537 The defined function is called immediately following its definition, with the
4538 result of that call being the result of the expression.
4539 The LC/SC version returns the populated container, while the GE version is
4540 flagged in symtable.c as a generator, so it returns the generator object
4541 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004542
4543 Possible cleanups:
4544 - iterate over the generator sequence instead of using recursion
4545*/
4546
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004547
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004548static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004549compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004550 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004551 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004552 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004553{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 comprehension_ty gen;
4555 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4556 if (gen->is_async) {
4557 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004558 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004559 } else {
4560 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004561 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004562 }
4563}
4564
4565static int
4566compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004567 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004568 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004569 expr_ty elt, expr_ty val, int type)
4570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004571 /* generate code for the iterator, then each of the ifs,
4572 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004574 comprehension_ty gen;
4575 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004576 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004578 start = compiler_new_block(c);
4579 skip = compiler_new_block(c);
4580 if_cleanup = compiler_new_block(c);
4581 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004583 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4584 anchor == NULL)
4585 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004587 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 if (gen_index == 0) {
4590 /* Receive outermost iter as an implicit argument */
4591 c->u->u_argcount = 1;
4592 ADDOP_I(c, LOAD_FAST, 0);
4593 }
4594 else {
4595 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004596 /* Fast path for the temporary variable assignment idiom:
4597 for y in [f(x)]
4598 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004599 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004600 switch (gen->iter->kind) {
4601 case List_kind:
4602 elts = gen->iter->v.List.elts;
4603 break;
4604 case Tuple_kind:
4605 elts = gen->iter->v.Tuple.elts;
4606 break;
4607 default:
4608 elts = NULL;
4609 }
4610 if (asdl_seq_LEN(elts) == 1) {
4611 expr_ty elt = asdl_seq_GET(elts, 0);
4612 if (elt->kind != Starred_kind) {
4613 VISIT(c, expr, elt);
4614 start = NULL;
4615 }
4616 }
4617 if (start) {
4618 VISIT(c, expr, gen->iter);
4619 ADDOP(c, GET_ITER);
4620 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004621 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004622 if (start) {
4623 depth++;
4624 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004625 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004626 NEXT_BLOCK(c);
4627 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004628 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 /* XXX this needs to be cleaned up...a lot! */
4631 n = asdl_seq_LEN(gen->ifs);
4632 for (i = 0; i < n; i++) {
4633 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004634 if (!compiler_jump_if(c, e, if_cleanup, 0))
4635 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 NEXT_BLOCK(c);
4637 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004639 if (++gen_index < asdl_seq_LEN(generators))
4640 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004641 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 elt, val, type))
4643 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004645 /* only append after the last for generator */
4646 if (gen_index >= asdl_seq_LEN(generators)) {
4647 /* comprehension specific code */
4648 switch (type) {
4649 case COMP_GENEXP:
4650 VISIT(c, expr, elt);
4651 ADDOP(c, YIELD_VALUE);
4652 ADDOP(c, POP_TOP);
4653 break;
4654 case COMP_LISTCOMP:
4655 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004656 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004657 break;
4658 case COMP_SETCOMP:
4659 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004660 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004661 break;
4662 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004663 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004666 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004667 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 break;
4669 default:
4670 return 0;
4671 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 compiler_use_next_block(c, skip);
4674 }
4675 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004676 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004677 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004678 compiler_use_next_block(c, anchor);
4679 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680
4681 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004682}
4683
4684static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004685compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004686 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004687 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004688 expr_ty elt, expr_ty val, int type)
4689{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004690 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004691 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004692 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004693 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004694 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004695 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004696
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004697 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004698 return 0;
4699 }
4700
4701 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4702
4703 if (gen_index == 0) {
4704 /* Receive outermost iter as an implicit argument */
4705 c->u->u_argcount = 1;
4706 ADDOP_I(c, LOAD_FAST, 0);
4707 }
4708 else {
4709 /* Sub-iter - calculate on the fly */
4710 VISIT(c, expr, gen->iter);
4711 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004712 }
4713
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004714 compiler_use_next_block(c, start);
tomKPZ7a7ba3d2021-04-07 07:43:45 -07004715 /* Runtime will push a block here, so we need to account for that */
4716 if (!compiler_push_fblock(c, ASYNC_COMPREHENSION_GENERATOR, start,
4717 NULL, NULL)) {
4718 return 0;
4719 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004720
Mark Shannon582aaf12020-08-04 17:30:11 +01004721 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004722 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004723 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004724 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004725 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004726 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004727
4728 n = asdl_seq_LEN(gen->ifs);
4729 for (i = 0; i < n; i++) {
4730 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004731 if (!compiler_jump_if(c, e, if_cleanup, 0))
4732 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004733 NEXT_BLOCK(c);
4734 }
4735
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004736 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004737 if (++gen_index < asdl_seq_LEN(generators))
4738 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004739 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004740 elt, val, type))
4741 return 0;
4742
4743 /* only append after the last for generator */
4744 if (gen_index >= asdl_seq_LEN(generators)) {
4745 /* comprehension specific code */
4746 switch (type) {
4747 case COMP_GENEXP:
4748 VISIT(c, expr, elt);
4749 ADDOP(c, YIELD_VALUE);
4750 ADDOP(c, POP_TOP);
4751 break;
4752 case COMP_LISTCOMP:
4753 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004754 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004755 break;
4756 case COMP_SETCOMP:
4757 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004758 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004759 break;
4760 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004761 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004762 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004763 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004764 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004765 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004766 break;
4767 default:
4768 return 0;
4769 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004770 }
4771 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004772 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004773
tomKPZ7a7ba3d2021-04-07 07:43:45 -07004774 compiler_pop_fblock(c, ASYNC_COMPREHENSION_GENERATOR, start);
4775
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004776 compiler_use_next_block(c, except);
4777 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004778
4779 return 1;
4780}
4781
4782static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004783compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004784 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004785 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004788 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004789 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004790 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004791 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004792
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004793
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004794 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004795
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004796 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004797 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4798 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004799 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004801 }
Mark Shannon7674c832021-06-21 11:47:16 +01004802 SET_LOC(c, e);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004803
4804 is_async_generator = c->u->u_ste->ste_coroutine;
4805
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004806 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004807 compiler_error(c, "asynchronous comprehension outside of "
4808 "an asynchronous function");
4809 goto error_in_scope;
4810 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004812 if (type != COMP_GENEXP) {
4813 int op;
4814 switch (type) {
4815 case COMP_LISTCOMP:
4816 op = BUILD_LIST;
4817 break;
4818 case COMP_SETCOMP:
4819 op = BUILD_SET;
4820 break;
4821 case COMP_DICTCOMP:
4822 op = BUILD_MAP;
4823 break;
4824 default:
4825 PyErr_Format(PyExc_SystemError,
4826 "unknown comprehension type %d", type);
4827 goto error_in_scope;
4828 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004830 ADDOP_I(c, op, 0);
4831 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004832
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004833 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004834 val, type))
4835 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004837 if (type != COMP_GENEXP) {
4838 ADDOP(c, RETURN_VALUE);
4839 }
4840
4841 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004842 qualname = c->u->u_qualname;
4843 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004844 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004845 if (top_level_await && is_async_generator){
4846 c->u->u_ste->ste_coroutine = 1;
4847 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004848 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004849 goto error;
4850
Victor Stinnerba7a99d2021-01-30 01:46:44 +01004851 if (!compiler_make_closure(c, co, 0, qualname)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004852 goto error;
Victor Stinnerba7a99d2021-01-30 01:46:44 +01004853 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004854 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004855 Py_DECREF(co);
4856
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004857 VISIT(c, expr, outermost->iter);
4858
4859 if (outermost->is_async) {
4860 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004861 } else {
4862 ADDOP(c, GET_ITER);
4863 }
4864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004865 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004866
4867 if (is_async_generator && type != COMP_GENEXP) {
4868 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004869 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004870 ADDOP(c, YIELD_FROM);
4871 }
4872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004873 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004874error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004875 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004876error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004877 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004878 Py_XDECREF(co);
4879 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004880}
4881
4882static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004883compiler_genexp(struct compiler *c, expr_ty e)
4884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004885 static identifier name;
4886 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004887 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004888 if (!name)
4889 return 0;
4890 }
4891 assert(e->kind == GeneratorExp_kind);
4892 return compiler_comprehension(c, e, COMP_GENEXP, name,
4893 e->v.GeneratorExp.generators,
4894 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004895}
4896
4897static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004898compiler_listcomp(struct compiler *c, expr_ty e)
4899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004900 static identifier name;
4901 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004902 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004903 if (!name)
4904 return 0;
4905 }
4906 assert(e->kind == ListComp_kind);
4907 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4908 e->v.ListComp.generators,
4909 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004910}
4911
4912static int
4913compiler_setcomp(struct compiler *c, expr_ty e)
4914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004915 static identifier name;
4916 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004917 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004918 if (!name)
4919 return 0;
4920 }
4921 assert(e->kind == SetComp_kind);
4922 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4923 e->v.SetComp.generators,
4924 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004925}
4926
4927
4928static int
4929compiler_dictcomp(struct compiler *c, expr_ty e)
4930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004931 static identifier name;
4932 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004933 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004934 if (!name)
4935 return 0;
4936 }
4937 assert(e->kind == DictComp_kind);
4938 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4939 e->v.DictComp.generators,
4940 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004941}
4942
4943
4944static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004945compiler_visit_keyword(struct compiler *c, keyword_ty k)
4946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004947 VISIT(c, expr, k->value);
4948 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004949}
4950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004951/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004952 whether they are true or false.
4953
4954 Return values: 1 for true, 0 for false, -1 for non-constant.
4955 */
4956
4957static int
Mark Shannonfee55262019-11-21 09:11:43 +00004958compiler_with_except_finish(struct compiler *c) {
4959 basicblock *exit;
4960 exit = compiler_new_block(c);
4961 if (exit == NULL)
4962 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004963 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004964 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004965 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004966 compiler_use_next_block(c, exit);
4967 ADDOP(c, POP_TOP);
4968 ADDOP(c, POP_TOP);
4969 ADDOP(c, POP_TOP);
4970 ADDOP(c, POP_EXCEPT);
4971 ADDOP(c, POP_TOP);
4972 return 1;
4973}
Yury Selivanov75445082015-05-11 22:57:16 -04004974
4975/*
4976 Implements the async with statement.
4977
4978 The semantics outlined in that PEP are as follows:
4979
4980 async with EXPR as VAR:
4981 BLOCK
4982
4983 It is implemented roughly as:
4984
4985 context = EXPR
4986 exit = context.__aexit__ # not calling it
4987 value = await context.__aenter__()
4988 try:
4989 VAR = value # if VAR present in the syntax
4990 BLOCK
4991 finally:
4992 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004993 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004994 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004995 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004996 if not (await exit(*exc)):
4997 raise
4998 */
4999static int
5000compiler_async_with(struct compiler *c, stmt_ty s, int pos)
5001{
Mark Shannonfee55262019-11-21 09:11:43 +00005002 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04005003 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
5004
5005 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00005006 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005007 c->u->u_ste->ste_coroutine = 1;
5008 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07005009 return compiler_error(c, "'async with' outside async function");
5010 }
Yury Selivanov75445082015-05-11 22:57:16 -04005011
5012 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00005013 final = compiler_new_block(c);
5014 exit = compiler_new_block(c);
5015 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04005016 return 0;
5017
5018 /* Evaluate EXPR */
5019 VISIT(c, expr, item->context_expr);
5020
5021 ADDOP(c, BEFORE_ASYNC_WITH);
5022 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005023 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005024 ADDOP(c, YIELD_FROM);
5025
Mark Shannon582aaf12020-08-04 17:30:11 +01005026 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04005027
5028 /* SETUP_ASYNC_WITH pushes a finally block. */
5029 compiler_use_next_block(c, block);
Mark Shannon5979e812021-04-30 14:32:47 +01005030 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, s)) {
Yury Selivanov75445082015-05-11 22:57:16 -04005031 return 0;
5032 }
5033
5034 if (item->optional_vars) {
5035 VISIT(c, expr, item->optional_vars);
5036 }
5037 else {
5038 /* Discard result from context.__aenter__() */
5039 ADDOP(c, POP_TOP);
5040 }
5041
5042 pos++;
5043 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
5044 /* BLOCK code */
5045 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
5046 else if (!compiler_async_with(c, s, pos))
5047 return 0;
5048
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005049 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00005050 ADDOP(c, POP_BLOCK);
5051 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04005052
Mark Shannonfee55262019-11-21 09:11:43 +00005053 /* For successful outcome:
5054 * call __exit__(None, None, None)
5055 */
Mark Shannon5979e812021-04-30 14:32:47 +01005056 SET_LOC(c, s);
Mark Shannonfee55262019-11-21 09:11:43 +00005057 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04005058 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00005059 ADDOP(c, GET_AWAITABLE);
5060 ADDOP_O(c, LOAD_CONST, Py_None, consts);
5061 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04005062
Mark Shannonfee55262019-11-21 09:11:43 +00005063 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04005064
Mark Shannon582aaf12020-08-04 17:30:11 +01005065 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00005066
5067 /* For exceptional outcome: */
5068 compiler_use_next_block(c, final);
Mark Shannonfee55262019-11-21 09:11:43 +00005069 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04005070 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005071 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005072 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00005073 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04005074
Mark Shannonfee55262019-11-21 09:11:43 +00005075compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04005076 return 1;
5077}
5078
5079
Guido van Rossumc2e20742006-02-27 22:32:47 +00005080/*
5081 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00005082 with EXPR as VAR:
5083 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00005084 is implemented as:
5085 <code for EXPR>
5086 SETUP_WITH E
5087 <code to store to VAR> or POP_TOP
5088 <code for BLOCK>
5089 LOAD_CONST (None, None, None)
5090 CALL_FUNCTION_EX 0
5091 JUMP_FORWARD EXIT
5092 E: WITH_EXCEPT_START (calls EXPR.__exit__)
5093 POP_JUMP_IF_TRUE T:
5094 RERAISE
5095 T: POP_TOP * 3 (remove exception from stack)
5096 POP_EXCEPT
5097 POP_TOP
5098 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00005099 */
Mark Shannonfee55262019-11-21 09:11:43 +00005100
Guido van Rossumc2e20742006-02-27 22:32:47 +00005101static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05005102compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00005103{
Mark Shannonfee55262019-11-21 09:11:43 +00005104 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05005105 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005106
5107 assert(s->kind == With_kind);
5108
Guido van Rossumc2e20742006-02-27 22:32:47 +00005109 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00005110 final = compiler_new_block(c);
5111 exit = compiler_new_block(c);
5112 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00005113 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00005114
Thomas Wouters477c8d52006-05-27 19:21:47 +00005115 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05005116 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00005117 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01005118 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005119
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005120 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00005121 compiler_use_next_block(c, block);
Mark Shannon5979e812021-04-30 14:32:47 +01005122 if (!compiler_push_fblock(c, WITH, block, final, s)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00005123 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00005124 }
5125
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05005126 if (item->optional_vars) {
5127 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00005128 }
5129 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00005131 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005132 }
5133
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05005134 pos++;
5135 if (pos == asdl_seq_LEN(s->v.With.items))
5136 /* BLOCK code */
5137 VISIT_SEQ(c, stmt, s->v.With.body)
5138 else if (!compiler_with(c, s, pos))
5139 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00005140
Mark Shannon3bd60352021-01-13 12:05:43 +00005141
5142 /* Mark all following code as artificial */
5143 c->u->u_lineno = -1;
Guido van Rossumc2e20742006-02-27 22:32:47 +00005144 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005145 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00005146
Mark Shannonfee55262019-11-21 09:11:43 +00005147 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00005148
Mark Shannonfee55262019-11-21 09:11:43 +00005149 /* For successful outcome:
5150 * call __exit__(None, None, None)
5151 */
Mark Shannon5979e812021-04-30 14:32:47 +01005152 SET_LOC(c, s);
Mark Shannonfee55262019-11-21 09:11:43 +00005153 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00005154 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00005155 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01005156 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005157
Mark Shannonfee55262019-11-21 09:11:43 +00005158 /* For exceptional outcome: */
5159 compiler_use_next_block(c, final);
Mark Shannonfee55262019-11-21 09:11:43 +00005160 ADDOP(c, WITH_EXCEPT_START);
5161 compiler_with_except_finish(c);
5162
5163 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005164 return 1;
5165}
5166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005167static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005168compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07005171 case NamedExpr_kind:
5172 VISIT(c, expr, e->v.NamedExpr.value);
5173 ADDOP(c, DUP_TOP);
5174 VISIT(c, expr, e->v.NamedExpr.target);
5175 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005176 case BoolOp_kind:
5177 return compiler_boolop(c, e);
5178 case BinOp_kind:
5179 VISIT(c, expr, e->v.BinOp.left);
5180 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05005181 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005182 break;
5183 case UnaryOp_kind:
5184 VISIT(c, expr, e->v.UnaryOp.operand);
5185 ADDOP(c, unaryop(e->v.UnaryOp.op));
5186 break;
5187 case Lambda_kind:
5188 return compiler_lambda(c, e);
5189 case IfExp_kind:
5190 return compiler_ifexp(c, e);
5191 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005192 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005194 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 case GeneratorExp_kind:
5196 return compiler_genexp(c, e);
5197 case ListComp_kind:
5198 return compiler_listcomp(c, e);
5199 case SetComp_kind:
5200 return compiler_setcomp(c, e);
5201 case DictComp_kind:
5202 return compiler_dictcomp(c, e);
5203 case Yield_kind:
5204 if (c->u->u_ste->ste_type != FunctionBlock)
5205 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005206 if (e->v.Yield.value) {
5207 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005208 }
5209 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005210 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005211 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005212 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005213 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005214 case YieldFrom_kind:
5215 if (c->u->u_ste->ste_type != FunctionBlock)
5216 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005217
5218 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5219 return compiler_error(c, "'yield from' inside async function");
5220
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005221 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005222 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005223 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005224 ADDOP(c, YIELD_FROM);
5225 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005226 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005227 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005228 if (c->u->u_ste->ste_type != FunctionBlock){
5229 return compiler_error(c, "'await' outside function");
5230 }
Yury Selivanov75445082015-05-11 22:57:16 -04005231
Victor Stinner331a6a52019-05-27 16:39:22 +02005232 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005233 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5234 return compiler_error(c, "'await' outside async function");
5235 }
5236 }
Yury Selivanov75445082015-05-11 22:57:16 -04005237
5238 VISIT(c, expr, e->v.Await.value);
5239 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005240 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005241 ADDOP(c, YIELD_FROM);
5242 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005243 case Compare_kind:
5244 return compiler_compare(c, e);
5245 case Call_kind:
5246 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005247 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005248 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005249 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005250 case JoinedStr_kind:
5251 return compiler_joined_str(c, e);
5252 case FormattedValue_kind:
5253 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005254 /* The following exprs can be assignment targets. */
5255 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005256 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005257 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005258 case Load:
Mark Shannond48848c2021-03-14 18:01:30 +00005259 {
5260 int old_lineno = c->u->u_lineno;
5261 c->u->u_lineno = e->end_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005262 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005263 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005264 break;
Mark Shannond48848c2021-03-14 18:01:30 +00005265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005266 case Store:
Mark Shannond48848c2021-03-14 18:01:30 +00005267 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005268 return 0;
Mark Shannond48848c2021-03-14 18:01:30 +00005269 }
5270 int old_lineno = c->u->u_lineno;
5271 c->u->u_lineno = e->end_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005272 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005273 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005274 break;
5275 case Del:
5276 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5277 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005278 }
5279 break;
5280 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005281 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 case Starred_kind:
5283 switch (e->v.Starred.ctx) {
5284 case Store:
5285 /* In all legitimate cases, the Starred node was already replaced
5286 * by compiler_list/compiler_tuple. XXX: is that okay? */
5287 return compiler_error(c,
5288 "starred assignment target must be in a list or tuple");
5289 default:
5290 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005291 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005293 break;
5294 case Slice_kind:
5295 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005296 case Name_kind:
5297 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5298 /* child nodes of List and Tuple will have expr_context set */
5299 case List_kind:
5300 return compiler_list(c, e);
5301 case Tuple_kind:
5302 return compiler_tuple(c, e);
5303 }
5304 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005305}
5306
5307static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005308compiler_visit_expr(struct compiler *c, expr_ty e)
5309{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005310 int old_lineno = c->u->u_lineno;
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005311 int old_end_lineno = c->u->u_end_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005312 int old_col_offset = c->u->u_col_offset;
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005313 int old_end_col_offset = c->u->u_end_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005314 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005315 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005316 c->u->u_lineno = old_lineno;
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005317 c->u->u_end_lineno = old_end_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005318 c->u->u_col_offset = old_col_offset;
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005319 c->u->u_end_col_offset = old_end_col_offset;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005320 return res;
5321}
5322
5323static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005324compiler_augassign(struct compiler *c, stmt_ty s)
5325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005326 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005327 expr_ty e = s->v.AugAssign.target;
5328
5329 int old_lineno = c->u->u_lineno;
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005330 int old_end_lineno = c->u->u_end_lineno;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005331 int old_col_offset = c->u->u_col_offset;
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005332 int old_end_col_offset = c->u->u_end_col_offset;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005333 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005335 switch (e->kind) {
5336 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005337 VISIT(c, expr, e->v.Attribute.value);
5338 ADDOP(c, DUP_TOP);
Mark Shannond48848c2021-03-14 18:01:30 +00005339 int old_lineno = c->u->u_lineno;
5340 c->u->u_lineno = e->end_lineno;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005341 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005342 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005343 break;
5344 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005345 VISIT(c, expr, e->v.Subscript.value);
5346 VISIT(c, expr, e->v.Subscript.slice);
5347 ADDOP(c, DUP_TOP_TWO);
5348 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 break;
5350 case Name_kind:
5351 if (!compiler_nameop(c, e->v.Name.id, Load))
5352 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005353 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 default:
5355 PyErr_Format(PyExc_SystemError,
5356 "invalid node type (%d) for augmented assignment",
5357 e->kind);
5358 return 0;
5359 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005360
5361 c->u->u_lineno = old_lineno;
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005362 c->u->u_end_lineno = old_end_lineno;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005363 c->u->u_col_offset = old_col_offset;
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005364 c->u->u_end_col_offset = old_end_col_offset;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005365
5366 VISIT(c, expr, s->v.AugAssign.value);
5367 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5368
5369 SET_LOC(c, e);
5370
5371 switch (e->kind) {
5372 case Attribute_kind:
Mark Shannond48848c2021-03-14 18:01:30 +00005373 c->u->u_lineno = e->end_lineno;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005374 ADDOP(c, ROT_TWO);
5375 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5376 break;
5377 case Subscript_kind:
5378 ADDOP(c, ROT_THREE);
5379 ADDOP(c, STORE_SUBSCR);
5380 break;
5381 case Name_kind:
5382 return compiler_nameop(c, e->v.Name.id, Store);
5383 default:
5384 Py_UNREACHABLE();
5385 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005387}
5388
5389static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005390check_ann_expr(struct compiler *c, expr_ty e)
5391{
5392 VISIT(c, expr, e);
5393 ADDOP(c, POP_TOP);
5394 return 1;
5395}
5396
5397static int
5398check_annotation(struct compiler *c, stmt_ty s)
5399{
Batuhan Taskaya8cc3cfa2021-04-25 05:31:20 +03005400 /* Annotations of complex targets does not produce anything
5401 under annotations future */
5402 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5403 return 1;
5404 }
5405
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005406 /* Annotations are only evaluated in a module or class. */
5407 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5408 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5409 return check_ann_expr(c, s->v.AnnAssign.annotation);
5410 }
5411 return 1;
5412}
5413
5414static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005415check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005416{
5417 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005418 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005419 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005420 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005421 return 0;
5422 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005423 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5424 return 0;
5425 }
5426 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5427 return 0;
5428 }
5429 return 1;
5430 case Tuple_kind: {
5431 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005432 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005433 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005434 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005435 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005436 return 0;
5437 }
5438 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005439 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005440 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005441 default:
5442 return check_ann_expr(c, e);
5443 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005444}
5445
5446static int
5447compiler_annassign(struct compiler *c, stmt_ty s)
5448{
5449 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005450 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005451
5452 assert(s->kind == AnnAssign_kind);
5453
5454 /* We perform the actual assignment first. */
5455 if (s->v.AnnAssign.value) {
5456 VISIT(c, expr, s->v.AnnAssign.value);
5457 VISIT(c, expr, targ);
5458 }
5459 switch (targ->kind) {
5460 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005461 if (forbidden_name(c, targ->v.Name.id, Store))
5462 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005463 /* If we have a simple name in a module or class, store annotation. */
5464 if (s->v.AnnAssign.simple &&
5465 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5466 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Pablo Galindob0544ba2021-04-21 12:41:19 +01005467 if (c->c_future->ff_features & CO_FUTURE_ANNOTATIONS) {
5468 VISIT(c, annexpr, s->v.AnnAssign.annotation)
5469 }
5470 else {
5471 VISIT(c, expr, s->v.AnnAssign.annotation);
5472 }
Mark Shannon332cd5e2018-01-30 00:41:04 +00005473 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005474 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005475 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005476 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005477 }
5478 break;
5479 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005480 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5481 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005482 if (!s->v.AnnAssign.value &&
5483 !check_ann_expr(c, targ->v.Attribute.value)) {
5484 return 0;
5485 }
5486 break;
5487 case Subscript_kind:
5488 if (!s->v.AnnAssign.value &&
5489 (!check_ann_expr(c, targ->v.Subscript.value) ||
5490 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5491 return 0;
5492 }
5493 break;
5494 default:
5495 PyErr_Format(PyExc_SystemError,
5496 "invalid node type (%d) for annotated assignment",
5497 targ->kind);
5498 return 0;
5499 }
5500 /* Annotation is evaluated last. */
5501 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5502 return 0;
5503 }
5504 return 1;
5505}
5506
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005507/* Raises a SyntaxError and returns 0.
5508 If something goes wrong, a different exception may be raised.
5509*/
5510
5511static int
Brandt Bucher145bf262021-02-26 14:51:55 -08005512compiler_error(struct compiler *c, const char *format, ...)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005513{
Brandt Bucher145bf262021-02-26 14:51:55 -08005514 va_list vargs;
5515#ifdef HAVE_STDARG_PROTOTYPES
5516 va_start(vargs, format);
5517#else
5518 va_start(vargs);
5519#endif
5520 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5521 va_end(vargs);
5522 if (msg == NULL) {
5523 return 0;
5524 }
5525 PyObject *loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
5526 if (loc == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 Py_INCREF(Py_None);
5528 loc = Py_None;
5529 }
Pablo Galindoa77aac42021-04-23 14:27:05 +01005530 PyObject *args = Py_BuildValue("O(OiiOii)", msg, c->c_filename,
5531 c->u->u_lineno, c->u->u_col_offset + 1, loc,
5532 c->u->u_end_lineno, c->u->u_end_col_offset + 1);
Brandt Bucher145bf262021-02-26 14:51:55 -08005533 Py_DECREF(msg);
5534 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 goto exit;
Brandt Bucher145bf262021-02-26 14:51:55 -08005536 }
5537 PyErr_SetObject(PyExc_SyntaxError, args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005538 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 Py_DECREF(loc);
Brandt Bucher145bf262021-02-26 14:51:55 -08005540 Py_XDECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005542}
5543
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005544/* Emits a SyntaxWarning and returns 1 on success.
5545 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5546 and returns 0.
5547*/
5548static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005549compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005550{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005551 va_list vargs;
5552#ifdef HAVE_STDARG_PROTOTYPES
5553 va_start(vargs, format);
5554#else
5555 va_start(vargs);
5556#endif
5557 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5558 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005559 if (msg == NULL) {
5560 return 0;
5561 }
5562 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5563 c->u->u_lineno, NULL, NULL) < 0)
5564 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005565 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005566 /* Replace the SyntaxWarning exception with a SyntaxError
5567 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005568 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005569 assert(PyUnicode_AsUTF8(msg) != NULL);
5570 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005571 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005572 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005573 return 0;
5574 }
5575 Py_DECREF(msg);
5576 return 1;
5577}
5578
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005579static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005580compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005581{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005582 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005584
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005585 if (ctx == Load) {
5586 if (!check_subscripter(c, e->v.Subscript.value)) {
5587 return 0;
5588 }
5589 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5590 return 0;
5591 }
5592 }
5593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005594 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005596 case Store: op = STORE_SUBSCR; break;
5597 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005598 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005599 assert(op);
5600 VISIT(c, expr, e->v.Subscript.value);
5601 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005602 ADDOP(c, op);
5603 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005604}
5605
5606static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005607compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005609 int n = 2;
5610 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005612 /* only handles the cases where BUILD_SLICE is emitted */
5613 if (s->v.Slice.lower) {
5614 VISIT(c, expr, s->v.Slice.lower);
5615 }
5616 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005617 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005620 if (s->v.Slice.upper) {
5621 VISIT(c, expr, s->v.Slice.upper);
5622 }
5623 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005624 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 }
5626
5627 if (s->v.Slice.step) {
5628 n++;
5629 VISIT(c, expr, s->v.Slice.step);
5630 }
5631 ADDOP_I(c, BUILD_SLICE, n);
5632 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005633}
5634
Brandt Bucher145bf262021-02-26 14:51:55 -08005635
5636// PEP 634: Structural Pattern Matching
5637
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005638// To keep things simple, all compiler_pattern_* and pattern_helper_* routines
5639// follow the convention of consuming TOS (the subject for the given pattern)
5640// and calling jump_to_fail_pop on failure (no match).
5641
5642// When calling into these routines, it's important that pc->on_top be kept
5643// updated to reflect the current number of items that we are using on the top
5644// of the stack: they will be popped on failure, and any name captures will be
5645// stored *underneath* them on success. This lets us defer all names stores
5646// until the *entire* pattern matches.
Brandt Bucher145bf262021-02-26 14:51:55 -08005647
Brandt Bucher145bf262021-02-26 14:51:55 -08005648#define WILDCARD_CHECK(N) \
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005649 ((N)->kind == MatchAs_kind && !(N)->v.MatchAs.name)
Brandt Bucher145bf262021-02-26 14:51:55 -08005650
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005651#define WILDCARD_STAR_CHECK(N) \
5652 ((N)->kind == MatchStar_kind && !(N)->v.MatchStar.name)
5653
5654// Limit permitted subexpressions, even if the parser & AST validator let them through
5655#define MATCH_VALUE_EXPR(N) \
5656 ((N)->kind == Constant_kind || (N)->kind == Attribute_kind)
Brandt Bucher145bf262021-02-26 14:51:55 -08005657
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005658// Allocate or resize pc->fail_pop to allow for n items to be popped on failure.
5659static int
5660ensure_fail_pop(struct compiler *c, pattern_context *pc, Py_ssize_t n)
5661{
5662 Py_ssize_t size = n + 1;
5663 if (size <= pc->fail_pop_size) {
5664 return 1;
5665 }
5666 Py_ssize_t needed = sizeof(basicblock*) * size;
5667 basicblock **resized = PyObject_Realloc(pc->fail_pop, needed);
5668 if (resized == NULL) {
5669 PyErr_NoMemory();
5670 return 0;
5671 }
5672 pc->fail_pop = resized;
5673 while (pc->fail_pop_size < size) {
5674 basicblock *new_block;
5675 RETURN_IF_FALSE(new_block = compiler_new_block(c));
5676 pc->fail_pop[pc->fail_pop_size++] = new_block;
5677 }
5678 return 1;
5679}
5680
5681// Use op to jump to the correct fail_pop block.
5682static int
5683jump_to_fail_pop(struct compiler *c, pattern_context *pc, int op)
5684{
5685 // Pop any items on the top of the stack, plus any objects we were going to
5686 // capture on success:
5687 Py_ssize_t pops = pc->on_top + PyList_GET_SIZE(pc->stores);
5688 RETURN_IF_FALSE(ensure_fail_pop(c, pc, pops));
5689 ADDOP_JUMP(c, op, pc->fail_pop[pops]);
5690 NEXT_BLOCK(c);
5691 return 1;
5692}
5693
5694// Build all of the fail_pop blocks and reset fail_pop.
5695static int
5696emit_and_reset_fail_pop(struct compiler *c, pattern_context *pc)
5697{
5698 if (!pc->fail_pop_size) {
5699 assert(pc->fail_pop == NULL);
5700 NEXT_BLOCK(c);
5701 return 1;
5702 }
5703 while (--pc->fail_pop_size) {
5704 compiler_use_next_block(c, pc->fail_pop[pc->fail_pop_size]);
5705 if (!compiler_addop(c, POP_TOP)) {
5706 pc->fail_pop_size = 0;
5707 PyObject_Free(pc->fail_pop);
5708 pc->fail_pop = NULL;
5709 return 0;
5710 }
5711 }
5712 compiler_use_next_block(c, pc->fail_pop[0]);
5713 PyObject_Free(pc->fail_pop);
5714 pc->fail_pop = NULL;
5715 return 1;
5716}
5717
5718static int
5719compiler_error_duplicate_store(struct compiler *c, identifier n)
5720{
5721 return compiler_error(c, "multiple assignments to name %R in pattern", n);
5722}
5723
Brandt Bucher145bf262021-02-26 14:51:55 -08005724static int
5725pattern_helper_store_name(struct compiler *c, identifier n, pattern_context *pc)
5726{
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07005727 if (n == NULL) {
5728 ADDOP(c, POP_TOP);
5729 return 1;
5730 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005731 if (forbidden_name(c, n, Store)) {
5732 return 0;
5733 }
Brandt Bucher145bf262021-02-26 14:51:55 -08005734 // Can't assign to the same name twice:
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005735 int duplicate = PySequence_Contains(pc->stores, n);
5736 if (duplicate < 0) {
5737 return 0;
Brandt Bucher145bf262021-02-26 14:51:55 -08005738 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005739 if (duplicate) {
5740 return compiler_error_duplicate_store(c, n);
Brandt Bucher145bf262021-02-26 14:51:55 -08005741 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005742 // Rotate this object underneath any items we need to preserve:
5743 ADDOP_I(c, ROT_N, pc->on_top + PyList_GET_SIZE(pc->stores) + 1);
5744 return !PyList_Append(pc->stores, n);
Brandt Bucher145bf262021-02-26 14:51:55 -08005745}
5746
5747
5748static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005749pattern_unpack_helper(struct compiler *c, asdl_pattern_seq *elts)
5750{
5751 Py_ssize_t n = asdl_seq_LEN(elts);
5752 int seen_star = 0;
5753 for (Py_ssize_t i = 0; i < n; i++) {
5754 pattern_ty elt = asdl_seq_GET(elts, i);
5755 if (elt->kind == MatchStar_kind && !seen_star) {
5756 if ((i >= (1 << 8)) ||
5757 (n-i-1 >= (INT_MAX >> 8)))
5758 return compiler_error(c,
5759 "too many expressions in "
5760 "star-unpacking sequence pattern");
5761 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
5762 seen_star = 1;
5763 }
5764 else if (elt->kind == MatchStar_kind) {
5765 return compiler_error(c,
5766 "multiple starred expressions in sequence pattern");
5767 }
5768 }
5769 if (!seen_star) {
5770 ADDOP_I(c, UNPACK_SEQUENCE, n);
5771 }
5772 return 1;
5773}
5774
5775static int
5776pattern_helper_sequence_unpack(struct compiler *c, asdl_pattern_seq *patterns,
Brandt Bucher145bf262021-02-26 14:51:55 -08005777 Py_ssize_t star, pattern_context *pc)
5778{
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005779 RETURN_IF_FALSE(pattern_unpack_helper(c, patterns));
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005780 Py_ssize_t size = asdl_seq_LEN(patterns);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005781 // We've now got a bunch of new subjects on the stack. They need to remain
5782 // there after each subpattern match:
5783 pc->on_top += size;
Brandt Bucher145bf262021-02-26 14:51:55 -08005784 for (Py_ssize_t i = 0; i < size; i++) {
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005785 // One less item to keep track of each time we loop through:
5786 pc->on_top--;
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005787 pattern_ty pattern = asdl_seq_GET(patterns, i);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005788 RETURN_IF_FALSE(compiler_pattern_subpattern(c, pattern, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08005789 }
Brandt Bucher145bf262021-02-26 14:51:55 -08005790 return 1;
Brandt Bucher145bf262021-02-26 14:51:55 -08005791}
5792
5793// Like pattern_helper_sequence_unpack, but uses BINARY_SUBSCR instead of
5794// UNPACK_SEQUENCE / UNPACK_EX. This is more efficient for patterns with a
5795// starred wildcard like [first, *_] / [first, *_, last] / [*_, last] / etc.
5796static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005797pattern_helper_sequence_subscr(struct compiler *c, asdl_pattern_seq *patterns,
Brandt Bucher145bf262021-02-26 14:51:55 -08005798 Py_ssize_t star, pattern_context *pc)
5799{
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005800 // We need to keep the subject around for extracting elements:
5801 pc->on_top++;
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005802 Py_ssize_t size = asdl_seq_LEN(patterns);
Brandt Bucher145bf262021-02-26 14:51:55 -08005803 for (Py_ssize_t i = 0; i < size; i++) {
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005804 pattern_ty pattern = asdl_seq_GET(patterns, i);
5805 if (WILDCARD_CHECK(pattern)) {
Brandt Bucher145bf262021-02-26 14:51:55 -08005806 continue;
5807 }
5808 if (i == star) {
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005809 assert(WILDCARD_STAR_CHECK(pattern));
Brandt Bucher145bf262021-02-26 14:51:55 -08005810 continue;
5811 }
5812 ADDOP(c, DUP_TOP);
5813 if (i < star) {
5814 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
5815 }
5816 else {
5817 // The subject may not support negative indexing! Compute a
5818 // nonnegative index:
5819 ADDOP(c, GET_LEN);
5820 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size - i));
5821 ADDOP(c, BINARY_SUBTRACT);
5822 }
5823 ADDOP(c, BINARY_SUBSCR);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005824 RETURN_IF_FALSE(compiler_pattern_subpattern(c, pattern, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08005825 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005826 // Pop the subject, we're done with it:
5827 pc->on_top--;
Brandt Bucher145bf262021-02-26 14:51:55 -08005828 ADDOP(c, POP_TOP);
Brandt Bucher145bf262021-02-26 14:51:55 -08005829 return 1;
5830}
5831
Brandt Bucher145bf262021-02-26 14:51:55 -08005832// Like compiler_pattern, but turn off checks for irrefutability.
5833static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005834compiler_pattern_subpattern(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08005835{
5836 int allow_irrefutable = pc->allow_irrefutable;
5837 pc->allow_irrefutable = 1;
5838 RETURN_IF_FALSE(compiler_pattern(c, p, pc));
5839 pc->allow_irrefutable = allow_irrefutable;
5840 return 1;
5841}
5842
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005843static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005844compiler_pattern_as(struct compiler *c, pattern_ty p, pattern_context *pc)
5845{
5846 assert(p->kind == MatchAs_kind);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005847 if (p->v.MatchAs.pattern == NULL) {
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07005848 // An irrefutable match:
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005849 if (!pc->allow_irrefutable) {
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07005850 if (p->v.MatchAs.name) {
5851 const char *e = "name capture %R makes remaining patterns unreachable";
5852 return compiler_error(c, e, p->v.MatchAs.name);
5853 }
5854 const char *e = "wildcard makes remaining patterns unreachable";
5855 return compiler_error(c, e);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005856 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005857 return pattern_helper_store_name(c, p->v.MatchAs.name, pc);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005858 }
Brandt Bucher145bf262021-02-26 14:51:55 -08005859 // Need to make a copy for (possibly) storing later:
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005860 pc->on_top++;
Brandt Bucher145bf262021-02-26 14:51:55 -08005861 ADDOP(c, DUP_TOP);
5862 RETURN_IF_FALSE(compiler_pattern(c, p->v.MatchAs.pattern, pc));
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005863 // Success! Store it:
5864 pc->on_top--;
Brandt Bucher145bf262021-02-26 14:51:55 -08005865 RETURN_IF_FALSE(pattern_helper_store_name(c, p->v.MatchAs.name, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08005866 return 1;
5867}
5868
Brandt Bucher145bf262021-02-26 14:51:55 -08005869static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005870compiler_pattern_star(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08005871{
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005872 assert(p->kind == MatchStar_kind);
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07005873 RETURN_IF_FALSE(pattern_helper_store_name(c, p->v.MatchStar.name, pc));
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07005874 return 1;
Brandt Bucher145bf262021-02-26 14:51:55 -08005875}
5876
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005877static int
5878validate_kwd_attrs(struct compiler *c, asdl_identifier_seq *attrs, asdl_pattern_seq* patterns)
5879{
5880 // Any errors will point to the pattern rather than the arg name as the
5881 // parser is only supplying identifiers rather than Name or keyword nodes
5882 Py_ssize_t nattrs = asdl_seq_LEN(attrs);
5883 for (Py_ssize_t i = 0; i < nattrs; i++) {
5884 identifier attr = ((identifier)asdl_seq_GET(attrs, i));
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005885 SET_LOC(c, ((pattern_ty) asdl_seq_GET(patterns, i)));
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005886 if (forbidden_name(c, attr, Store)) {
5887 return -1;
5888 }
5889 for (Py_ssize_t j = i + 1; j < nattrs; j++) {
5890 identifier other = ((identifier)asdl_seq_GET(attrs, j));
5891 if (!PyUnicode_Compare(attr, other)) {
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005892 SET_LOC(c, ((pattern_ty) asdl_seq_GET(patterns, j)));
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005893 compiler_error(c, "attribute name repeated in class pattern: %U", attr);
5894 return -1;
5895 }
5896 }
5897 }
5898 return 0;
5899}
Brandt Bucher145bf262021-02-26 14:51:55 -08005900
5901static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005902compiler_pattern_class(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08005903{
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005904 assert(p->kind == MatchClass_kind);
5905 asdl_pattern_seq *patterns = p->v.MatchClass.patterns;
5906 asdl_identifier_seq *kwd_attrs = p->v.MatchClass.kwd_attrs;
5907 asdl_pattern_seq *kwd_patterns = p->v.MatchClass.kwd_patterns;
5908 Py_ssize_t nargs = asdl_seq_LEN(patterns);
5909 Py_ssize_t nattrs = asdl_seq_LEN(kwd_attrs);
5910 Py_ssize_t nkwd_patterns = asdl_seq_LEN(kwd_patterns);
5911 if (nattrs != nkwd_patterns) {
5912 // AST validator shouldn't let this happen, but if it does,
5913 // just fail, don't crash out of the interpreter
5914 const char * e = "kwd_attrs (%d) / kwd_patterns (%d) length mismatch in class pattern";
5915 return compiler_error(c, e, nattrs, nkwd_patterns);
Brandt Bucher145bf262021-02-26 14:51:55 -08005916 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005917 if (INT_MAX < nargs || INT_MAX < nargs + nattrs - 1) {
5918 const char *e = "too many sub-patterns in class pattern %R";
5919 return compiler_error(c, e, p->v.MatchClass.cls);
5920 }
5921 if (nattrs) {
5922 RETURN_IF_FALSE(!validate_kwd_attrs(c, kwd_attrs, kwd_patterns));
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07005923 SET_LOC(c, p);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005924 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005925 VISIT(c, expr, p->v.MatchClass.cls);
5926 PyObject *attr_names;
5927 RETURN_IF_FALSE(attr_names = PyTuple_New(nattrs));
Brandt Bucher145bf262021-02-26 14:51:55 -08005928 Py_ssize_t i;
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005929 for (i = 0; i < nattrs; i++) {
5930 PyObject *name = asdl_seq_GET(kwd_attrs, i);
Brandt Bucher145bf262021-02-26 14:51:55 -08005931 Py_INCREF(name);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005932 PyTuple_SET_ITEM(attr_names, i, name);
Brandt Bucher145bf262021-02-26 14:51:55 -08005933 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005934 ADDOP_LOAD_CONST_NEW(c, attr_names);
Brandt Bucher145bf262021-02-26 14:51:55 -08005935 ADDOP_I(c, MATCH_CLASS, nargs);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005936 // TOS is now a tuple of (nargs + nattrs) attributes. Preserve it:
5937 pc->on_top++;
5938 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005939 for (i = 0; i < nargs + nattrs; i++) {
5940 pattern_ty pattern;
Brandt Bucher145bf262021-02-26 14:51:55 -08005941 if (i < nargs) {
5942 // Positional:
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005943 pattern = asdl_seq_GET(patterns, i);
Brandt Bucher145bf262021-02-26 14:51:55 -08005944 }
5945 else {
5946 // Keyword:
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005947 pattern = asdl_seq_GET(kwd_patterns, i - nargs);
Brandt Bucher145bf262021-02-26 14:51:55 -08005948 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005949 if (WILDCARD_CHECK(pattern)) {
Brandt Bucher145bf262021-02-26 14:51:55 -08005950 continue;
5951 }
5952 // Get the i-th attribute, and match it against the i-th pattern:
5953 ADDOP(c, DUP_TOP);
5954 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
5955 ADDOP(c, BINARY_SUBSCR);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005956 RETURN_IF_FALSE(compiler_pattern_subpattern(c, pattern, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08005957 }
5958 // Success! Pop the tuple of attributes:
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005959 pc->on_top--;
Brandt Bucher145bf262021-02-26 14:51:55 -08005960 ADDOP(c, POP_TOP);
Brandt Bucher145bf262021-02-26 14:51:55 -08005961 return 1;
5962}
5963
Brandt Bucher145bf262021-02-26 14:51:55 -08005964static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005965compiler_pattern_mapping(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08005966{
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005967 assert(p->kind == MatchMapping_kind);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005968 asdl_expr_seq *keys = p->v.MatchMapping.keys;
5969 asdl_pattern_seq *patterns = p->v.MatchMapping.patterns;
5970 Py_ssize_t size = asdl_seq_LEN(keys);
5971 Py_ssize_t npatterns = asdl_seq_LEN(patterns);
5972 if (size != npatterns) {
5973 // AST validator shouldn't let this happen, but if it does,
5974 // just fail, don't crash out of the interpreter
5975 const char * e = "keys (%d) / patterns (%d) length mismatch in mapping pattern";
5976 return compiler_error(c, e, size, npatterns);
5977 }
5978 // We have a double-star target if "rest" is set
5979 PyObject *star_target = p->v.MatchMapping.rest;
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005980 // We need to keep the subject on top during the mapping and length checks:
5981 pc->on_top++;
Brandt Bucher145bf262021-02-26 14:51:55 -08005982 ADDOP(c, MATCH_MAPPING);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005983 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005984 if (!size && !star_target) {
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005985 // If the pattern is just "{}", we're done! Pop the subject:
5986 pc->on_top--;
Brandt Bucher145bf262021-02-26 14:51:55 -08005987 ADDOP(c, POP_TOP);
Brandt Bucher145bf262021-02-26 14:51:55 -08005988 return 1;
5989 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005990 if (size) {
Brandt Bucher145bf262021-02-26 14:51:55 -08005991 // If the pattern has any keys in it, perform a length check:
5992 ADDOP(c, GET_LEN);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005993 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size));
Brandt Bucher145bf262021-02-26 14:51:55 -08005994 ADDOP_COMPARE(c, GtE);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07005995 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
Brandt Bucher145bf262021-02-26 14:51:55 -08005996 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10005997 if (INT_MAX < size - 1) {
Brandt Bucher145bf262021-02-26 14:51:55 -08005998 return compiler_error(c, "too many sub-patterns in mapping pattern");
5999 }
6000 // Collect all of the keys into a tuple for MATCH_KEYS and
6001 // COPY_DICT_WITHOUT_KEYS. They can either be dotted names or literals:
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006002 for (Py_ssize_t i = 0; i < size; i++) {
Brandt Bucher145bf262021-02-26 14:51:55 -08006003 expr_ty key = asdl_seq_GET(keys, i);
6004 if (key == NULL) {
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006005 const char *e = "can't use NULL keys in MatchMapping "
6006 "(set 'rest' parameter instead)";
Miss Islington (bot)13de28f2021-05-07 13:40:09 -07006007 SET_LOC(c, ((pattern_ty) asdl_seq_GET(patterns, i)));
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006008 return compiler_error(c, e);
6009 }
6010 if (!MATCH_VALUE_EXPR(key)) {
6011 const char *e = "mapping pattern keys may only match literals and attribute lookups";
Brandt Bucher145bf262021-02-26 14:51:55 -08006012 return compiler_error(c, e);
6013 }
6014 VISIT(c, expr, key);
6015 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006016 ADDOP_I(c, BUILD_TUPLE, size);
Brandt Bucher145bf262021-02-26 14:51:55 -08006017 ADDOP(c, MATCH_KEYS);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006018 // There's now a tuple of keys and a tuple of values on top of the subject:
6019 pc->on_top += 2;
6020 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
6021 // So far so good. Use that tuple of values on the stack to match
Brandt Bucher145bf262021-02-26 14:51:55 -08006022 // sub-patterns against:
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006023 for (Py_ssize_t i = 0; i < size; i++) {
6024 pattern_ty pattern = asdl_seq_GET(patterns, i);
6025 if (WILDCARD_CHECK(pattern)) {
Brandt Bucher145bf262021-02-26 14:51:55 -08006026 continue;
6027 }
6028 ADDOP(c, DUP_TOP);
6029 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
6030 ADDOP(c, BINARY_SUBSCR);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006031 RETURN_IF_FALSE(compiler_pattern_subpattern(c, pattern, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08006032 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006033 // If we get this far, it's a match! We're done with the tuple of values,
6034 // and whatever happens next should consume the tuple of keys underneath it:
6035 pc->on_top -= 2;
Brandt Bucher145bf262021-02-26 14:51:55 -08006036 ADDOP(c, POP_TOP);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006037 if (star_target) {
6038 // If we have a starred name, bind a dict of remaining items to it:
Brandt Bucher145bf262021-02-26 14:51:55 -08006039 ADDOP(c, COPY_DICT_WITHOUT_KEYS);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006040 RETURN_IF_FALSE(pattern_helper_store_name(c, star_target, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08006041 }
6042 else {
6043 // Otherwise, we don't care about this tuple of keys anymore:
6044 ADDOP(c, POP_TOP);
6045 }
6046 // Pop the subject:
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006047 pc->on_top--;
Brandt Bucher145bf262021-02-26 14:51:55 -08006048 ADDOP(c, POP_TOP);
Brandt Bucher145bf262021-02-26 14:51:55 -08006049 return 1;
6050}
6051
Brandt Bucher145bf262021-02-26 14:51:55 -08006052static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006053compiler_pattern_or(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08006054{
6055 assert(p->kind == MatchOr_kind);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006056 basicblock *end;
Brandt Bucher145bf262021-02-26 14:51:55 -08006057 RETURN_IF_FALSE(end = compiler_new_block(c));
Brandt Bucher145bf262021-02-26 14:51:55 -08006058 Py_ssize_t size = asdl_seq_LEN(p->v.MatchOr.patterns);
6059 assert(size > 1);
6060 // We're going to be messing with pc. Keep the original info handy:
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006061 pattern_context old_pc = *pc;
6062 Py_INCREF(pc->stores);
6063 // control is the list of names bound by the first alternative. It is used
6064 // for checking different name bindings in alternatives, and for correcting
6065 // the order in which extracted elements are placed on the stack.
6066 PyObject *control = NULL;
6067 // NOTE: We can't use returning macros anymore! goto error on error.
Brandt Bucher145bf262021-02-26 14:51:55 -08006068 for (Py_ssize_t i = 0; i < size; i++) {
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006069 pattern_ty alt = asdl_seq_GET(p->v.MatchOr.patterns, i);
Brandt Bucher145bf262021-02-26 14:51:55 -08006070 SET_LOC(c, alt);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006071 PyObject *pc_stores = PyList_New(0);
6072 if (pc_stores == NULL) {
6073 goto error;
Brandt Bucher145bf262021-02-26 14:51:55 -08006074 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006075 Py_SETREF(pc->stores, pc_stores);
6076 // An irrefutable sub-pattern must be last, if it is allowed at all:
6077 pc->allow_irrefutable = (i == size - 1) && old_pc.allow_irrefutable;
6078 pc->fail_pop = NULL;
6079 pc->fail_pop_size = 0;
6080 pc->on_top = 0;
6081 if (!compiler_addop(c, DUP_TOP) || !compiler_pattern(c, alt, pc)) {
6082 goto error;
6083 }
6084 // Success!
6085 Py_ssize_t nstores = PyList_GET_SIZE(pc->stores);
Brandt Bucher145bf262021-02-26 14:51:55 -08006086 if (!i) {
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006087 // This is the first alternative, so save its stores as a "control"
6088 // for the others (they can't bind a different set of names, and
6089 // might need to be reordered):
6090 assert(control == NULL);
Brandt Bucher145bf262021-02-26 14:51:55 -08006091 control = pc->stores;
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006092 Py_INCREF(control);
Brandt Bucher145bf262021-02-26 14:51:55 -08006093 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006094 else if (nstores != PyList_GET_SIZE(control)) {
6095 goto diff;
Brandt Bucher145bf262021-02-26 14:51:55 -08006096 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006097 else if (nstores) {
6098 // There were captures. Check to see if we differ from control:
6099 Py_ssize_t icontrol = nstores;
6100 while (icontrol--) {
6101 PyObject *name = PyList_GET_ITEM(control, icontrol);
6102 Py_ssize_t istores = PySequence_Index(pc->stores, name);
6103 if (istores < 0) {
6104 PyErr_Clear();
6105 goto diff;
6106 }
6107 if (icontrol != istores) {
6108 // Reorder the names on the stack to match the order of the
6109 // names in control. There's probably a better way of doing
6110 // this; the current solution is potentially very
6111 // inefficient when each alternative subpattern binds lots
6112 // of names in different orders. It's fine for reasonable
6113 // cases, though.
6114 assert(istores < icontrol);
6115 Py_ssize_t rotations = istores + 1;
6116 // Perfom the same rotation on pc->stores:
6117 PyObject *rotated = PyList_GetSlice(pc->stores, 0,
6118 rotations);
6119 if (rotated == NULL ||
6120 PyList_SetSlice(pc->stores, 0, rotations, NULL) ||
6121 PyList_SetSlice(pc->stores, icontrol - istores,
6122 icontrol - istores, rotated))
6123 {
6124 Py_XDECREF(rotated);
6125 goto error;
6126 }
6127 Py_DECREF(rotated);
6128 // That just did:
6129 // rotated = pc_stores[:rotations]
6130 // del pc_stores[:rotations]
6131 // pc_stores[icontrol-istores:icontrol-istores] = rotated
6132 // Do the same thing to the stack, using several ROT_Ns:
6133 while (rotations--) {
6134 if (!compiler_addop_i(c, ROT_N, icontrol + 1)) {
6135 goto error;
6136 }
6137 }
6138 }
6139 }
6140 }
6141 assert(control);
6142 if (!compiler_addop_j(c, JUMP_FORWARD, end) ||
6143 !compiler_next_block(c) ||
6144 !emit_and_reset_fail_pop(c, pc))
6145 {
6146 goto error;
6147 }
Brandt Bucher145bf262021-02-26 14:51:55 -08006148 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006149 Py_DECREF(pc->stores);
6150 *pc = old_pc;
6151 Py_INCREF(pc->stores);
6152 // Need to NULL this for the PyObject_Free call in the error block.
6153 old_pc.fail_pop = NULL;
6154 // No match. Pop the remaining copy of the subject and fail:
6155 if (!compiler_addop(c, POP_TOP) || !jump_to_fail_pop(c, pc, JUMP_FORWARD)) {
6156 goto error;
6157 }
Brandt Bucher145bf262021-02-26 14:51:55 -08006158 compiler_use_next_block(c, end);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006159 Py_ssize_t nstores = PyList_GET_SIZE(control);
6160 // There's a bunch of stuff on the stack between any where the new stores
6161 // are and where they need to be:
6162 // - The other stores.
6163 // - A copy of the subject.
6164 // - Anything else that may be on top of the stack.
6165 // - Any previous stores we've already stashed away on the stack.
Pablo Galindo39494282021-05-03 16:20:46 +01006166 Py_ssize_t nrots = nstores + 1 + pc->on_top + PyList_GET_SIZE(pc->stores);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006167 for (Py_ssize_t i = 0; i < nstores; i++) {
6168 // Rotate this capture to its proper place on the stack:
6169 if (!compiler_addop_i(c, ROT_N, nrots)) {
6170 goto error;
6171 }
6172 // Update the list of previous stores with this new name, checking for
6173 // duplicates:
6174 PyObject *name = PyList_GET_ITEM(control, i);
6175 int dupe = PySequence_Contains(pc->stores, name);
6176 if (dupe < 0) {
6177 goto error;
6178 }
6179 if (dupe) {
6180 compiler_error_duplicate_store(c, name);
6181 goto error;
6182 }
6183 if (PyList_Append(pc->stores, name)) {
6184 goto error;
6185 }
6186 }
6187 Py_DECREF(old_pc.stores);
6188 Py_DECREF(control);
6189 // NOTE: Returning macros are safe again.
6190 // Pop the copy of the subject:
6191 ADDOP(c, POP_TOP);
Brandt Bucher145bf262021-02-26 14:51:55 -08006192 return 1;
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006193diff:
6194 compiler_error(c, "alternative patterns bind different names");
6195error:
6196 PyObject_Free(old_pc.fail_pop);
6197 Py_DECREF(old_pc.stores);
Brandt Bucher145bf262021-02-26 14:51:55 -08006198 Py_XDECREF(control);
6199 return 0;
6200}
6201
6202
6203static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006204compiler_pattern_sequence(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08006205{
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006206 assert(p->kind == MatchSequence_kind);
6207 asdl_pattern_seq *patterns = p->v.MatchSequence.patterns;
6208 Py_ssize_t size = asdl_seq_LEN(patterns);
Brandt Bucher145bf262021-02-26 14:51:55 -08006209 Py_ssize_t star = -1;
6210 int only_wildcard = 1;
6211 int star_wildcard = 0;
6212 // Find a starred name, if it exists. There may be at most one:
6213 for (Py_ssize_t i = 0; i < size; i++) {
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006214 pattern_ty pattern = asdl_seq_GET(patterns, i);
6215 if (pattern->kind == MatchStar_kind) {
Brandt Bucher145bf262021-02-26 14:51:55 -08006216 if (star >= 0) {
6217 const char *e = "multiple starred names in sequence pattern";
6218 return compiler_error(c, e);
6219 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006220 star_wildcard = WILDCARD_STAR_CHECK(pattern);
6221 only_wildcard &= star_wildcard;
Brandt Bucher145bf262021-02-26 14:51:55 -08006222 star = i;
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006223 continue;
Brandt Bucher145bf262021-02-26 14:51:55 -08006224 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006225 only_wildcard &= WILDCARD_CHECK(pattern);
Brandt Bucher145bf262021-02-26 14:51:55 -08006226 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006227 // We need to keep the subject on top during the sequence and length checks:
6228 pc->on_top++;
Brandt Bucher145bf262021-02-26 14:51:55 -08006229 ADDOP(c, MATCH_SEQUENCE);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006230 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
Brandt Bucher145bf262021-02-26 14:51:55 -08006231 if (star < 0) {
6232 // No star: len(subject) == size
6233 ADDOP(c, GET_LEN);
6234 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size));
6235 ADDOP_COMPARE(c, Eq);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006236 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
Brandt Bucher145bf262021-02-26 14:51:55 -08006237 }
6238 else if (size > 1) {
6239 // Star: len(subject) >= size - 1
6240 ADDOP(c, GET_LEN);
6241 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size - 1));
6242 ADDOP_COMPARE(c, GtE);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006243 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
Brandt Bucher145bf262021-02-26 14:51:55 -08006244 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006245 // Whatever comes next should consume the subject:
6246 pc->on_top--;
Brandt Bucher145bf262021-02-26 14:51:55 -08006247 if (only_wildcard) {
6248 // Patterns like: [] / [_] / [_, _] / [*_] / [_, *_] / [_, _, *_] / etc.
6249 ADDOP(c, POP_TOP);
Brandt Bucher145bf262021-02-26 14:51:55 -08006250 }
6251 else if (star_wildcard) {
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006252 RETURN_IF_FALSE(pattern_helper_sequence_subscr(c, patterns, star, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08006253 }
6254 else {
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006255 RETURN_IF_FALSE(pattern_helper_sequence_unpack(c, patterns, star, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08006256 }
Brandt Bucher145bf262021-02-26 14:51:55 -08006257 return 1;
6258}
6259
Brandt Bucher145bf262021-02-26 14:51:55 -08006260static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006261compiler_pattern_value(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08006262{
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006263 assert(p->kind == MatchValue_kind);
6264 expr_ty value = p->v.MatchValue.value;
6265 if (!MATCH_VALUE_EXPR(value)) {
6266 const char *e = "patterns may only match literals and attribute lookups";
6267 return compiler_error(c, e);
6268 }
6269 VISIT(c, expr, value);
Brandt Bucher145bf262021-02-26 14:51:55 -08006270 ADDOP_COMPARE(c, Eq);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006271 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
Brandt Bucher145bf262021-02-26 14:51:55 -08006272 return 1;
6273}
6274
Brandt Bucher145bf262021-02-26 14:51:55 -08006275static int
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07006276compiler_pattern_singleton(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08006277{
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006278 assert(p->kind == MatchSingleton_kind);
6279 ADDOP_LOAD_CONST(c, p->v.MatchSingleton.value);
6280 ADDOP_COMPARE(c, Is);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006281 RETURN_IF_FALSE(jump_to_fail_pop(c, pc, POP_JUMP_IF_FALSE));
Brandt Bucher145bf262021-02-26 14:51:55 -08006282 return 1;
6283}
6284
Brandt Bucher145bf262021-02-26 14:51:55 -08006285static int
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006286compiler_pattern(struct compiler *c, pattern_ty p, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08006287{
6288 SET_LOC(c, p);
6289 switch (p->kind) {
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006290 case MatchValue_kind:
Brandt Bucher145bf262021-02-26 14:51:55 -08006291 return compiler_pattern_value(c, p, pc);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006292 case MatchSingleton_kind:
Brandt Bucherdbe60ee2021-04-29 17:19:28 -07006293 return compiler_pattern_singleton(c, p, pc);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006294 case MatchSequence_kind:
Brandt Bucher145bf262021-02-26 14:51:55 -08006295 return compiler_pattern_sequence(c, p, pc);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006296 case MatchMapping_kind:
6297 return compiler_pattern_mapping(c, p, pc);
6298 case MatchClass_kind:
6299 return compiler_pattern_class(c, p, pc);
6300 case MatchStar_kind:
6301 return compiler_pattern_star(c, p, pc);
Brandt Bucher145bf262021-02-26 14:51:55 -08006302 case MatchAs_kind:
6303 return compiler_pattern_as(c, p, pc);
6304 case MatchOr_kind:
6305 return compiler_pattern_or(c, p, pc);
Brandt Bucher145bf262021-02-26 14:51:55 -08006306 }
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006307 // AST validator shouldn't let this happen, but if it does,
6308 // just fail, don't crash out of the interpreter
6309 const char *e = "invalid match pattern node in AST (kind=%d)";
6310 return compiler_error(c, e, p->kind);
Brandt Bucher145bf262021-02-26 14:51:55 -08006311}
6312
Brandt Bucher145bf262021-02-26 14:51:55 -08006313static int
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006314compiler_match_inner(struct compiler *c, stmt_ty s, pattern_context *pc)
Brandt Bucher145bf262021-02-26 14:51:55 -08006315{
6316 VISIT(c, expr, s->v.Match.subject);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006317 basicblock *end;
Brandt Bucher145bf262021-02-26 14:51:55 -08006318 RETURN_IF_FALSE(end = compiler_new_block(c));
6319 Py_ssize_t cases = asdl_seq_LEN(s->v.Match.cases);
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006320 assert(cases > 0);
Brandt Bucher145bf262021-02-26 14:51:55 -08006321 match_case_ty m = asdl_seq_GET(s->v.Match.cases, cases - 1);
6322 int has_default = WILDCARD_CHECK(m->pattern) && 1 < cases;
6323 for (Py_ssize_t i = 0; i < cases - has_default; i++) {
6324 m = asdl_seq_GET(s->v.Match.cases, i);
6325 SET_LOC(c, m->pattern);
Brandt Bucher145bf262021-02-26 14:51:55 -08006326 // Only copy the subject if we're *not* on the last case:
6327 if (i != cases - has_default - 1) {
6328 ADDOP(c, DUP_TOP);
6329 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006330 RETURN_IF_FALSE(pc->stores = PyList_New(0));
6331 // Irrefutable cases must be either guarded, last, or both:
6332 pc->allow_irrefutable = m->guard != NULL || i == cases - 1;
6333 pc->fail_pop = NULL;
6334 pc->fail_pop_size = 0;
6335 pc->on_top = 0;
6336 // NOTE: Can't use returning macros here (they'll leak pc->stores)!
6337 if (!compiler_pattern(c, m->pattern, pc)) {
6338 Py_DECREF(pc->stores);
6339 return 0;
6340 }
6341 assert(!pc->on_top);
6342 // It's a match! Store all of the captured names (they're on the stack).
6343 Py_ssize_t nstores = PyList_GET_SIZE(pc->stores);
6344 for (Py_ssize_t n = 0; n < nstores; n++) {
6345 PyObject *name = PyList_GET_ITEM(pc->stores, n);
6346 if (!compiler_nameop(c, name, Store)) {
6347 Py_DECREF(pc->stores);
6348 return 0;
6349 }
6350 }
6351 Py_DECREF(pc->stores);
6352 // NOTE: Returning macros are safe again.
Brandt Bucher145bf262021-02-26 14:51:55 -08006353 if (m->guard) {
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006354 RETURN_IF_FALSE(ensure_fail_pop(c, pc, 0));
6355 RETURN_IF_FALSE(compiler_jump_if(c, m->guard, pc->fail_pop[0], 0));
Brandt Bucher145bf262021-02-26 14:51:55 -08006356 }
6357 // Success! Pop the subject off, we're done with it:
6358 if (i != cases - has_default - 1) {
6359 ADDOP(c, POP_TOP);
6360 }
6361 VISIT_SEQ(c, stmt, m->body);
6362 ADDOP_JUMP(c, JUMP_FORWARD, end);
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006363 RETURN_IF_FALSE(emit_and_reset_fail_pop(c, pc));
Brandt Bucher145bf262021-02-26 14:51:55 -08006364 }
6365 if (has_default) {
6366 if (cases == 1) {
6367 // No matches. Done with the subject:
6368 ADDOP(c, POP_TOP);
6369 }
6370 // A trailing "case _" is common, and lets us save a bit of redundant
6371 // pushing and popping in the loop above:
6372 m = asdl_seq_GET(s->v.Match.cases, cases - 1);
6373 SET_LOC(c, m->pattern);
6374 if (m->guard) {
6375 RETURN_IF_FALSE(compiler_jump_if(c, m->guard, end, 0));
6376 }
6377 VISIT_SEQ(c, stmt, m->body);
6378 }
6379 compiler_use_next_block(c, end);
6380 return 1;
6381}
6382
Brandt Bucher0ad1e032021-05-02 13:02:10 -07006383static int
6384compiler_match(struct compiler *c, stmt_ty s)
6385{
6386 pattern_context pc;
6387 pc.fail_pop = NULL;
6388 int result = compiler_match_inner(c, s, &pc);
6389 PyObject_Free(pc.fail_pop);
6390 return result;
6391}
6392
Brandt Bucher145bf262021-02-26 14:51:55 -08006393#undef WILDCARD_CHECK
Nick Coghlan1e7b8582021-04-29 15:58:44 +10006394#undef WILDCARD_STAR_CHECK
Brandt Bucher145bf262021-02-26 14:51:55 -08006395
Thomas Wouters89f507f2006-12-13 04:49:30 +00006396/* End of the compiler section, beginning of the assembler section */
6397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006398/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07006399 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006400
6401 XXX must handle implicit jumps from one block to next
6402*/
6403
Thomas Wouters89f507f2006-12-13 04:49:30 +00006404struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006405 PyObject *a_bytecode; /* string containing bytecode */
6406 int a_offset; /* offset into bytecode */
6407 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006408 PyObject *a_lnotab; /* string containing lnotab */
6409 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00006410 int a_prevlineno; /* lineno of last emitted line in line table */
6411 int a_lineno; /* lineno of last emitted instruction */
6412 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006413 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00006414};
6415
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006416Py_LOCAL_INLINE(void)
6417stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006418{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02006419 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00006420 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006421 assert(b->b_startdepth < 0);
6422 b->b_startdepth = depth;
6423 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02006424 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006425}
6426
6427/* Find the flow path that needs the largest stack. We assume that
6428 * cycles in the flow graph have no net effect on the stack depth.
6429 */
6430static int
6431stackdepth(struct compiler *c)
6432{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006433 basicblock *b, *entryblock = NULL;
6434 basicblock **stack, **sp;
6435 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006436 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006437 b->b_startdepth = INT_MIN;
6438 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006439 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006440 }
Mark Shannon67969f52021-04-07 10:52:07 +01006441 assert(entryblock!= NULL);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006442 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
6443 if (!stack) {
6444 PyErr_NoMemory();
6445 return -1;
6446 }
6447
6448 sp = stack;
Mark Shannonb37181e2021-04-06 11:48:59 +01006449 if (c->u->u_ste->ste_generator || c->u->u_ste->ste_coroutine) {
6450 stackdepth_push(&sp, entryblock, 1);
6451 } else {
6452 stackdepth_push(&sp, entryblock, 0);
6453 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006454 while (sp != stack) {
6455 b = *--sp;
6456 int depth = b->b_startdepth;
6457 assert(depth >= 0);
6458 basicblock *next = b->b_next;
6459 for (int i = 0; i < b->b_iused; i++) {
6460 struct instr *instr = &b->b_instr[i];
6461 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
6462 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01006463 PyErr_Format(PyExc_SystemError,
6464 "compiler stack_effect(opcode=%d, arg=%i) failed",
6465 instr->i_opcode, instr->i_oparg);
6466 return -1;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006467 }
6468 int new_depth = depth + effect;
6469 if (new_depth > maxdepth) {
6470 maxdepth = new_depth;
6471 }
6472 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01006473 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006474 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
6475 assert(effect != PY_INVALID_STACK_EFFECT);
6476 int target_depth = depth + effect;
6477 if (target_depth > maxdepth) {
6478 maxdepth = target_depth;
6479 }
6480 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006481 stackdepth_push(&sp, instr->i_target, target_depth);
6482 }
6483 depth = new_depth;
6484 if (instr->i_opcode == JUMP_ABSOLUTE ||
6485 instr->i_opcode == JUMP_FORWARD ||
6486 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00006487 instr->i_opcode == RAISE_VARARGS ||
6488 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006489 {
6490 /* remaining code is dead */
6491 next = NULL;
6492 break;
6493 }
6494 }
6495 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00006496 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006497 stackdepth_push(&sp, next, depth);
6498 }
6499 }
6500 PyObject_Free(stack);
6501 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006502}
6503
6504static int
6505assemble_init(struct assembler *a, int nblocks, int firstlineno)
6506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006507 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00006508 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00006509 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006510 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00006511 if (a->a_bytecode == NULL) {
6512 goto error;
6513 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006514 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00006515 if (a->a_lnotab == NULL) {
6516 goto error;
6517 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07006518 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006519 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00006520 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006521 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006522 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00006523error:
6524 Py_XDECREF(a->a_bytecode);
6525 Py_XDECREF(a->a_lnotab);
6526 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006527}
6528
6529static void
6530assemble_free(struct assembler *a)
6531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006532 Py_XDECREF(a->a_bytecode);
6533 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006534}
6535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006536static int
6537blocksize(basicblock *b)
6538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006539 int i;
6540 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006542 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006543 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006544 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006545}
6546
Guido van Rossumf68d8e52001-04-14 17:55:09 +00006547static int
Mark Shannon877df852020-11-12 09:43:29 +00006548assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006549{
Mark Shannon877df852020-11-12 09:43:29 +00006550 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006551 if (a->a_lnotab_off + 2 >= len) {
6552 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
6553 return 0;
6554 }
Pablo Galindo86e322f2021-01-30 13:54:22 +00006555 unsigned char *lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab);
6556 lnotab += a->a_lnotab_off;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006557 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00006558 *lnotab++ = bdelta;
6559 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006560 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006561}
6562
Mark Shannon877df852020-11-12 09:43:29 +00006563/* Appends a range to the end of the line number table. See
6564 * Objects/lnotab_notes.txt for the description of the line number table. */
6565
6566static int
6567assemble_line_range(struct assembler *a)
6568{
6569 int ldelta, bdelta;
6570 bdelta = (a->a_offset - a->a_lineno_start) * 2;
6571 if (bdelta == 0) {
6572 return 1;
6573 }
6574 if (a->a_lineno < 0) {
6575 ldelta = -128;
6576 }
6577 else {
6578 ldelta = a->a_lineno - a->a_prevlineno;
6579 a->a_prevlineno = a->a_lineno;
6580 while (ldelta > 127) {
6581 if (!assemble_emit_linetable_pair(a, 0, 127)) {
6582 return 0;
6583 }
6584 ldelta -= 127;
6585 }
6586 while (ldelta < -127) {
6587 if (!assemble_emit_linetable_pair(a, 0, -127)) {
6588 return 0;
6589 }
6590 ldelta += 127;
6591 }
6592 }
6593 assert(-128 <= ldelta && ldelta < 128);
6594 while (bdelta > 254) {
6595 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
6596 return 0;
6597 }
6598 ldelta = a->a_lineno < 0 ? -128 : 0;
6599 bdelta -= 254;
6600 }
6601 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
6602 return 0;
6603 }
6604 a->a_lineno_start = a->a_offset;
6605 return 1;
6606}
6607
6608static int
6609assemble_lnotab(struct assembler *a, struct instr *i)
6610{
6611 if (i->i_lineno == a->a_lineno) {
6612 return 1;
6613 }
6614 if (!assemble_line_range(a)) {
6615 return 0;
6616 }
6617 a->a_lineno = i->i_lineno;
6618 return 1;
6619}
6620
6621
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006622/* assemble_emit()
6623 Extend the bytecode with a new instruction.
6624 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00006625*/
6626
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00006627static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006628assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00006629{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006630 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006631 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03006632 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006633
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006634 arg = i->i_oparg;
6635 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006636 if (i->i_lineno && !assemble_lnotab(a, i))
6637 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006638 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006639 if (len > PY_SSIZE_T_MAX / 2)
6640 return 0;
6641 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
6642 return 0;
6643 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03006644 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006645 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006646 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006647 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00006648}
6649
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00006650static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006651assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00006652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006653 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006654 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006655 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00006656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006657 /* Compute the size of each block and fixup jump args.
6658 Replace block pointer with position in bytecode. */
6659 do {
6660 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006661 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006662 bsize = blocksize(b);
6663 b->b_offset = totsize;
6664 totsize += bsize;
6665 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006666 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006667 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6668 bsize = b->b_offset;
6669 for (i = 0; i < b->b_iused; i++) {
6670 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006671 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006672 /* Relative jumps are computed relative to
6673 the instruction pointer after fetching
6674 the jump instruction.
6675 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006676 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01006677 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006678 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01006679 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006680 instr->i_oparg -= bsize;
6681 }
6682 if (instrsize(instr->i_oparg) != isize) {
6683 extended_arg_recompile = 1;
6684 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006685 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006686 }
6687 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00006688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006689 /* XXX: This is an awful hack that could hurt performance, but
6690 on the bright side it should work until we come up
6691 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00006692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006693 The issue is that in the first loop blocksize() is called
6694 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006695 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006696 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00006697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006698 So we loop until we stop seeing new EXTENDED_ARGs.
6699 The only EXTENDED_ARGs that could be popping up are
6700 ones in jump instructions. So this should converge
6701 fairly quickly.
6702 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006703 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00006704}
6705
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006706static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01006707dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006709 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006710 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006712 tuple = PyTuple_New(size);
6713 if (tuple == NULL)
6714 return NULL;
6715 while (PyDict_Next(dict, &pos, &k, &v)) {
6716 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006717 Py_INCREF(k);
6718 assert((i - offset) < size);
6719 assert((i - offset) >= 0);
6720 PyTuple_SET_ITEM(tuple, i - offset, k);
6721 }
6722 return tuple;
6723}
6724
6725static PyObject *
6726consts_dict_keys_inorder(PyObject *dict)
6727{
6728 PyObject *consts, *k, *v;
6729 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
6730
6731 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
6732 if (consts == NULL)
6733 return NULL;
6734 while (PyDict_Next(dict, &pos, &k, &v)) {
6735 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03006736 /* The keys of the dictionary can be tuples wrapping a contant.
6737 * (see compiler_add_o and _PyCode_ConstantKey). In that case
6738 * the object we want is always second. */
6739 if (PyTuple_CheckExact(k)) {
6740 k = PyTuple_GET_ITEM(k, 1);
6741 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006742 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006743 assert(i < size);
6744 assert(i >= 0);
6745 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006746 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006747 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006748}
6749
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006750static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006751compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006753 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006754 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006755 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04006756 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006757 if (ste->ste_nested)
6758 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07006759 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006760 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07006761 if (!ste->ste_generator && ste->ste_coroutine)
6762 flags |= CO_COROUTINE;
6763 if (ste->ste_generator && ste->ste_coroutine)
6764 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006765 if (ste->ste_varargs)
6766 flags |= CO_VARARGS;
6767 if (ste->ste_varkeywords)
6768 flags |= CO_VARKEYWORDS;
6769 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00006770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006771 /* (Only) inherit compilerflags in PyCF_MASK */
6772 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00006773
Pablo Galindo90235812020-03-15 04:29:22 +00006774 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07006775 ste->ste_coroutine &&
6776 !ste->ste_generator) {
6777 flags |= CO_COROUTINE;
6778 }
6779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006780 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00006781}
6782
Inada Naokibdb941b2021-02-10 09:20:42 +09006783// Merge *obj* with constant cache.
INADA Naokic2e16072018-11-26 21:23:22 +09006784// Unlike merge_consts_recursive(), this function doesn't work recursively.
6785static int
Inada Naokibdb941b2021-02-10 09:20:42 +09006786merge_const_one(struct compiler *c, PyObject **obj)
INADA Naokic2e16072018-11-26 21:23:22 +09006787{
Inada Naokibdb941b2021-02-10 09:20:42 +09006788 PyObject *key = _PyCode_ConstantKey(*obj);
INADA Naokic2e16072018-11-26 21:23:22 +09006789 if (key == NULL) {
6790 return 0;
6791 }
6792
6793 // t is borrowed reference
6794 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
6795 Py_DECREF(key);
6796 if (t == NULL) {
6797 return 0;
6798 }
Inada Naokibdb941b2021-02-10 09:20:42 +09006799 if (t == key) { // obj is new constant.
INADA Naokic2e16072018-11-26 21:23:22 +09006800 return 1;
6801 }
6802
Inada Naokibdb941b2021-02-10 09:20:42 +09006803 if (PyTuple_CheckExact(t)) {
6804 // t is still borrowed reference
6805 t = PyTuple_GET_ITEM(t, 1);
6806 }
6807
6808 Py_INCREF(t);
6809 Py_DECREF(*obj);
6810 *obj = t;
INADA Naokic2e16072018-11-26 21:23:22 +09006811 return 1;
6812}
6813
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006814static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01006815makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006817 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006818 PyObject *names = NULL;
6819 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006820 PyObject *name = NULL;
6821 PyObject *freevars = NULL;
6822 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006823 Py_ssize_t nlocals;
6824 int nlocals_int;
6825 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01006826 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006828 names = dict_keys_inorder(c->u->u_names, 0);
6829 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006830 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006831 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006832 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006833 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
6834 if (!cellvars)
6835 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006836 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006837 if (!freevars)
6838 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006839
Inada Naokibdb941b2021-02-10 09:20:42 +09006840 if (!merge_const_one(c, &names) ||
6841 !merge_const_one(c, &varnames) ||
6842 !merge_const_one(c, &cellvars) ||
6843 !merge_const_one(c, &freevars))
INADA Naokic2e16072018-11-26 21:23:22 +09006844 {
6845 goto error;
6846 }
6847
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006848 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01006849 assert(nlocals < INT_MAX);
6850 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
6851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006852 flags = compute_code_flags(c);
6853 if (flags < 0)
6854 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006855
Mark Shannon6e8128f2020-07-30 10:03:00 +01006856 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
6857 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006858 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006859 }
Inada Naokibdb941b2021-02-10 09:20:42 +09006860 if (!merge_const_one(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006861 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09006862 goto error;
6863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006864
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01006865 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01006866 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01006867 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006868 maxdepth = stackdepth(c);
6869 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006870 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006871 goto error;
6872 }
Mark Shannon11e0b292021-04-15 14:28:56 +01006873 if (maxdepth > MAX_ALLOWED_STACK_USE) {
6874 PyErr_Format(PyExc_SystemError,
6875 "excessive stack use: stack is %d deep",
6876 maxdepth);
6877 Py_DECREF(consts);
6878 goto error;
6879 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006880 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00006881 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01006882 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006883 varnames, freevars, cellvars, c->c_filename,
6884 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006885 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006886 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006887 Py_XDECREF(names);
6888 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006889 Py_XDECREF(name);
6890 Py_XDECREF(freevars);
6891 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006892 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006893}
6894
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006895
6896/* For debugging purposes only */
6897#if 0
6898static void
6899dump_instr(const struct instr *i)
6900{
Mark Shannon582aaf12020-08-04 17:30:11 +01006901 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
6902 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006903 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006905 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006906 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006907 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006908 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006909 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6910 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006911}
6912
6913static void
6914dump_basicblock(const basicblock *b)
6915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006916 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01006917 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
6918 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006919 if (b->b_instr) {
6920 int i;
6921 for (i = 0; i < b->b_iused; i++) {
6922 fprintf(stderr, " [%02d] ", i);
6923 dump_instr(b->b_instr + i);
6924 }
6925 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006926}
6927#endif
6928
Mark Shannon5977a792020-12-02 13:31:40 +00006929
6930static int
6931normalize_basic_block(basicblock *bb);
6932
Mark Shannon6e8128f2020-07-30 10:03:00 +01006933static int
Inada Naoki8a232c72021-04-16 14:01:04 +09006934optimize_cfg(struct compiler *c, struct assembler *a, PyObject *consts);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006935
Mark Shannon5977a792020-12-02 13:31:40 +00006936static int
6937ensure_exits_have_lineno(struct compiler *c);
6938
Mark Shannonb37181e2021-04-06 11:48:59 +01006939static int
6940insert_generator_prefix(struct compiler *c, basicblock *entryblock) {
6941
6942 int flags = compute_code_flags(c);
6943 if (flags < 0) {
6944 return -1;
6945 }
6946 int kind;
6947 if (flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
6948 if (flags & CO_COROUTINE) {
6949 kind = 1;
6950 }
6951 else if (flags & CO_ASYNC_GENERATOR) {
6952 kind = 2;
6953 }
6954 else {
6955 kind = 0;
6956 }
6957 }
6958 else {
6959 return 0;
6960 }
6961 if (compiler_next_instr(entryblock) < 0) {
6962 return -1;
6963 }
6964 for (int i = entryblock->b_iused-1; i > 0; i--) {
6965 entryblock->b_instr[i] = entryblock->b_instr[i-1];
6966 }
6967 entryblock->b_instr[0].i_opcode = GEN_START;
6968 entryblock->b_instr[0].i_oparg = kind;
6969 entryblock->b_instr[0].i_lineno = -1;
6970 entryblock->b_instr[0].i_target = NULL;
6971 return 0;
6972}
6973
Mark Shannon0acdf252021-05-13 14:11:41 +01006974/* Make sure that all returns have a line number, even if early passes
6975 * have failed to propagate a correct line number.
6976 * The resulting line number may not be correct according to PEP 626,
6977 * but should be "good enough", and no worse than in older versions. */
6978static void
6979guarantee_lineno_for_exits(struct assembler *a, int firstlineno) {
6980 int lineno = firstlineno;
6981 assert(lineno > 0);
6982 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6983 if (b->b_iused == 0) {
6984 continue;
6985 }
6986 struct instr *last = &b->b_instr[b->b_iused-1];
6987 if (last->i_lineno < 0) {
6988 if (last->i_opcode == RETURN_VALUE)
6989 {
6990 for (int i = 0; i < b->b_iused; i++) {
6991 assert(b->b_instr[i].i_lineno < 0);
6992 b->b_instr[i].i_lineno = lineno;
6993 }
6994 }
6995 }
6996 else {
6997 lineno = last->i_lineno;
6998 }
6999 }
7000}
7001
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007002static PyCodeObject *
7003assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00007004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007005 basicblock *b, *entryblock;
7006 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007007 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007008 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007009 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00007010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007011 /* Make sure every block that falls off the end returns None.
7012 XXX NEXT_BLOCK() isn't quite right, because if the last
7013 block ends with a jump or return b_next shouldn't set.
7014 */
7015 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00007016 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007017 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03007018 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007019 ADDOP(c, RETURN_VALUE);
7020 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00007021
Mark Shannon5977a792020-12-02 13:31:40 +00007022 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7023 if (normalize_basic_block(b)) {
Alex Henrie503627f2021-03-02 03:20:25 -07007024 return NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00007025 }
7026 }
7027
7028 if (ensure_exits_have_lineno(c)) {
Alex Henrie503627f2021-03-02 03:20:25 -07007029 return NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00007030 }
7031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007032 nblocks = 0;
7033 entryblock = NULL;
7034 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
7035 nblocks++;
7036 entryblock = b;
7037 }
Mark Shannon67969f52021-04-07 10:52:07 +01007038 assert(entryblock != NULL);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00007039
Mark Shannonb37181e2021-04-06 11:48:59 +01007040 if (insert_generator_prefix(c, entryblock)) {
7041 goto error;
7042 }
7043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007044 /* Set firstlineno if it wasn't explicitly set. */
7045 if (!c->u->u_firstlineno) {
Mark Shannon67969f52021-04-07 10:52:07 +01007046 if (entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007047 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00007048 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007049 c->u->u_firstlineno = 1;
7050 }
Mark Shannon5977a792020-12-02 13:31:40 +00007051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007052 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
7053 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007054 a.a_entry = entryblock;
7055 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00007056
Mark Shannon6e8128f2020-07-30 10:03:00 +01007057 consts = consts_dict_keys_inorder(c->u->u_consts);
7058 if (consts == NULL) {
7059 goto error;
7060 }
Inada Naoki8a232c72021-04-16 14:01:04 +09007061 if (optimize_cfg(c, &a, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007062 goto error;
7063 }
Mark Shannon0acdf252021-05-13 14:11:41 +01007064 guarantee_lineno_for_exits(&a, c->u->u_firstlineno);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007066 /* Can't modify the bytecode after computing jump offsets. */
7067 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00007068
Mark Shannoncc75ab72020-11-12 19:49:33 +00007069 /* Emit code. */
7070 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007071 for (j = 0; j < b->b_iused; j++)
7072 if (!assemble_emit(&a, &b->b_instr[j]))
7073 goto error;
7074 }
Mark Shannon877df852020-11-12 09:43:29 +00007075 if (!assemble_line_range(&a)) {
7076 return 0;
7077 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00007078
Inada Naokibdb941b2021-02-10 09:20:42 +09007079 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007080 goto error;
Inada Naokibdb941b2021-02-10 09:20:42 +09007081 }
7082 if (!merge_const_one(c, &a.a_lnotab)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007083 goto error;
Inada Naokibdb941b2021-02-10 09:20:42 +09007084 }
7085 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0) {
7086 goto error;
7087 }
7088 if (!merge_const_one(c, &a.a_bytecode)) {
7089 goto error;
7090 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00007091
Mark Shannon6e8128f2020-07-30 10:03:00 +01007092 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00007093 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01007094 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00007095 assemble_free(&a);
7096 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00007097}
Georg Brandl8334fd92010-12-04 10:26:46 +00007098
Mark Shannon6e8128f2020-07-30 10:03:00 +01007099/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
7100 with LOAD_CONST (c1, c2, ... cn).
7101 The consts table must still be in list form so that the
7102 new constant (c1, c2, ... cn) can be appended.
7103 Called with codestr pointing to the first LOAD_CONST.
7104*/
7105static int
Inada Naoki8a232c72021-04-16 14:01:04 +09007106fold_tuple_on_constants(struct compiler *c,
7107 struct instr *inst,
Mark Shannon6e8128f2020-07-30 10:03:00 +01007108 int n, PyObject *consts)
7109{
7110 /* Pre-conditions */
7111 assert(PyList_CheckExact(consts));
7112 assert(inst[n].i_opcode == BUILD_TUPLE);
7113 assert(inst[n].i_oparg == n);
7114
7115 for (int i = 0; i < n; i++) {
7116 if (inst[i].i_opcode != LOAD_CONST) {
7117 return 0;
7118 }
7119 }
7120
7121 /* Buildup new tuple of constants */
7122 PyObject *newconst = PyTuple_New(n);
7123 if (newconst == NULL) {
7124 return -1;
7125 }
7126 for (int i = 0; i < n; i++) {
7127 int arg = inst[i].i_oparg;
7128 PyObject *constant = PyList_GET_ITEM(consts, arg);
7129 Py_INCREF(constant);
7130 PyTuple_SET_ITEM(newconst, i, constant);
7131 }
Inada Naoki8a232c72021-04-16 14:01:04 +09007132 if (merge_const_one(c, &newconst) == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007133 Py_DECREF(newconst);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007134 return -1;
7135 }
Inada Naoki8a232c72021-04-16 14:01:04 +09007136
7137 Py_ssize_t index;
7138 for (index = 0; index < PyList_GET_SIZE(consts); index++) {
7139 if (PyList_GET_ITEM(consts, index) == newconst) {
7140 break;
7141 }
7142 }
7143 if (index == PyList_GET_SIZE(consts)) {
7144 if ((size_t)index >= (size_t)INT_MAX - 1) {
7145 Py_DECREF(newconst);
7146 PyErr_SetString(PyExc_OverflowError, "too many constants");
7147 return -1;
7148 }
7149 if (PyList_Append(consts, newconst)) {
7150 Py_DECREF(newconst);
7151 return -1;
7152 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007153 }
7154 Py_DECREF(newconst);
7155 for (int i = 0; i < n; i++) {
7156 inst[i].i_opcode = NOP;
7157 }
7158 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02007159 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007160 return 0;
7161}
7162
Mark Shannon28b75c82020-12-23 11:43:10 +00007163
Brandt Bucher0ad1e032021-05-02 13:02:10 -07007164// Eliminate n * ROT_N(n).
7165static void
7166fold_rotations(struct instr *inst, int n)
7167{
7168 for (int i = 0; i < n; i++) {
7169 int rot;
7170 switch (inst[i].i_opcode) {
7171 case ROT_N:
7172 rot = inst[i].i_oparg;
7173 break;
7174 case ROT_FOUR:
7175 rot = 4;
7176 break;
7177 case ROT_THREE:
7178 rot = 3;
7179 break;
7180 case ROT_TWO:
7181 rot = 2;
7182 break;
7183 default:
7184 return;
7185 }
7186 if (rot != n) {
7187 return;
7188 }
7189 }
7190 for (int i = 0; i < n; i++) {
7191 inst[i].i_opcode = NOP;
7192 }
7193}
7194
7195
Mark Shannon28b75c82020-12-23 11:43:10 +00007196static int
7197eliminate_jump_to_jump(basicblock *bb, int opcode) {
7198 assert (bb->b_iused > 0);
7199 struct instr *inst = &bb->b_instr[bb->b_iused-1];
7200 assert (is_jump(inst));
7201 assert (inst->i_target->b_iused > 0);
7202 struct instr *target = &inst->i_target->b_instr[0];
7203 if (inst->i_target == target->i_target) {
7204 /* Nothing to do */
7205 return 0;
7206 }
7207 int lineno = target->i_lineno;
7208 if (add_jump_to_block(bb, opcode, lineno, target->i_target) == 0) {
7209 return -1;
7210 }
7211 assert (bb->b_iused >= 2);
7212 bb->b_instr[bb->b_iused-2].i_opcode = NOP;
7213 return 0;
7214}
7215
Mark Shannoncc75ab72020-11-12 19:49:33 +00007216/* Maximum size of basic block that should be copied in optimizer */
7217#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01007218
7219/* Optimization */
7220static int
Inada Naoki8a232c72021-04-16 14:01:04 +09007221optimize_basic_block(struct compiler *c, basicblock *bb, PyObject *consts)
Mark Shannon6e8128f2020-07-30 10:03:00 +01007222{
7223 assert(PyList_CheckExact(consts));
7224 struct instr nop;
7225 nop.i_opcode = NOP;
7226 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007227 for (int i = 0; i < bb->b_iused; i++) {
7228 struct instr *inst = &bb->b_instr[i];
7229 int oparg = inst->i_oparg;
7230 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01007231 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007232 /* Skip over empty basic blocks. */
7233 while (inst->i_target->b_iused == 0) {
7234 inst->i_target = inst->i_target->b_next;
7235 }
7236 target = &inst->i_target->b_instr[0];
7237 }
7238 else {
7239 target = &nop;
7240 }
7241 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00007242 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01007243 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00007244 {
7245 PyObject* cnt;
7246 int is_true;
7247 int jump_if_true;
7248 switch(nextop) {
7249 case POP_JUMP_IF_FALSE:
7250 case POP_JUMP_IF_TRUE:
7251 cnt = PyList_GET_ITEM(consts, oparg);
7252 is_true = PyObject_IsTrue(cnt);
7253 if (is_true == -1) {
7254 goto error;
7255 }
7256 inst->i_opcode = NOP;
7257 jump_if_true = nextop == POP_JUMP_IF_TRUE;
7258 if (is_true == jump_if_true) {
7259 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
7260 bb->b_nofallthrough = 1;
7261 }
7262 else {
7263 bb->b_instr[i+1].i_opcode = NOP;
7264 }
7265 break;
7266 case JUMP_IF_FALSE_OR_POP:
7267 case JUMP_IF_TRUE_OR_POP:
7268 cnt = PyList_GET_ITEM(consts, oparg);
7269 is_true = PyObject_IsTrue(cnt);
7270 if (is_true == -1) {
7271 goto error;
7272 }
7273 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
7274 if (is_true == jump_if_true) {
7275 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
7276 bb->b_nofallthrough = 1;
7277 }
7278 else {
7279 inst->i_opcode = NOP;
7280 bb->b_instr[i+1].i_opcode = NOP;
7281 }
7282 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007283 }
7284 break;
Mark Shannon266b4622020-11-17 19:30:14 +00007285 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007286
7287 /* Try to fold tuples of constants.
7288 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
7289 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
7290 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
7291 case BUILD_TUPLE:
7292 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
7293 switch(oparg) {
7294 case 1:
7295 inst->i_opcode = NOP;
7296 bb->b_instr[i+1].i_opcode = NOP;
7297 break;
7298 case 2:
7299 inst->i_opcode = ROT_TWO;
7300 bb->b_instr[i+1].i_opcode = NOP;
7301 break;
7302 case 3:
7303 inst->i_opcode = ROT_THREE;
7304 bb->b_instr[i+1].i_opcode = ROT_TWO;
7305 }
7306 break;
7307 }
7308 if (i >= oparg) {
Inada Naoki8a232c72021-04-16 14:01:04 +09007309 if (fold_tuple_on_constants(c, inst-oparg, oparg, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007310 goto error;
7311 }
7312 }
7313 break;
7314
7315 /* Simplify conditional jump to conditional jump where the
7316 result of the first test implies the success of a similar
7317 test or the failure of the opposite test.
7318 Arises in code like:
7319 "a and b or c"
7320 "(a and b) and c"
7321 "(a or b) or c"
7322 "(a or b) and c"
7323 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
7324 --> x:JUMP_IF_FALSE_OR_POP z
7325 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
7326 --> x:POP_JUMP_IF_FALSE y+1
7327 where y+1 is the instruction following the second test.
7328 */
7329 case JUMP_IF_FALSE_OR_POP:
7330 switch(target->i_opcode) {
7331 case POP_JUMP_IF_FALSE:
Mark Shannon28b75c82020-12-23 11:43:10 +00007332 if (inst->i_lineno == target->i_lineno) {
7333 *inst = *target;
7334 i--;
7335 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007336 break;
7337 case JUMP_ABSOLUTE:
7338 case JUMP_FORWARD:
7339 case JUMP_IF_FALSE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00007340 if (inst->i_lineno == target->i_lineno &&
7341 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00007342 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007343 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007344 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007345 break;
7346 case JUMP_IF_TRUE_OR_POP:
7347 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00007348 if (inst->i_lineno == target->i_lineno) {
7349 inst->i_opcode = POP_JUMP_IF_FALSE;
7350 inst->i_target = inst->i_target->b_next;
7351 --i;
7352 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007353 break;
7354 }
7355 break;
7356
7357 case JUMP_IF_TRUE_OR_POP:
7358 switch(target->i_opcode) {
7359 case POP_JUMP_IF_TRUE:
Mark Shannon28b75c82020-12-23 11:43:10 +00007360 if (inst->i_lineno == target->i_lineno) {
7361 *inst = *target;
7362 i--;
7363 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007364 break;
7365 case JUMP_ABSOLUTE:
7366 case JUMP_FORWARD:
7367 case JUMP_IF_TRUE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00007368 if (inst->i_lineno == target->i_lineno &&
7369 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00007370 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007371 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007372 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007373 break;
7374 case JUMP_IF_FALSE_OR_POP:
7375 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00007376 if (inst->i_lineno == target->i_lineno) {
7377 inst->i_opcode = POP_JUMP_IF_TRUE;
7378 inst->i_target = inst->i_target->b_next;
7379 --i;
7380 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007381 break;
7382 }
7383 break;
7384
7385 case POP_JUMP_IF_FALSE:
7386 switch(target->i_opcode) {
7387 case JUMP_ABSOLUTE:
7388 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007389 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00007390 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007391 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007392 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007393 break;
7394 }
7395 break;
7396
7397 case POP_JUMP_IF_TRUE:
7398 switch(target->i_opcode) {
7399 case JUMP_ABSOLUTE:
7400 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007401 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00007402 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007403 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007404 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007405 break;
7406 }
7407 break;
7408
7409 case JUMP_ABSOLUTE:
7410 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007411 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007412 switch(target->i_opcode) {
7413 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007414 if (eliminate_jump_to_jump(bb, inst->i_opcode)) {
7415 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00007416 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007417 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00007418
Mark Shannon6e8128f2020-07-30 10:03:00 +01007419 case JUMP_ABSOLUTE:
Mark Shannon28b75c82020-12-23 11:43:10 +00007420 if (eliminate_jump_to_jump(bb, JUMP_ABSOLUTE)) {
7421 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00007422 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007423 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00007424 default:
7425 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
7426 basicblock *to_copy = inst->i_target;
7427 inst->i_opcode = NOP;
7428 for (i = 0; i < to_copy->b_iused; i++) {
7429 int index = compiler_next_instr(bb);
7430 if (index < 0) {
7431 return -1;
7432 }
7433 bb->b_instr[index] = to_copy->b_instr[i];
7434 }
7435 bb->b_exit = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007436 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00007437 }
Brandt Bucher0ad1e032021-05-02 13:02:10 -07007438 break;
7439 case ROT_N:
7440 switch (oparg) {
7441 case 0:
7442 case 1:
7443 inst->i_opcode = NOP;
7444 continue;
7445 case 2:
7446 inst->i_opcode = ROT_TWO;
7447 break;
7448 case 3:
7449 inst->i_opcode = ROT_THREE;
7450 break;
7451 case 4:
7452 inst->i_opcode = ROT_FOUR;
7453 break;
7454 }
7455 if (i >= oparg - 1) {
7456 fold_rotations(inst - oparg + 1, oparg);
7457 }
7458 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007459 }
7460 }
7461 return 0;
7462error:
7463 return -1;
7464}
7465
7466
7467static void
Mark Shannon1659ad12021-01-13 15:05:04 +00007468clean_basic_block(basicblock *bb, int prev_lineno) {
7469 /* Remove NOPs when legal to do so. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01007470 int dest = 0;
7471 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00007472 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007473 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00007474 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007475 if (lineno < 0) {
7476 continue;
7477 }
Mark Shannon266b4622020-11-17 19:30:14 +00007478 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007479 if (prev_lineno == lineno) {
7480 continue;
7481 }
Mark Shannon266b4622020-11-17 19:30:14 +00007482 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007483 if (src < bb->b_iused - 1) {
7484 int next_lineno = bb->b_instr[src+1].i_lineno;
7485 if (next_lineno < 0 || next_lineno == lineno) {
7486 bb->b_instr[src+1].i_lineno = lineno;
7487 continue;
Mark Shannon877df852020-11-12 09:43:29 +00007488 }
7489 }
Mark Shannon266b4622020-11-17 19:30:14 +00007490 else {
7491 basicblock* next = bb->b_next;
7492 while (next && next->b_iused == 0) {
7493 next = next->b_next;
7494 }
7495 /* or if last instruction in BB and next BB has same line number */
7496 if (next) {
7497 if (lineno == next->b_instr[0].i_lineno) {
7498 continue;
7499 }
7500 }
7501 }
7502
Mark Shannon6e8128f2020-07-30 10:03:00 +01007503 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00007504 if (dest != src) {
7505 bb->b_instr[dest] = bb->b_instr[src];
7506 }
7507 dest++;
7508 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007509 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007510 assert(dest <= bb->b_iused);
7511 bb->b_iused = dest;
7512}
7513
Mark Shannon266b4622020-11-17 19:30:14 +00007514static int
7515normalize_basic_block(basicblock *bb) {
7516 /* Mark blocks as exit and/or nofallthrough.
7517 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007518 for (int i = 0; i < bb->b_iused; i++) {
7519 switch(bb->b_instr[i].i_opcode) {
7520 case RETURN_VALUE:
7521 case RAISE_VARARGS:
7522 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007523 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00007524 bb->b_nofallthrough = 1;
7525 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007526 case JUMP_ABSOLUTE:
7527 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007528 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00007529 /* fall through */
7530 case POP_JUMP_IF_FALSE:
7531 case POP_JUMP_IF_TRUE:
7532 case JUMP_IF_FALSE_OR_POP:
7533 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00007534 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00007535 if (i != bb->b_iused-1) {
7536 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
7537 return -1;
7538 }
Mark Shannon5977a792020-12-02 13:31:40 +00007539 /* Skip over empty basic blocks. */
7540 while (bb->b_instr[i].i_target->b_iused == 0) {
7541 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
7542 }
7543
Mark Shannoncc75ab72020-11-12 19:49:33 +00007544 }
7545 }
Mark Shannon266b4622020-11-17 19:30:14 +00007546 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007547}
7548
Mark Shannon6e8128f2020-07-30 10:03:00 +01007549static int
7550mark_reachable(struct assembler *a) {
7551 basicblock **stack, **sp;
7552 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
7553 if (stack == NULL) {
7554 return -1;
7555 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007556 a->a_entry->b_predecessors = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007557 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007558 while (sp > stack) {
7559 basicblock *b = *(--sp);
Mark Shannon3bd60352021-01-13 12:05:43 +00007560 if (b->b_next && !b->b_nofallthrough) {
7561 if (b->b_next->b_predecessors == 0) {
7562 *sp++ = b->b_next;
7563 }
7564 b->b_next->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007565 }
7566 for (int i = 0; i < b->b_iused; i++) {
7567 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01007568 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007569 target = b->b_instr[i].i_target;
Mark Shannon3bd60352021-01-13 12:05:43 +00007570 if (target->b_predecessors == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007571 *sp++ = target;
7572 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007573 target->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007574 }
7575 }
7576 }
7577 PyObject_Free(stack);
7578 return 0;
7579}
7580
Mark Shannon3bd60352021-01-13 12:05:43 +00007581static void
7582eliminate_empty_basic_blocks(basicblock *entry) {
7583 /* Eliminate empty blocks */
7584 for (basicblock *b = entry; b != NULL; b = b->b_next) {
7585 basicblock *next = b->b_next;
7586 if (next) {
7587 while (next->b_iused == 0 && next->b_next) {
7588 next = next->b_next;
7589 }
7590 b->b_next = next;
7591 }
7592 }
7593 for (basicblock *b = entry; b != NULL; b = b->b_next) {
7594 if (b->b_iused == 0) {
7595 continue;
7596 }
7597 if (is_jump(&b->b_instr[b->b_iused-1])) {
7598 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7599 while (target->b_iused == 0) {
7600 target = target->b_next;
7601 }
7602 b->b_instr[b->b_iused-1].i_target = target;
7603 }
7604 }
7605}
7606
7607
Mark Shannon5977a792020-12-02 13:31:40 +00007608/* If an instruction has no line number, but it's predecessor in the BB does,
Mark Shannon3bd60352021-01-13 12:05:43 +00007609 * then copy the line number. If a successor block has no line number, and only
7610 * one predecessor, then inherit the line number.
7611 * This ensures that all exit blocks (with one predecessor) receive a line number.
7612 * Also reduces the size of the line number table,
Mark Shannon5977a792020-12-02 13:31:40 +00007613 * but has no impact on the generated line number events.
7614 */
7615static void
Mark Shannon3bd60352021-01-13 12:05:43 +00007616propogate_line_numbers(struct assembler *a) {
Mark Shannon5977a792020-12-02 13:31:40 +00007617 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007618 if (b->b_iused == 0) {
7619 continue;
7620 }
Mark Shannon5977a792020-12-02 13:31:40 +00007621 int prev_lineno = -1;
7622 for (int i = 0; i < b->b_iused; i++) {
7623 if (b->b_instr[i].i_lineno < 0) {
7624 b->b_instr[i].i_lineno = prev_lineno;
7625 }
7626 else {
7627 prev_lineno = b->b_instr[i].i_lineno;
7628 }
7629 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007630 if (!b->b_nofallthrough && b->b_next->b_predecessors == 1) {
7631 assert(b->b_next->b_iused);
7632 if (b->b_next->b_instr[0].i_lineno < 0) {
7633 b->b_next->b_instr[0].i_lineno = prev_lineno;
7634 }
7635 }
7636 if (is_jump(&b->b_instr[b->b_iused-1])) {
7637 switch (b->b_instr[b->b_iused-1].i_opcode) {
7638 /* Note: Only actual jumps, not exception handlers */
7639 case SETUP_ASYNC_WITH:
7640 case SETUP_WITH:
7641 case SETUP_FINALLY:
7642 continue;
7643 }
7644 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7645 if (target->b_predecessors == 1) {
7646 if (target->b_instr[0].i_lineno < 0) {
7647 target->b_instr[0].i_lineno = prev_lineno;
7648 }
7649 }
7650 }
Mark Shannon5977a792020-12-02 13:31:40 +00007651 }
7652}
7653
7654/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01007655 The consts object should still be in list form to allow new constants
7656 to be appended.
7657
7658 All transformations keep the code size the same or smaller.
7659 For those that reduce size, the gaps are initially filled with
7660 NOPs. Later those NOPs are removed.
7661*/
7662
7663static int
Inada Naoki8a232c72021-04-16 14:01:04 +09007664optimize_cfg(struct compiler *c, struct assembler *a, PyObject *consts)
Mark Shannon6e8128f2020-07-30 10:03:00 +01007665{
Mark Shannoncc75ab72020-11-12 19:49:33 +00007666 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Inada Naoki8a232c72021-04-16 14:01:04 +09007667 if (optimize_basic_block(c, b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007668 return -1;
7669 }
Mark Shannon1659ad12021-01-13 15:05:04 +00007670 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00007671 assert(b->b_predecessors == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007672 }
7673 if (mark_reachable(a)) {
7674 return -1;
7675 }
7676 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007677 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007678 if (b->b_predecessors == 0) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00007679 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05307680 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007681 }
7682 }
Mark Shannon1659ad12021-01-13 15:05:04 +00007683 basicblock *pred = NULL;
7684 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
7685 int prev_lineno = -1;
7686 if (pred && pred->b_iused) {
7687 prev_lineno = pred->b_instr[pred->b_iused-1].i_lineno;
7688 }
7689 clean_basic_block(b, prev_lineno);
7690 pred = b->b_nofallthrough ? NULL : b;
7691 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007692 eliminate_empty_basic_blocks(a->a_entry);
Om Gc71581c2020-12-16 17:48:05 +05307693 /* Delete jump instructions made redundant by previous step. If a non-empty
7694 block ends with a jump instruction, check if the next non-empty block
7695 reached through normal flow control is the target of that jump. If it
7696 is, then the jump instruction is redundant and can be deleted.
7697 */
Mark Shannon3bd60352021-01-13 12:05:43 +00007698 int maybe_empty_blocks = 0;
Om Gc71581c2020-12-16 17:48:05 +05307699 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
7700 if (b->b_iused > 0) {
7701 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
Mark Shannon802b6452021-02-02 14:59:15 +00007702 if (b_last_instr->i_opcode == JUMP_ABSOLUTE ||
Om Gc71581c2020-12-16 17:48:05 +05307703 b_last_instr->i_opcode == JUMP_FORWARD) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007704 if (b_last_instr->i_target == b->b_next) {
7705 assert(b->b_next->b_iused);
Om Gc71581c2020-12-16 17:48:05 +05307706 b->b_nofallthrough = 0;
Mark Shannon802b6452021-02-02 14:59:15 +00007707 b_last_instr->i_opcode = NOP;
7708 clean_basic_block(b, -1);
7709 maybe_empty_blocks = 1;
Om Gc71581c2020-12-16 17:48:05 +05307710 }
7711 }
7712 }
7713 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007714 if (maybe_empty_blocks) {
7715 eliminate_empty_basic_blocks(a->a_entry);
7716 }
7717 propogate_line_numbers(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007718 return 0;
7719}
7720
Mark Shannon5977a792020-12-02 13:31:40 +00007721static inline int
7722is_exit_without_lineno(basicblock *b) {
7723 return b->b_exit && b->b_instr[0].i_lineno < 0;
7724}
7725
7726/* PEP 626 mandates that the f_lineno of a frame is correct
7727 * after a frame terminates. It would be prohibitively expensive
7728 * to continuously update the f_lineno field at runtime,
7729 * so we make sure that all exiting instruction (raises and returns)
7730 * have a valid line number, allowing us to compute f_lineno lazily.
7731 * We can do this by duplicating the exit blocks without line number
7732 * so that none have more than one predecessor. We can then safely
7733 * copy the line number from the sole predecessor block.
7734 */
7735static int
7736ensure_exits_have_lineno(struct compiler *c)
7737{
Mark Shannoneaccc122020-12-04 15:22:12 +00007738 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00007739 /* Copy all exit blocks without line number that are targets of a jump.
7740 */
7741 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7742 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
7743 switch (b->b_instr[b->b_iused-1].i_opcode) {
7744 /* Note: Only actual jumps, not exception handlers */
7745 case SETUP_ASYNC_WITH:
7746 case SETUP_WITH:
7747 case SETUP_FINALLY:
7748 continue;
7749 }
7750 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7751 if (is_exit_without_lineno(target)) {
7752 basicblock *new_target = compiler_copy_block(c, target);
7753 if (new_target == NULL) {
7754 return -1;
7755 }
7756 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
7757 b->b_instr[b->b_iused-1].i_target = new_target;
7758 }
7759 }
Mark Shannoneaccc122020-12-04 15:22:12 +00007760 entry = b;
7761 }
7762 assert(entry != NULL);
7763 if (is_exit_without_lineno(entry)) {
7764 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00007765 }
Mark Shannonee9f98d2021-01-05 12:04:10 +00007766 /* Eliminate empty blocks */
7767 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7768 while (b->b_next && b->b_next->b_iused == 0) {
7769 b->b_next = b->b_next->b_next;
7770 }
7771 }
Mark Shannon5977a792020-12-02 13:31:40 +00007772 /* Any remaining reachable exit blocks without line number can only be reached by
7773 * fall through, and thus can only have a single predecessor */
7774 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7775 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
7776 if (is_exit_without_lineno(b->b_next)) {
7777 assert(b->b_next->b_iused > 0);
7778 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
7779 }
7780 }
7781 }
7782 return 0;
7783}
7784
7785
Mark Shannon6e8128f2020-07-30 10:03:00 +01007786/* Retained for API compatibility.
7787 * Optimization is now done in optimize_cfg */
7788
7789PyObject *
7790PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
7791 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
7792{
7793 Py_INCREF(code);
7794 return code;
7795}