blob: 85bc87dbf682068e5029fe3e1c7febb4b6dfd4c4 [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
Pablo Galindo90235812020-03-15 04:29:22 +000046#define IS_TOP_LEVEL_AWAIT(c) ( \
47 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
48 && (c->u->u_ste->ste_type == ModuleBlock))
49
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000050struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 unsigned char i_opcode;
52 int i_oparg;
53 struct basicblock_ *i_target; /* target block (if jump instruction) */
54 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055};
56
Mark Shannon582aaf12020-08-04 17:30:11 +010057#define LOG_BITS_PER_INT 5
58#define MASK_LOW_LOG_BITS 31
59
60static inline int
61is_bit_set_in_table(uint32_t *table, int bitindex) {
62 /* Is the relevant bit set in the relevant word? */
63 /* 256 bits fit into 8 32-bits words.
64 * Word is indexed by (bitindex>>ln(size of int in bits)).
65 * Bit within word is the low bits of bitindex.
66 */
67 uint32_t word = table[bitindex >> LOG_BITS_PER_INT];
68 return (word >> (bitindex & MASK_LOW_LOG_BITS)) & 1;
69}
70
71static inline int
72is_relative_jump(struct instr *i)
73{
74 return is_bit_set_in_table(_PyOpcode_RelativeJump, i->i_opcode);
75}
76
77static inline int
78is_jump(struct instr *i)
79{
80 return is_bit_set_in_table(_PyOpcode_Jump, i->i_opcode);
81}
82
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000083typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000084 /* Each basicblock in a compilation unit is linked via b_list in the
85 reverse order that the block are allocated. b_list points to the next
86 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 struct basicblock_ *b_list;
88 /* number of instructions used */
89 int b_iused;
90 /* length of instruction array (b_instr) */
91 int b_ialloc;
92 /* pointer to an array of instructions, initially NULL */
93 struct instr *b_instr;
94 /* If b_next is non-NULL, it is a pointer to the next
95 block reached by normal control flow. */
96 struct basicblock_ *b_next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 /* b_return is true if a RETURN_VALUE opcode is inserted. */
98 unsigned b_return : 1;
Mark Shannon3bd60352021-01-13 12:05:43 +000099 /* Number of predecssors that a block has. */
100 int b_predecessors;
Mark Shannoncc75ab72020-11-12 19:49:33 +0000101 /* Basic block has no fall through (it ends with a return, raise or jump) */
102 unsigned b_nofallthrough : 1;
103 /* Basic block exits scope (it ends with a return or raise) */
104 unsigned b_exit : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 /* depth of stack upon entry of block, computed by stackdepth() */
106 int b_startdepth;
107 /* instruction offset for block, computed by assemble_jump_offsets() */
108 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000109} basicblock;
110
111/* fblockinfo tracks the current frame block.
112
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000113A frame block is used to handle loops, try/except, and try/finally.
114It's called a frame block to distinguish it from a basic block in the
115compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000116*/
117
Mark Shannon02d126a2020-09-25 14:04:19 +0100118enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
tomKPZ7a7ba3d2021-04-07 07:43:45 -0700119 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER,
120 ASYNC_COMPREHENSION_GENERATOR };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000121
122struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 enum fblocktype fb_type;
124 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200125 /* (optional) type-specific exit or cleanup block */
126 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +0000127 /* (optional) additional information required for unwinding */
128 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000129};
130
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100131enum {
132 COMPILER_SCOPE_MODULE,
133 COMPILER_SCOPE_CLASS,
134 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400135 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400136 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100137 COMPILER_SCOPE_COMPREHENSION,
138};
139
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000140/* The following items change on entry and exit of code blocks.
141 They must be saved and restored when returning to a block.
142*/
143struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400147 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100148 int u_scope_type;
149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 /* The following fields are dicts that map objects to
151 the index of them in co_XXX. The index is used as
152 the argument for opcodes that refer to those collections.
153 */
154 PyObject *u_consts; /* all constants */
155 PyObject *u_names; /* all names */
156 PyObject *u_varnames; /* local variables */
157 PyObject *u_cellvars; /* cell variables */
158 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000161
Victor Stinnerf8e32212013-11-19 23:56:34 +0100162 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100163 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100164 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 /* Pointer to the most recently allocated block. By following b_list
166 members, you can reach all early allocated blocks. */
167 basicblock *u_blocks;
168 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 int u_nfblocks;
171 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 int u_firstlineno; /* the first lineno of the block */
174 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000175 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176};
177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000179
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000180The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000182managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000183
184Note that we don't track recursion levels during compilation - the
185task of detecting and rejecting excessive levels of nesting is
186handled by the symbol analysis pass.
187
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000188*/
189
190struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200191 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 struct symtable *c_st;
193 PyFutureFeatures *c_future; /* pointer to module's __future__ */
194 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000195
Georg Brandl8334fd92010-12-04 10:26:46 +0000196 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 int c_interactive; /* true if in interactive mode */
198 int c_nestlevel;
INADA Naokic2e16072018-11-26 21:23:22 +0900199 PyObject *c_const_cache; /* Python dict holding all constants,
200 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 struct compiler_unit *u; /* compiler state for current block */
202 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
203 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204};
205
Brandt Bucher145bf262021-02-26 14:51:55 -0800206typedef struct {
207 PyObject *stores;
208 int allow_irrefutable;
209} pattern_context;
210
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100211static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212static void compiler_free(struct compiler *);
213static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500214static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100216static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100217static int compiler_addop_j(struct compiler *, int, basicblock *);
Mark Shannon127dde52021-01-04 18:06:55 +0000218static int compiler_addop_j_noline(struct compiler *, int, basicblock *);
Brandt Bucher145bf262021-02-26 14:51:55 -0800219static int compiler_error(struct compiler *, const char *, ...);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200220static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000221static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
222
223static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
224static int compiler_visit_stmt(struct compiler *, stmt_ty);
225static int compiler_visit_keyword(struct compiler *, keyword_ty);
226static int compiler_visit_expr(struct compiler *, expr_ty);
227static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700228static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200229static int compiler_subscript(struct compiler *, expr_ty);
230static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000231
Andy Lester76d58772020-03-10 21:18:12 -0500232static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100233static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Mark Shannon8473cf82020-12-15 11:07:50 +0000234
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500236static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400237static int compiler_async_with(struct compiler *, stmt_ty, int);
238static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100239static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100240 asdl_expr_seq *args,
241 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500242static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400243static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000244
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700245static int compiler_sync_comprehension_generator(
246 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100247 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200248 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700249 expr_ty elt, expr_ty val, int type);
250
251static int compiler_async_comprehension_generator(
252 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100253 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200254 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700255 expr_ty elt, expr_ty val, int type);
256
Brandt Bucher145bf262021-02-26 14:51:55 -0800257static int compiler_pattern(struct compiler *, expr_ty, pattern_context *);
258static int compiler_match(struct compiler *, stmt_ty);
259static int compiler_pattern_subpattern(struct compiler *, expr_ty,
260 pattern_context *);
261
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000262static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000263static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000264
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400265#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000266
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000267PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000268_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* Name mangling: __private becomes _classname__private.
271 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200272 PyObject *result;
273 size_t nlen, plen, ipriv;
274 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200276 PyUnicode_READ_CHAR(ident, 0) != '_' ||
277 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 Py_INCREF(ident);
279 return ident;
280 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 nlen = PyUnicode_GET_LENGTH(ident);
282 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 The only time a name with a dot can occur is when
286 we are compiling an import statement that has a
287 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 TODO(jhylton): Decide whether we want to support
290 mangling of the module name, e.g. __M.X.
291 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200292 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
293 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
294 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_INCREF(ident);
296 return ident; /* Don't mangle __whatever__ */
297 }
298 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200299 ipriv = 0;
300 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
301 ipriv++;
302 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 Py_INCREF(ident);
304 return ident; /* Don't mangle if class is just underscores */
305 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200306 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000307
Antoine Pitrou55bff892013-04-06 21:21:04 +0200308 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
309 PyErr_SetString(PyExc_OverflowError,
310 "private identifier too large to be mangled");
311 return NULL;
312 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200314 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
315 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
316 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
317
318 result = PyUnicode_New(1 + nlen + plen, maxchar);
319 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200321 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
322 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200323 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
324 Py_DECREF(result);
325 return NULL;
326 }
327 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
328 Py_DECREF(result);
329 return NULL;
330 }
Victor Stinner8f825062012-04-27 13:55:39 +0200331 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200332 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000333}
334
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000335static int
336compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000339
INADA Naokic2e16072018-11-26 21:23:22 +0900340 c->c_const_cache = PyDict_New();
341 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900343 }
344
345 c->c_stack = PyList_New(0);
346 if (!c->c_stack) {
347 Py_CLEAR(c->c_const_cache);
348 return 0;
349 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000352}
353
354PyCodeObject *
Victor Stinnera81fca62021-03-24 00:51:50 +0100355_PyAST_Compile(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
356 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 struct compiler c;
359 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200360 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (!__doc__) {
364 __doc__ = PyUnicode_InternFromString("__doc__");
365 if (!__doc__)
366 return NULL;
367 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000368 if (!__annotations__) {
369 __annotations__ = PyUnicode_InternFromString("__annotations__");
370 if (!__annotations__)
371 return NULL;
372 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (!compiler_init(&c))
374 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200375 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 c.c_filename = filename;
377 c.c_arena = arena;
Victor Stinnera81fca62021-03-24 00:51:50 +0100378 c.c_future = _PyFuture_FromAST(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (c.c_future == NULL)
380 goto finally;
381 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 flags = &local_flags;
383 }
384 merged = c.c_future->ff_features | flags->cf_flags;
385 c.c_future->ff_features = merged;
386 flags->cf_flags = merged;
387 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200388 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000390
Pablo Galindod112c602020-03-18 23:02:09 +0000391 _PyASTOptimizeState state;
392 state.optimize = c.c_optimize;
393 state.ff_features = merged;
394
395 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900396 goto finally;
397 }
398
Victor Stinner28ad12f2021-03-19 12:41:49 +0100399 c.c_st = _PySymtable_Build(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 if (c.c_st == NULL) {
401 if (!PyErr_Occurred())
402 PyErr_SetString(PyExc_SystemError, "no symtable");
403 goto finally;
404 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000407
Thomas Wouters1175c432006-02-27 22:49:54 +0000408 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 compiler_free(&c);
410 assert(co || PyErr_Occurred());
411 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000412}
413
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000414static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000415compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (c->c_st)
Victor Stinner28ad12f2021-03-19 12:41:49 +0100418 _PySymtable_Free(c->c_st);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (c->c_future)
420 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200421 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900422 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000424}
425
Guido van Rossum79f25d91997-04-29 20:08:16 +0000426static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 Py_ssize_t i, n;
430 PyObject *v, *k;
431 PyObject *dict = PyDict_New();
432 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 n = PyList_Size(list);
435 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100436 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (!v) {
438 Py_DECREF(dict);
439 return NULL;
440 }
441 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300442 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Py_DECREF(v);
444 Py_DECREF(dict);
445 return NULL;
446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 Py_DECREF(v);
448 }
449 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000450}
451
452/* Return new dict containing names from src that match scope(s).
453
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000454src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000456values are integers, starting at offset and increasing by one for
457each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458*/
459
460static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100461dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000462{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700463 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500465 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 assert(offset >= 0);
468 if (dest == NULL)
469 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470
Meador Inge2ca63152012-07-18 14:20:11 -0500471 /* Sort the keys so that we have a deterministic order on the indexes
472 saved in the returned dictionary. These indexes are used as indexes
473 into the free and cell var storage. Therefore if they aren't
474 deterministic, then the generated bytecode is not deterministic.
475 */
476 sorted_keys = PyDict_Keys(src);
477 if (sorted_keys == NULL)
478 return NULL;
479 if (PyList_Sort(sorted_keys) != 0) {
480 Py_DECREF(sorted_keys);
481 return NULL;
482 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500483 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500484
485 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 /* XXX this should probably be a macro in symtable.h */
487 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500488 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200489 v = PyDict_GetItemWithError(src, k);
490 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 vi = PyLong_AS_LONG(v);
492 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300495 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500497 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 Py_DECREF(dest);
499 return NULL;
500 }
501 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300502 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500503 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 Py_DECREF(item);
505 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 return NULL;
507 }
508 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 }
510 }
Meador Inge2ca63152012-07-18 14:20:11 -0500511 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000513}
514
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000515static void
516compiler_unit_check(struct compiler_unit *u)
517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 basicblock *block;
519 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +0100520 assert(!_PyMem_IsPtrFreed(block));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (block->b_instr != NULL) {
522 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100523 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 assert(block->b_ialloc >= block->b_iused);
525 }
526 else {
527 assert (block->b_iused == 0);
528 assert (block->b_ialloc == 0);
529 }
530 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000531}
532
533static void
534compiler_unit_free(struct compiler_unit *u)
535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 compiler_unit_check(u);
539 b = u->u_blocks;
540 while (b != NULL) {
541 if (b->b_instr)
542 PyObject_Free((void *)b->b_instr);
543 next = b->b_list;
544 PyObject_Free((void *)b);
545 b = next;
546 }
547 Py_CLEAR(u->u_ste);
548 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400549 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 Py_CLEAR(u->u_consts);
551 Py_CLEAR(u->u_names);
552 Py_CLEAR(u->u_varnames);
553 Py_CLEAR(u->u_freevars);
554 Py_CLEAR(u->u_cellvars);
555 Py_CLEAR(u->u_private);
556 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000557}
558
559static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100560compiler_enter_scope(struct compiler *c, identifier name,
561 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100564 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000565
Andy Lester7668a8b2020-03-24 23:26:44 -0500566 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 struct compiler_unit));
568 if (!u) {
569 PyErr_NoMemory();
570 return 0;
571 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100572 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100574 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 u->u_kwonlyargcount = 0;
576 u->u_ste = PySymtable_Lookup(c->c_st, key);
577 if (!u->u_ste) {
578 compiler_unit_free(u);
579 return 0;
580 }
581 Py_INCREF(name);
582 u->u_name = name;
583 u->u_varnames = list2dict(u->u_ste->ste_varnames);
584 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
585 if (!u->u_varnames || !u->u_cellvars) {
586 compiler_unit_free(u);
587 return 0;
588 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500589 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000590 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500591 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300592 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500593 int res;
594 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200595 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500596 name = _PyUnicode_FromId(&PyId___class__);
597 if (!name) {
598 compiler_unit_free(u);
599 return 0;
600 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100601 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500602 if (res < 0) {
603 compiler_unit_free(u);
604 return 0;
605 }
606 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200609 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (!u->u_freevars) {
611 compiler_unit_free(u);
612 return 0;
613 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 u->u_blocks = NULL;
616 u->u_nfblocks = 0;
617 u->u_firstlineno = lineno;
618 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000619 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 u->u_consts = PyDict_New();
621 if (!u->u_consts) {
622 compiler_unit_free(u);
623 return 0;
624 }
625 u->u_names = PyDict_New();
626 if (!u->u_names) {
627 compiler_unit_free(u);
628 return 0;
629 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* Push the old compiler_unit on the stack. */
634 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400635 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
637 Py_XDECREF(capsule);
638 compiler_unit_free(u);
639 return 0;
640 }
641 Py_DECREF(capsule);
642 u->u_private = c->u->u_private;
643 Py_XINCREF(u->u_private);
644 }
645 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100648
649 block = compiler_new_block(c);
650 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100652 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000653
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400654 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
655 if (!compiler_set_qualname(c))
656 return 0;
657 }
658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660}
661
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000662static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663compiler_exit_scope(struct compiler *c)
664{
Victor Stinnera6192632021-01-29 16:53:03 +0100665 // Don't call PySequence_DelItem() with an exception raised
666 PyObject *exc_type, *exc_val, *exc_tb;
667 PyErr_Fetch(&exc_type, &exc_val, &exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 c->c_nestlevel--;
670 compiler_unit_free(c->u);
671 /* Restore c->u to the parent unit. */
Victor Stinnera6192632021-01-29 16:53:03 +0100672 Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if (n >= 0) {
Victor Stinnera6192632021-01-29 16:53:03 +0100674 PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400675 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 assert(c->u);
677 /* we are deleting from a list so this really shouldn't fail */
Victor Stinnera6192632021-01-29 16:53:03 +0100678 if (PySequence_DelItem(c->c_stack, n) < 0) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +0100679 _PyErr_WriteUnraisableMsg("on removing the last compiler "
680 "stack item", NULL);
Victor Stinnera6192632021-01-29 16:53:03 +0100681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 compiler_unit_check(c->u);
683 }
Victor Stinnera6192632021-01-29 16:53:03 +0100684 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 c->u = NULL;
Victor Stinnera6192632021-01-29 16:53:03 +0100686 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000687
Victor Stinnera6192632021-01-29 16:53:03 +0100688 PyErr_Restore(exc_type, exc_val, exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000689}
690
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691static int
692compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100693{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100694 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400695 _Py_static_string(dot_locals, ".<locals>");
696 Py_ssize_t stack_size;
697 struct compiler_unit *u = c->u;
698 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100699
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400700 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100701 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400702 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 if (stack_size > 1) {
704 int scope, force_global = 0;
705 struct compiler_unit *parent;
706 PyObject *mangled, *capsule;
707
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400708 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400709 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400710 assert(parent);
711
Yury Selivanov75445082015-05-11 22:57:16 -0400712 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
713 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
714 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400715 assert(u->u_name);
716 mangled = _Py_Mangle(parent->u_private, u->u_name);
717 if (!mangled)
718 return 0;
Victor Stinner28ad12f2021-03-19 12:41:49 +0100719 scope = _PyST_GetScope(parent->u_ste, mangled);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 Py_DECREF(mangled);
721 assert(scope != GLOBAL_IMPLICIT);
722 if (scope == GLOBAL_EXPLICIT)
723 force_global = 1;
724 }
725
726 if (!force_global) {
727 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400728 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400729 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
730 dot_locals_str = _PyUnicode_FromId(&dot_locals);
731 if (dot_locals_str == NULL)
732 return 0;
733 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
734 if (base == NULL)
735 return 0;
736 }
737 else {
738 Py_INCREF(parent->u_qualname);
739 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400740 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741 }
742 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400743
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400744 if (base != NULL) {
745 dot_str = _PyUnicode_FromId(&dot);
746 if (dot_str == NULL) {
747 Py_DECREF(base);
748 return 0;
749 }
750 name = PyUnicode_Concat(base, dot_str);
751 Py_DECREF(base);
752 if (name == NULL)
753 return 0;
754 PyUnicode_Append(&name, u->u_name);
755 if (name == NULL)
756 return 0;
757 }
758 else {
759 Py_INCREF(u->u_name);
760 name = u->u_name;
761 }
762 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100763
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400764 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100765}
766
Eric V. Smith235a6f02015-09-19 14:51:32 -0400767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768/* Allocate a new block and return a pointer to it.
769 Returns NULL on error.
770*/
771
772static basicblock *
773compiler_new_block(struct compiler *c)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 basicblock *b;
776 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500779 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (b == NULL) {
781 PyErr_NoMemory();
782 return NULL;
783 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Extend the singly linked list of blocks with new block. */
785 b->b_list = u->u_blocks;
786 u->u_blocks = b;
787 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000788}
789
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791compiler_next_block(struct compiler *c)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 basicblock *block = compiler_new_block(c);
794 if (block == NULL)
795 return NULL;
796 c->u->u_curblock->b_next = block;
797 c->u->u_curblock = block;
798 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000799}
800
801static basicblock *
802compiler_use_next_block(struct compiler *c, basicblock *block)
803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 assert(block != NULL);
805 c->u->u_curblock->b_next = block;
806 c->u->u_curblock = block;
807 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808}
809
Mark Shannon5977a792020-12-02 13:31:40 +0000810static basicblock *
811compiler_copy_block(struct compiler *c, basicblock *block)
812{
813 /* Cannot copy a block if it has a fallthrough, since
814 * a block can only have one fallthrough predecessor.
815 */
816 assert(block->b_nofallthrough);
817 basicblock *result = compiler_next_block(c);
818 if (result == NULL) {
819 return NULL;
820 }
821 for (int i = 0; i < block->b_iused; i++) {
822 int n = compiler_next_instr(result);
823 if (n < 0) {
824 return NULL;
825 }
826 result->b_instr[n] = block->b_instr[i];
827 }
828 result->b_exit = block->b_exit;
Mark Shannon3bd60352021-01-13 12:05:43 +0000829 result->b_nofallthrough = 1;
Mark Shannon5977a792020-12-02 13:31:40 +0000830 return result;
831}
832
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833/* Returns the offset of the next instruction in the current block's
834 b_instr array. Resizes the b_instr as necessary.
835 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000836*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837
838static int
Andy Lester76d58772020-03-10 21:18:12 -0500839compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 assert(b != NULL);
842 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500843 b->b_instr = (struct instr *)PyObject_Calloc(
844 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (b->b_instr == NULL) {
846 PyErr_NoMemory();
847 return -1;
848 }
849 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 }
851 else if (b->b_iused == b->b_ialloc) {
852 struct instr *tmp;
853 size_t oldsize, newsize;
854 oldsize = b->b_ialloc * sizeof(struct instr);
855 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000856
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700857 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyErr_NoMemory();
859 return -1;
860 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (newsize == 0) {
863 PyErr_NoMemory();
864 return -1;
865 }
866 b->b_ialloc <<= 1;
867 tmp = (struct instr *)PyObject_Realloc(
868 (void *)b->b_instr, newsize);
869 if (tmp == NULL) {
870 PyErr_NoMemory();
871 return -1;
872 }
873 b->b_instr = tmp;
874 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
875 }
876 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000877}
878
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200879/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000880
Christian Heimes2202f872008-02-06 14:31:34 +0000881 The line number is reset in the following cases:
882 - when entering a new scope
883 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200884 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200885 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000886*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000887
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200888#define SET_LOC(c, x) \
889 (c)->u->u_lineno = (x)->lineno; \
890 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200892/* Return the stack effect of opcode with argument oparg.
893
894 Some opcodes have different stack effect when jump to the target and
895 when not jump. The 'jump' parameter specifies the case:
896
897 * 0 -- when not jump
898 * 1 -- when jump
899 * -1 -- maximal
900 */
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200901static int
902stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300905 case NOP:
906 case EXTENDED_ARG:
907 return 0;
908
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200909 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case POP_TOP:
911 return -1;
912 case ROT_TWO:
913 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200914 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 return 0;
916 case DUP_TOP:
917 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000918 case DUP_TOP_TWO:
919 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200921 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case UNARY_POSITIVE:
923 case UNARY_NEGATIVE:
924 case UNARY_NOT:
925 case UNARY_INVERT:
926 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case SET_ADD:
929 case LIST_APPEND:
930 return -1;
931 case MAP_ADD:
932 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000933
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200934 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 case BINARY_POWER:
936 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400937 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case BINARY_MODULO:
939 case BINARY_ADD:
940 case BINARY_SUBTRACT:
941 case BINARY_SUBSCR:
942 case BINARY_FLOOR_DIVIDE:
943 case BINARY_TRUE_DIVIDE:
944 return -1;
945 case INPLACE_FLOOR_DIVIDE:
946 case INPLACE_TRUE_DIVIDE:
947 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case INPLACE_ADD:
950 case INPLACE_SUBTRACT:
951 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400952 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case INPLACE_MODULO:
954 return -1;
955 case STORE_SUBSCR:
956 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case DELETE_SUBSCR:
958 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case BINARY_LSHIFT:
961 case BINARY_RSHIFT:
962 case BINARY_AND:
963 case BINARY_XOR:
964 case BINARY_OR:
965 return -1;
966 case INPLACE_POWER:
967 return -1;
968 case GET_ITER:
969 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case PRINT_EXPR:
972 return -1;
973 case LOAD_BUILD_CLASS:
974 return 1;
975 case INPLACE_LSHIFT:
976 case INPLACE_RSHIFT:
977 case INPLACE_AND:
978 case INPLACE_XOR:
979 case INPLACE_OR:
980 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200983 /* 1 in the normal flow.
984 * Restore the stack position and push 6 values before jumping to
985 * the handler if an exception be raised. */
986 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case RETURN_VALUE:
988 return -1;
989 case IMPORT_STAR:
990 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700991 case SETUP_ANNOTATIONS:
992 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case YIELD_VALUE:
994 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500995 case YIELD_FROM:
996 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case POP_BLOCK:
998 return 0;
999 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001000 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 case STORE_NAME:
1003 return -1;
1004 case DELETE_NAME:
1005 return 0;
1006 case UNPACK_SEQUENCE:
1007 return oparg-1;
1008 case UNPACK_EX:
1009 return (oparg&0xFF) + (oparg>>8);
1010 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001011 /* -1 at end of iterator, 1 if continue iterating. */
1012 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case STORE_ATTR:
1015 return -2;
1016 case DELETE_ATTR:
1017 return -1;
1018 case STORE_GLOBAL:
1019 return -1;
1020 case DELETE_GLOBAL:
1021 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 case LOAD_CONST:
1023 return 1;
1024 case LOAD_NAME:
1025 return 1;
1026 case BUILD_TUPLE:
1027 case BUILD_LIST:
1028 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001029 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 return 1-oparg;
1031 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001032 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001033 case BUILD_CONST_KEY_MAP:
1034 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case LOAD_ATTR:
1036 return 0;
1037 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001038 case IS_OP:
1039 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001041 case JUMP_IF_NOT_EXC_MATCH:
1042 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case IMPORT_NAME:
1044 return -1;
1045 case IMPORT_FROM:
1046 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001048 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case JUMP_ABSOLUTE:
1051 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001053 case JUMP_IF_TRUE_OR_POP:
1054 case JUMP_IF_FALSE_OR_POP:
1055 return jump ? 0 : -1;
1056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 case POP_JUMP_IF_FALSE:
1058 case POP_JUMP_IF_TRUE:
1059 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 case LOAD_GLOBAL:
1062 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001064 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001066 /* 0 in the normal flow.
1067 * Restore the stack position and push 6 values before jumping to
1068 * the handler if an exception be raised. */
1069 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001070 case RERAISE:
1071 return -3;
1072
1073 case WITH_EXCEPT_START:
1074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 case LOAD_FAST:
1077 return 1;
1078 case STORE_FAST:
1079 return -1;
1080 case DELETE_FAST:
1081 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 case RAISE_VARARGS:
1084 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001085
1086 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001088 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001089 case CALL_METHOD:
1090 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001092 return -oparg-1;
1093 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001094 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001095 case MAKE_FUNCTION:
1096 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1097 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 case BUILD_SLICE:
1099 if (oparg == 3)
1100 return -2;
1101 else
1102 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001104 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 case LOAD_CLOSURE:
1106 return 1;
1107 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001108 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 return 1;
1110 case STORE_DEREF:
1111 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001112 case DELETE_DEREF:
1113 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001114
1115 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001116 case GET_AWAITABLE:
1117 return 0;
1118 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001119 /* 0 in the normal flow.
1120 * Restore the stack position to the position before the result
1121 * of __aenter__ and push 6 values before jumping to the handler
1122 * if an exception be raised. */
1123 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001124 case BEFORE_ASYNC_WITH:
1125 return 1;
1126 case GET_AITER:
1127 return 0;
1128 case GET_ANEXT:
1129 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001130 case GET_YIELD_FROM_ITER:
1131 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001132 case END_ASYNC_FOR:
1133 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001134 case FORMAT_VALUE:
1135 /* If there's a fmt_spec on the stack, we go from 2->1,
1136 else 1->1. */
1137 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001138 case LOAD_METHOD:
1139 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001140 case LOAD_ASSERTION_ERROR:
1141 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001142 case LIST_TO_TUPLE:
1143 return 0;
Mark Shannonb37181e2021-04-06 11:48:59 +01001144 case GEN_START:
1145 return -1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001146 case LIST_EXTEND:
1147 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001148 case DICT_MERGE:
1149 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001150 return -1;
Brandt Bucher145bf262021-02-26 14:51:55 -08001151 case COPY_DICT_WITHOUT_KEYS:
1152 return 0;
1153 case MATCH_CLASS:
1154 return -1;
1155 case GET_LEN:
1156 case MATCH_MAPPING:
1157 case MATCH_SEQUENCE:
1158 return 1;
1159 case MATCH_KEYS:
1160 return 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001162 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 }
Larry Hastings3a907972013-11-23 14:49:22 -08001164 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001165}
1166
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001167int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001168PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1169{
1170 return stack_effect(opcode, oparg, jump);
1171}
1172
1173int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001174PyCompile_OpcodeStackEffect(int opcode, int oparg)
1175{
1176 return stack_effect(opcode, oparg, -1);
1177}
1178
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001179/* Add an opcode with no argument.
1180 Returns 0 on failure, 1 on success.
1181*/
1182
1183static int
Mark Shannon3bd60352021-01-13 12:05:43 +00001184compiler_addop_line(struct compiler *c, int opcode, int line)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 basicblock *b;
1187 struct instr *i;
1188 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001189 assert(!HAS_ARG(opcode));
Andy Lester76d58772020-03-10 21:18:12 -05001190 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (off < 0)
1192 return 0;
1193 b = c->u->u_curblock;
1194 i = &b->b_instr[off];
1195 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001196 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 if (opcode == RETURN_VALUE)
1198 b->b_return = 1;
Mark Shannon3bd60352021-01-13 12:05:43 +00001199 i->i_lineno = line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001201}
1202
Mark Shannon3bd60352021-01-13 12:05:43 +00001203static int
1204compiler_addop(struct compiler *c, int opcode)
1205{
1206 return compiler_addop_line(c, opcode, c->u->u_lineno);
1207}
1208
1209static int
1210compiler_addop_noline(struct compiler *c, int opcode)
1211{
1212 return compiler_addop_line(c, opcode, -1);
1213}
1214
1215
Victor Stinnerf8e32212013-11-19 23:56:34 +01001216static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001217compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001218{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001219 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001221
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001222 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001224 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001226 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001227 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001228 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 return -1;
1231 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001232 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 Py_DECREF(v);
1234 return -1;
1235 }
1236 Py_DECREF(v);
1237 }
1238 else
1239 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001240 return arg;
1241}
1242
INADA Naokic2e16072018-11-26 21:23:22 +09001243// Merge const *o* recursively and return constant key object.
1244static PyObject*
1245merge_consts_recursive(struct compiler *c, PyObject *o)
1246{
1247 // None and Ellipsis are singleton, and key is the singleton.
1248 // No need to merge object and key.
1249 if (o == Py_None || o == Py_Ellipsis) {
1250 Py_INCREF(o);
1251 return o;
1252 }
1253
1254 PyObject *key = _PyCode_ConstantKey(o);
1255 if (key == NULL) {
1256 return NULL;
1257 }
1258
1259 // t is borrowed reference
1260 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1261 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001262 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001263 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001264 Py_DECREF(key);
1265 return t;
1266 }
1267
INADA Naokif7e4d362018-11-29 00:58:46 +09001268 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001269 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001270 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001271 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001272 Py_ssize_t len = PyTuple_GET_SIZE(o);
1273 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001274 PyObject *item = PyTuple_GET_ITEM(o, i);
1275 PyObject *u = merge_consts_recursive(c, item);
1276 if (u == NULL) {
1277 Py_DECREF(key);
1278 return NULL;
1279 }
1280
1281 // See _PyCode_ConstantKey()
1282 PyObject *v; // borrowed
1283 if (PyTuple_CheckExact(u)) {
1284 v = PyTuple_GET_ITEM(u, 1);
1285 }
1286 else {
1287 v = u;
1288 }
1289 if (v != item) {
1290 Py_INCREF(v);
1291 PyTuple_SET_ITEM(o, i, v);
1292 Py_DECREF(item);
1293 }
1294
1295 Py_DECREF(u);
1296 }
1297 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001298 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001299 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001300 // constant keys.
1301 // See _PyCode_ConstantKey() for detail.
1302 assert(PyTuple_CheckExact(key));
1303 assert(PyTuple_GET_SIZE(key) == 2);
1304
1305 Py_ssize_t len = PySet_GET_SIZE(o);
1306 if (len == 0) { // empty frozenset should not be re-created.
1307 return key;
1308 }
1309 PyObject *tuple = PyTuple_New(len);
1310 if (tuple == NULL) {
1311 Py_DECREF(key);
1312 return NULL;
1313 }
1314 Py_ssize_t i = 0, pos = 0;
1315 PyObject *item;
1316 Py_hash_t hash;
1317 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1318 PyObject *k = merge_consts_recursive(c, item);
1319 if (k == NULL) {
1320 Py_DECREF(tuple);
1321 Py_DECREF(key);
1322 return NULL;
1323 }
1324 PyObject *u;
1325 if (PyTuple_CheckExact(k)) {
1326 u = PyTuple_GET_ITEM(k, 1);
1327 Py_INCREF(u);
1328 Py_DECREF(k);
1329 }
1330 else {
1331 u = k;
1332 }
1333 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1334 i++;
1335 }
1336
1337 // Instead of rewriting o, we create new frozenset and embed in the
1338 // key tuple. Caller should get merged frozenset from the key tuple.
1339 PyObject *new = PyFrozenSet_New(tuple);
1340 Py_DECREF(tuple);
1341 if (new == NULL) {
1342 Py_DECREF(key);
1343 return NULL;
1344 }
1345 assert(PyTuple_GET_ITEM(key, 1) == o);
1346 Py_DECREF(o);
1347 PyTuple_SET_ITEM(key, 1, new);
1348 }
INADA Naokic2e16072018-11-26 21:23:22 +09001349
1350 return key;
1351}
1352
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001353static Py_ssize_t
1354compiler_add_const(struct compiler *c, PyObject *o)
1355{
INADA Naokic2e16072018-11-26 21:23:22 +09001356 PyObject *key = merge_consts_recursive(c, o);
1357 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001358 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001359 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001360
Andy Lester76d58772020-03-10 21:18:12 -05001361 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001362 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364}
1365
1366static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001367compiler_addop_load_const(struct compiler *c, PyObject *o)
1368{
1369 Py_ssize_t arg = compiler_add_const(c, o);
1370 if (arg < 0)
1371 return 0;
1372 return compiler_addop_i(c, LOAD_CONST, arg);
1373}
1374
1375static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378{
Andy Lester76d58772020-03-10 21:18:12 -05001379 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001381 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001382 return compiler_addop_i(c, opcode, arg);
1383}
1384
1385static int
1386compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001388{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001389 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001390
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1392 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001393 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001394 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395 Py_DECREF(mangled);
1396 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001397 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 return compiler_addop_i(c, opcode, arg);
1399}
1400
1401/* Add an opcode with an integer argument.
1402 Returns 0 on failure, 1 on success.
1403*/
1404
1405static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001406compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 struct instr *i;
1409 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001410
Victor Stinner2ad474b2016-03-01 23:34:47 +01001411 /* oparg value is unsigned, but a signed C int is usually used to store
1412 it in the C code (like Python/ceval.c).
1413
1414 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1415
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001416 The argument of a concrete bytecode instruction is limited to 8-bit.
1417 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1418 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001419 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001420
Andy Lester76d58772020-03-10 21:18:12 -05001421 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (off < 0)
1423 return 0;
1424 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001425 i->i_opcode = opcode;
1426 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001427 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001429}
1430
Mark Shannon28b75c82020-12-23 11:43:10 +00001431static int add_jump_to_block(basicblock *b, int opcode, int lineno, basicblock *target)
1432{
1433 assert(HAS_ARG(opcode));
1434 assert(b != NULL);
1435 assert(target != NULL);
1436
1437 int off = compiler_next_instr(b);
1438 struct instr *i = &b->b_instr[off];
1439 if (off < 0) {
1440 return 0;
1441 }
1442 i->i_opcode = opcode;
1443 i->i_target = target;
1444 i->i_lineno = lineno;
1445 return 1;
1446}
1447
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001448static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001449compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450{
Mark Shannon28b75c82020-12-23 11:43:10 +00001451 return add_jump_to_block(c->u->u_curblock, opcode, c->u->u_lineno, b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452}
1453
Mark Shannon127dde52021-01-04 18:06:55 +00001454static int
1455compiler_addop_j_noline(struct compiler *c, int opcode, basicblock *b)
1456{
1457 return add_jump_to_block(c->u->u_curblock, opcode, -1, b);
1458}
1459
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001460/* NEXT_BLOCK() creates an implicit jump from the current block
1461 to the new block.
1462
1463 The returns inside this macro make it impossible to decref objects
1464 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (compiler_next_block((C)) == NULL) \
1468 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
1471#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (!compiler_addop((C), (OP))) \
1473 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001474}
1475
Mark Shannon3bd60352021-01-13 12:05:43 +00001476#define ADDOP_NOLINE(C, OP) { \
1477 if (!compiler_addop_noline((C), (OP))) \
1478 return 0; \
1479}
1480
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001481#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (!compiler_addop((C), (OP))) { \
1483 compiler_exit_scope(c); \
1484 return 0; \
1485 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001486}
1487
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001488#define ADDOP_LOAD_CONST(C, O) { \
1489 if (!compiler_addop_load_const((C), (O))) \
1490 return 0; \
1491}
1492
1493/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1494#define ADDOP_LOAD_CONST_NEW(C, O) { \
1495 PyObject *__new_const = (O); \
1496 if (__new_const == NULL) { \
1497 return 0; \
1498 } \
1499 if (!compiler_addop_load_const((C), __new_const)) { \
1500 Py_DECREF(__new_const); \
1501 return 0; \
1502 } \
1503 Py_DECREF(__new_const); \
1504}
1505
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1508 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509}
1510
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001511/* Same as ADDOP_O, but steals a reference. */
1512#define ADDOP_N(C, OP, O, TYPE) { \
1513 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1514 Py_DECREF((O)); \
1515 return 0; \
1516 } \
1517 Py_DECREF((O)); \
1518}
1519
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1522 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001523}
1524
1525#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (!compiler_addop_i((C), (OP), (O))) \
1527 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528}
1529
Mark Shannon582aaf12020-08-04 17:30:11 +01001530#define ADDOP_JUMP(C, OP, O) { \
1531 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001533}
1534
Mark Shannon127dde52021-01-04 18:06:55 +00001535/* Add a jump with no line number.
1536 * Used for artificial jumps that have no corresponding
1537 * token in the source code. */
1538#define ADDOP_JUMP_NOLINE(C, OP, O) { \
1539 if (!compiler_addop_j_noline((C), (OP), (O))) \
1540 return 0; \
1541}
1542
Mark Shannon9af0e472020-01-14 10:12:45 +00001543#define ADDOP_COMPARE(C, CMP) { \
1544 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1545 return 0; \
1546}
1547
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1549 the ASDL name to synthesize the name of the C type and the visit function.
1550*/
1551
1552#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 if (!compiler_visit_ ## TYPE((C), (V))) \
1554 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555}
1556
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001557#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 if (!compiler_visit_ ## TYPE((C), (V))) { \
1559 compiler_exit_scope(c); \
1560 return 0; \
1561 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001562}
1563
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001564#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 if (!compiler_visit_slice((C), (V), (CTX))) \
1566 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001567}
1568
1569#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001571 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1573 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1574 if (!compiler_visit_ ## TYPE((C), elt)) \
1575 return 0; \
1576 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001577}
1578
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001579#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001581 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1583 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1584 if (!compiler_visit_ ## TYPE((C), elt)) { \
1585 compiler_exit_scope(c); \
1586 return 0; \
1587 } \
1588 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001589}
1590
Brandt Bucher145bf262021-02-26 14:51:55 -08001591#define RETURN_IF_FALSE(X) \
1592 if (!(X)) { \
1593 return 0; \
1594 }
1595
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001596/* Search if variable annotations are present statically in a block. */
1597
1598static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001599find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001600{
1601 int i, j, res = 0;
1602 stmt_ty st;
1603
1604 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1605 st = (stmt_ty)asdl_seq_GET(stmts, i);
1606 switch (st->kind) {
1607 case AnnAssign_kind:
1608 return 1;
1609 case For_kind:
1610 res = find_ann(st->v.For.body) ||
1611 find_ann(st->v.For.orelse);
1612 break;
1613 case AsyncFor_kind:
1614 res = find_ann(st->v.AsyncFor.body) ||
1615 find_ann(st->v.AsyncFor.orelse);
1616 break;
1617 case While_kind:
1618 res = find_ann(st->v.While.body) ||
1619 find_ann(st->v.While.orelse);
1620 break;
1621 case If_kind:
1622 res = find_ann(st->v.If.body) ||
1623 find_ann(st->v.If.orelse);
1624 break;
1625 case With_kind:
1626 res = find_ann(st->v.With.body);
1627 break;
1628 case AsyncWith_kind:
1629 res = find_ann(st->v.AsyncWith.body);
1630 break;
1631 case Try_kind:
1632 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1633 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1634 st->v.Try.handlers, j);
1635 if (find_ann(handler->v.ExceptHandler.body)) {
1636 return 1;
1637 }
1638 }
1639 res = find_ann(st->v.Try.body) ||
1640 find_ann(st->v.Try.finalbody) ||
1641 find_ann(st->v.Try.orelse);
1642 break;
1643 default:
1644 res = 0;
1645 }
1646 if (res) {
1647 break;
1648 }
1649 }
1650 return res;
1651}
1652
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001653/*
1654 * Frame block handling functions
1655 */
1656
1657static int
1658compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001659 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001660{
1661 struct fblockinfo *f;
1662 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001663 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001664 }
1665 f = &c->u->u_fblock[c->u->u_nfblocks++];
1666 f->fb_type = t;
1667 f->fb_block = b;
1668 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001669 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001670 return 1;
1671}
1672
1673static void
1674compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1675{
1676 struct compiler_unit *u = c->u;
1677 assert(u->u_nfblocks > 0);
1678 u->u_nfblocks--;
1679 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1680 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1681}
1682
Mark Shannonfee55262019-11-21 09:11:43 +00001683static int
1684compiler_call_exit_with_nones(struct compiler *c) {
1685 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1686 ADDOP(c, DUP_TOP);
1687 ADDOP(c, DUP_TOP);
1688 ADDOP_I(c, CALL_FUNCTION, 3);
1689 return 1;
1690}
1691
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001692/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001693 * popping the blocks will be restored afterwards, unless another
1694 * return, break or continue is found. In which case, the TOS will
1695 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001696 */
1697static int
1698compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1699 int preserve_tos)
1700{
1701 switch (info->fb_type) {
1702 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001703 case EXCEPTION_HANDLER:
tomKPZ7a7ba3d2021-04-07 07:43:45 -07001704 case ASYNC_COMPREHENSION_GENERATOR:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001705 return 1;
1706
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001707 case FOR_LOOP:
1708 /* Pop the iterator */
1709 if (preserve_tos) {
1710 ADDOP(c, ROT_TWO);
1711 }
1712 ADDOP(c, POP_TOP);
1713 return 1;
1714
Mark Shannon02d126a2020-09-25 14:04:19 +01001715 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001716 ADDOP(c, POP_BLOCK);
1717 return 1;
1718
1719 case FINALLY_TRY:
Mark Shannon5274b682020-12-16 13:07:01 +00001720 /* This POP_BLOCK gets the line number of the unwinding statement */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001721 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001722 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001723 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1724 return 0;
1725 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001726 }
Mark Shannon5274b682020-12-16 13:07:01 +00001727 /* Emit the finally block */
Mark Shannonfee55262019-11-21 09:11:43 +00001728 VISIT_SEQ(c, stmt, info->fb_datum);
1729 if (preserve_tos) {
1730 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001731 }
Mark Shannon5274b682020-12-16 13:07:01 +00001732 /* The finally block should appear to execute after the
1733 * statement causing the unwinding, so make the unwinding
1734 * instruction artificial */
1735 c->u->u_lineno = -1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001736 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001737
Mark Shannonfee55262019-11-21 09:11:43 +00001738 case FINALLY_END:
1739 if (preserve_tos) {
1740 ADDOP(c, ROT_FOUR);
1741 }
1742 ADDOP(c, POP_TOP);
1743 ADDOP(c, POP_TOP);
1744 ADDOP(c, POP_TOP);
1745 if (preserve_tos) {
1746 ADDOP(c, ROT_FOUR);
1747 }
1748 ADDOP(c, POP_EXCEPT);
1749 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001750
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001751 case WITH:
1752 case ASYNC_WITH:
1753 ADDOP(c, POP_BLOCK);
1754 if (preserve_tos) {
1755 ADDOP(c, ROT_TWO);
1756 }
Mark Shannonfee55262019-11-21 09:11:43 +00001757 if(!compiler_call_exit_with_nones(c)) {
1758 return 0;
1759 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001760 if (info->fb_type == ASYNC_WITH) {
1761 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001762 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001763 ADDOP(c, YIELD_FROM);
1764 }
Mark Shannonfee55262019-11-21 09:11:43 +00001765 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001766 return 1;
1767
1768 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001769 if (info->fb_datum) {
1770 ADDOP(c, POP_BLOCK);
1771 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001772 if (preserve_tos) {
1773 ADDOP(c, ROT_FOUR);
1774 }
Mark Shannonfee55262019-11-21 09:11:43 +00001775 ADDOP(c, POP_EXCEPT);
1776 if (info->fb_datum) {
1777 ADDOP_LOAD_CONST(c, Py_None);
1778 compiler_nameop(c, info->fb_datum, Store);
1779 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001780 }
Mark Shannonfee55262019-11-21 09:11:43 +00001781 return 1;
1782
1783 case POP_VALUE:
1784 if (preserve_tos) {
1785 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001786 }
Mark Shannonfee55262019-11-21 09:11:43 +00001787 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001788 return 1;
1789 }
1790 Py_UNREACHABLE();
1791}
1792
Mark Shannonfee55262019-11-21 09:11:43 +00001793/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1794static int
1795compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1796 if (c->u->u_nfblocks == 0) {
1797 return 1;
1798 }
1799 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1800 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1801 *loop = top;
1802 return 1;
1803 }
1804 struct fblockinfo copy = *top;
1805 c->u->u_nfblocks--;
1806 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1807 return 0;
1808 }
1809 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1810 return 0;
1811 }
1812 c->u->u_fblock[c->u->u_nfblocks] = copy;
1813 c->u->u_nfblocks++;
1814 return 1;
1815}
1816
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001817/* Compile a sequence of statements, checking for a docstring
1818 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819
1820static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001821compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001823 int i = 0;
1824 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001825 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001826
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001827 /* Set current line number to the line number of first statement.
1828 This way line number for SETUP_ANNOTATIONS will always
1829 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301830 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001831 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001832 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001833 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001834 }
1835 /* Every annotated class and module should have __annotations__. */
1836 if (find_ann(stmts)) {
1837 ADDOP(c, SETUP_ANNOTATIONS);
1838 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001839 if (!asdl_seq_LEN(stmts))
1840 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001841 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001842 if (c->c_optimize < 2) {
1843 docstring = _PyAST_GetDocString(stmts);
1844 if (docstring) {
1845 i = 1;
1846 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1847 assert(st->kind == Expr_kind);
1848 VISIT(c, expr, st->v.Expr.value);
1849 if (!compiler_nameop(c, __doc__, Store))
1850 return 0;
1851 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001853 for (; i < asdl_seq_LEN(stmts); i++)
1854 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001856}
1857
1858static PyCodeObject *
1859compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 PyCodeObject *co;
1862 int addNone = 1;
1863 static PyObject *module;
1864 if (!module) {
1865 module = PyUnicode_InternFromString("<module>");
1866 if (!module)
1867 return NULL;
1868 }
1869 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001870 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 return NULL;
1872 switch (mod->kind) {
1873 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001874 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 compiler_exit_scope(c);
1876 return 0;
1877 }
1878 break;
1879 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001880 if (find_ann(mod->v.Interactive.body)) {
1881 ADDOP(c, SETUP_ANNOTATIONS);
1882 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001884 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 break;
1886 case Expression_kind:
1887 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1888 addNone = 0;
1889 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 default:
1891 PyErr_Format(PyExc_SystemError,
1892 "module kind %d should not be possible",
1893 mod->kind);
1894 return 0;
1895 }
1896 co = assemble(c, addNone);
1897 compiler_exit_scope(c);
1898 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001899}
1900
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901/* The test for LOCAL must come before the test for FREE in order to
1902 handle classes where name is both local and free. The local var is
1903 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001904*/
1905
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906static int
1907get_ref_type(struct compiler *c, PyObject *name)
1908{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001909 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001910 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001911 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001912 return CELL;
Victor Stinner28ad12f2021-03-19 12:41:49 +01001913 scope = _PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 if (scope == 0) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001915 PyErr_Format(PyExc_SystemError,
Victor Stinner28ad12f2021-03-19 12:41:49 +01001916 "_PyST_GetScope(name=%R) failed: "
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001917 "unknown scope in unit %S (%R); "
1918 "symbols: %R; locals: %R; globals: %R",
1919 name,
1920 c->u->u_name, c->u->u_ste->ste_id,
1921 c->u->u_ste->ste_symbols, c->u->u_varnames, c->u->u_names);
1922 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925}
1926
1927static int
1928compiler_lookup_arg(PyObject *dict, PyObject *name)
1929{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001930 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001931 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001933 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001934 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935}
1936
1937static int
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001938compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags,
1939 PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001940{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001941 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001942 if (qualname == NULL)
1943 qualname = co->co_name;
1944
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001945 if (free) {
1946 for (i = 0; i < free; ++i) {
1947 /* Bypass com_addop_varname because it will generate
1948 LOAD_DEREF but LOAD_CLOSURE is needed.
1949 */
1950 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001951
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001952 /* Special case: If a class contains a method with a
1953 free variable that has the same name as a method,
1954 the name will be considered free *and* local in the
1955 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001956 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001957 */
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001958 int reftype = get_ref_type(c, name);
1959 if (reftype == -1) {
1960 return 0;
1961 }
1962 int arg;
1963 if (reftype == CELL) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001964 arg = compiler_lookup_arg(c->u->u_cellvars, name);
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001965 }
1966 else {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001967 arg = compiler_lookup_arg(c->u->u_freevars, name);
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001968 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001969 if (arg == -1) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001970 PyErr_Format(PyExc_SystemError,
1971 "compiler_lookup_arg(name=%R) with reftype=%d failed in %S; "
1972 "freevars of code %S: %R",
1973 name,
1974 reftype,
1975 c->u->u_name,
1976 co->co_name,
1977 co->co_freevars);
1978 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001979 }
1980 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001982 flags |= 0x08;
1983 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001985 ADDOP_LOAD_CONST(c, (PyObject*)co);
1986 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001987 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989}
1990
1991static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001992compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 if (!decos)
1997 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2000 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
2001 }
2002 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002003}
2004
2005static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002006compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
2007 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00002008{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002009 /* Push a dict of keyword-only default values.
2010
2011 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
2012 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002013 int i;
2014 PyObject *keys = NULL;
2015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
2017 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
2018 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
2019 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04002020 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002021 if (!mangled) {
2022 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002024 if (keys == NULL) {
2025 keys = PyList_New(1);
2026 if (keys == NULL) {
2027 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002028 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002029 }
2030 PyList_SET_ITEM(keys, 0, mangled);
2031 }
2032 else {
2033 int res = PyList_Append(keys, mangled);
2034 Py_DECREF(mangled);
2035 if (res == -1) {
2036 goto error;
2037 }
2038 }
2039 if (!compiler_visit_expr(c, default_)) {
2040 goto error;
2041 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 }
2043 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002044 if (keys != NULL) {
2045 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2046 PyObject *keys_tuple = PyList_AsTuple(keys);
2047 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002048 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002049 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002050 assert(default_count > 0);
2051 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002052 }
2053 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002054 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002055 }
2056
2057error:
2058 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002059 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002060}
2061
2062static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002063compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2064{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002065 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002066 return 1;
2067}
2068
2069static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002070compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002071 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002074 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002075 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002076 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002077
2078 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002079 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002080 VISIT(c, annexpr, annotation);
2081 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002083 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002084}
2085
2086static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002087compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002088 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002089{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002090 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 for (i = 0; i < asdl_seq_LEN(args); i++) {
2092 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002093 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 c,
2095 arg->arg,
2096 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002097 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002098 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002100 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002101}
2102
2103static int
2104compiler_visit_annotations(struct compiler *c, arguments_ty args,
2105 expr_ty returns)
2106{
Yurii Karabas73019792020-11-25 12:43:18 +02002107 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002108 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002109
Yurii Karabas73019792020-11-25 12:43:18 +02002110 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 */
2112 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002113 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002114
Yurii Karabas73019792020-11-25 12:43:18 +02002115 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2116 return 0;
2117 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2118 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002119 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002120 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002121 args->vararg->annotation, &annotations_len))
2122 return 0;
2123 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2124 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002125 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002126 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002127 args->kwarg->annotation, &annotations_len))
2128 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 if (!return_str) {
2131 return_str = PyUnicode_InternFromString("return");
2132 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002133 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 }
Yurii Karabas73019792020-11-25 12:43:18 +02002135 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2136 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 }
2138
Yurii Karabas73019792020-11-25 12:43:18 +02002139 if (annotations_len) {
2140 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002141 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002143
Yurii Karabas73019792020-11-25 12:43:18 +02002144 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002145}
2146
2147static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002148compiler_visit_defaults(struct compiler *c, arguments_ty args)
2149{
2150 VISIT_SEQ(c, expr, args->defaults);
2151 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2152 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002153}
2154
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002155static Py_ssize_t
2156compiler_default_arguments(struct compiler *c, arguments_ty args)
2157{
2158 Py_ssize_t funcflags = 0;
2159 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002160 if (!compiler_visit_defaults(c, args))
2161 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002162 funcflags |= 0x01;
2163 }
2164 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002165 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002166 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002167 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002168 return -1;
2169 }
2170 else if (res > 0) {
2171 funcflags |= 0x02;
2172 }
2173 }
2174 return funcflags;
2175}
2176
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002177static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002178forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2179{
2180
2181 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2182 compiler_error(c, "cannot assign to __debug__");
2183 return 1;
2184 }
2185 return 0;
2186}
2187
2188static int
2189compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2190{
2191 if (arg != NULL) {
2192 if (forbidden_name(c, arg->arg, Store))
2193 return 0;
2194 }
2195 return 1;
2196}
2197
2198static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002199compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002200{
2201 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002202 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002203 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2204 return 0;
2205 }
2206 }
2207 return 1;
2208}
2209
2210static int
2211compiler_check_debug_args(struct compiler *c, arguments_ty args)
2212{
2213 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2214 return 0;
2215 if (!compiler_check_debug_args_seq(c, args->args))
2216 return 0;
2217 if (!compiler_check_debug_one_arg(c, args->vararg))
2218 return 0;
2219 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2220 return 0;
2221 if (!compiler_check_debug_one_arg(c, args->kwarg))
2222 return 0;
2223 return 1;
2224}
2225
2226static int
Yury Selivanov75445082015-05-11 22:57:16 -04002227compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002230 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002231 arguments_ty args;
2232 expr_ty returns;
2233 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002234 asdl_expr_seq* decos;
2235 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002236 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002237 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002238 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002239 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002240
Yury Selivanov75445082015-05-11 22:57:16 -04002241 if (is_async) {
2242 assert(s->kind == AsyncFunctionDef_kind);
2243
2244 args = s->v.AsyncFunctionDef.args;
2245 returns = s->v.AsyncFunctionDef.returns;
2246 decos = s->v.AsyncFunctionDef.decorator_list;
2247 name = s->v.AsyncFunctionDef.name;
2248 body = s->v.AsyncFunctionDef.body;
2249
2250 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2251 } else {
2252 assert(s->kind == FunctionDef_kind);
2253
2254 args = s->v.FunctionDef.args;
2255 returns = s->v.FunctionDef.returns;
2256 decos = s->v.FunctionDef.decorator_list;
2257 name = s->v.FunctionDef.name;
2258 body = s->v.FunctionDef.body;
2259
2260 scope_type = COMPILER_SCOPE_FUNCTION;
2261 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002262
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002263 if (!compiler_check_debug_args(c, args))
2264 return 0;
2265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 if (!compiler_decorators(c, decos))
2267 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002268
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002269 firstlineno = s->lineno;
2270 if (asdl_seq_LEN(decos)) {
2271 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2272 }
2273
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002274 funcflags = compiler_default_arguments(c, args);
2275 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002277 }
2278
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002279 annotations = compiler_visit_annotations(c, args, returns);
2280 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002281 return 0;
2282 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002283 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002284 funcflags |= 0x04;
2285 }
2286
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002287 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002288 return 0;
2289 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290
INADA Naokicb41b272017-02-23 00:31:59 +09002291 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002292 if (c->c_optimize < 2) {
2293 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002294 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002295 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 compiler_exit_scope(c);
2297 return 0;
2298 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002301 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002303 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002304 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002305 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002307 qualname = c->u->u_qualname;
2308 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002310 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002311 Py_XDECREF(qualname);
2312 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002314 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002316 if (!compiler_make_closure(c, co, funcflags, qualname)) {
2317 Py_DECREF(qualname);
2318 Py_DECREF(co);
2319 return 0;
2320 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002321 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* decorators */
2325 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2326 ADDOP_I(c, CALL_FUNCTION, 1);
2327 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328
Yury Selivanov75445082015-05-11 22:57:16 -04002329 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330}
2331
2332static int
2333compiler_class(struct compiler *c, stmt_ty s)
2334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 PyCodeObject *co;
2336 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002337 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002338 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 if (!compiler_decorators(c, decos))
2341 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002342
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002343 firstlineno = s->lineno;
2344 if (asdl_seq_LEN(decos)) {
2345 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2346 }
2347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 /* ultimately generate code for:
2349 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2350 where:
2351 <func> is a function/closure created from the class body;
2352 it has a single argument (__locals__) where the dict
2353 (or MutableSequence) representing the locals is passed
2354 <name> is the class name
2355 <bases> is the positional arguments and *varargs argument
2356 <keywords> is the keyword arguments and **kwds argument
2357 This borrows from compiler_call.
2358 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002361 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002362 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return 0;
2364 /* this block represents what we do in the new scope */
2365 {
2366 /* use the class name for name mangling */
2367 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002368 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 /* load (global) __name__ ... */
2370 str = PyUnicode_InternFromString("__name__");
2371 if (!str || !compiler_nameop(c, str, Load)) {
2372 Py_XDECREF(str);
2373 compiler_exit_scope(c);
2374 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002375 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 Py_DECREF(str);
2377 /* ... and store it as __module__ */
2378 str = PyUnicode_InternFromString("__module__");
2379 if (!str || !compiler_nameop(c, str, Store)) {
2380 Py_XDECREF(str);
2381 compiler_exit_scope(c);
2382 return 0;
2383 }
2384 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002385 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002386 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002387 str = PyUnicode_InternFromString("__qualname__");
2388 if (!str || !compiler_nameop(c, str, Store)) {
2389 Py_XDECREF(str);
2390 compiler_exit_scope(c);
2391 return 0;
2392 }
2393 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002395 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 compiler_exit_scope(c);
2397 return 0;
2398 }
Mark Shannone56d54e2021-01-15 13:52:00 +00002399 /* The following code is artificial */
2400 c->u->u_lineno = -1;
Nick Coghlan19d24672016-12-05 16:47:55 +10002401 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002402 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002403 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002404 str = PyUnicode_InternFromString("__class__");
2405 if (str == NULL) {
2406 compiler_exit_scope(c);
2407 return 0;
2408 }
2409 i = compiler_lookup_arg(c->u->u_cellvars, str);
2410 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002411 if (i < 0) {
2412 compiler_exit_scope(c);
2413 return 0;
2414 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002415 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002418 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002419 str = PyUnicode_InternFromString("__classcell__");
2420 if (!str || !compiler_nameop(c, str, Store)) {
2421 Py_XDECREF(str);
2422 compiler_exit_scope(c);
2423 return 0;
2424 }
2425 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002427 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002428 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002429 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002430 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002431 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002432 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 /* create the code object */
2434 co = assemble(c, 1);
2435 }
2436 /* leave the new scope */
2437 compiler_exit_scope(c);
2438 if (co == NULL)
2439 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 /* 2. load the 'build_class' function */
2442 ADDOP(c, LOAD_BUILD_CLASS);
2443
2444 /* 3. load a function (or closure) made from the code object */
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002445 if (!compiler_make_closure(c, co, 0, NULL)) {
2446 Py_DECREF(co);
2447 return 0;
2448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 Py_DECREF(co);
2450
2451 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002452 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453
2454 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002455 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 return 0;
2457
2458 /* 6. apply decorators */
2459 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2460 ADDOP_I(c, CALL_FUNCTION, 1);
2461 }
2462
2463 /* 7. store into <name> */
2464 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2465 return 0;
2466 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467}
2468
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002469/* Return 0 if the expression is a constant value except named singletons.
2470 Return 1 otherwise. */
2471static int
2472check_is_arg(expr_ty e)
2473{
2474 if (e->kind != Constant_kind) {
2475 return 1;
2476 }
2477 PyObject *value = e->v.Constant.value;
2478 return (value == Py_None
2479 || value == Py_False
2480 || value == Py_True
2481 || value == Py_Ellipsis);
2482}
2483
2484/* Check operands of identity chacks ("is" and "is not").
2485 Emit a warning if any operand is a constant except named singletons.
2486 Return 0 on error.
2487 */
2488static int
2489check_compare(struct compiler *c, expr_ty e)
2490{
2491 Py_ssize_t i, n;
2492 int left = check_is_arg(e->v.Compare.left);
2493 n = asdl_seq_LEN(e->v.Compare.ops);
2494 for (i = 0; i < n; i++) {
2495 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2496 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2497 if (op == Is || op == IsNot) {
2498 if (!right || !left) {
2499 const char *msg = (op == Is)
2500 ? "\"is\" with a literal. Did you mean \"==\"?"
2501 : "\"is not\" with a literal. Did you mean \"!=\"?";
2502 return compiler_warn(c, msg);
2503 }
2504 }
2505 left = right;
2506 }
2507 return 1;
2508}
2509
Mark Shannon9af0e472020-01-14 10:12:45 +00002510static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002511{
Mark Shannon9af0e472020-01-14 10:12:45 +00002512 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002513 switch (op) {
2514 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002515 cmp = Py_EQ;
2516 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002517 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002518 cmp = Py_NE;
2519 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002520 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002521 cmp = Py_LT;
2522 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002523 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002524 cmp = Py_LE;
2525 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002526 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002527 cmp = Py_GT;
2528 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002529 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002530 cmp = Py_GE;
2531 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002532 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002533 ADDOP_I(c, IS_OP, 0);
2534 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002535 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002536 ADDOP_I(c, IS_OP, 1);
2537 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002538 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002539 ADDOP_I(c, CONTAINS_OP, 0);
2540 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002541 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002542 ADDOP_I(c, CONTAINS_OP, 1);
2543 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002544 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002545 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002546 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002547 ADDOP_I(c, COMPARE_OP, cmp);
2548 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002549}
2550
Mark Shannon9af0e472020-01-14 10:12:45 +00002551
2552
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002553static int
2554compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2555{
2556 switch (e->kind) {
2557 case UnaryOp_kind:
2558 if (e->v.UnaryOp.op == Not)
2559 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2560 /* fallback to general implementation */
2561 break;
2562 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002563 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002564 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2565 assert(n >= 0);
2566 int cond2 = e->v.BoolOp.op == Or;
2567 basicblock *next2 = next;
2568 if (!cond2 != !cond) {
2569 next2 = compiler_new_block(c);
2570 if (next2 == NULL)
2571 return 0;
2572 }
2573 for (i = 0; i < n; ++i) {
2574 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2575 return 0;
2576 }
2577 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2578 return 0;
2579 if (next2 != next)
2580 compiler_use_next_block(c, next2);
2581 return 1;
2582 }
2583 case IfExp_kind: {
2584 basicblock *end, *next2;
2585 end = compiler_new_block(c);
2586 if (end == NULL)
2587 return 0;
2588 next2 = compiler_new_block(c);
2589 if (next2 == NULL)
2590 return 0;
2591 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2592 return 0;
2593 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2594 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002595 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002596 compiler_use_next_block(c, next2);
2597 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2598 return 0;
2599 compiler_use_next_block(c, end);
2600 return 1;
2601 }
2602 case Compare_kind: {
2603 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2604 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002605 if (!check_compare(c, e)) {
2606 return 0;
2607 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002608 basicblock *cleanup = compiler_new_block(c);
2609 if (cleanup == NULL)
2610 return 0;
2611 VISIT(c, expr, e->v.Compare.left);
2612 for (i = 0; i < n; i++) {
2613 VISIT(c, expr,
2614 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2615 ADDOP(c, DUP_TOP);
2616 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002617 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002618 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002619 NEXT_BLOCK(c);
2620 }
2621 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002622 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002623 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002624 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002625 basicblock *end = compiler_new_block(c);
2626 if (end == NULL)
2627 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002628 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002629 compiler_use_next_block(c, cleanup);
2630 ADDOP(c, POP_TOP);
2631 if (!cond) {
Mark Shannon127dde52021-01-04 18:06:55 +00002632 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002633 }
2634 compiler_use_next_block(c, end);
2635 return 1;
2636 }
2637 /* fallback to general implementation */
2638 break;
2639 }
2640 default:
2641 /* fallback to general implementation */
2642 break;
2643 }
2644
2645 /* general implementation */
2646 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002647 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002648 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002649 return 1;
2650}
2651
2652static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002653compiler_ifexp(struct compiler *c, expr_ty e)
2654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 basicblock *end, *next;
2656
2657 assert(e->kind == IfExp_kind);
2658 end = compiler_new_block(c);
2659 if (end == NULL)
2660 return 0;
2661 next = compiler_new_block(c);
2662 if (next == NULL)
2663 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002664 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2665 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon127dde52021-01-04 18:06:55 +00002667 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 compiler_use_next_block(c, next);
2669 VISIT(c, expr, e->v.IfExp.orelse);
2670 compiler_use_next_block(c, end);
2671 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002672}
2673
2674static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002675compiler_lambda(struct compiler *c, expr_ty e)
2676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002678 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002680 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 arguments_ty args = e->v.Lambda.args;
2682 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002683
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002684 if (!compiler_check_debug_args(c, args))
2685 return 0;
2686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 if (!name) {
2688 name = PyUnicode_InternFromString("<lambda>");
2689 if (!name)
2690 return 0;
2691 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002693 funcflags = compiler_default_arguments(c, args);
2694 if (funcflags == -1) {
2695 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002697
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002698 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002699 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 /* Make None the first constant, so the lambda can't have a
2703 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002704 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002708 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2710 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2711 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002712 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 }
2714 else {
2715 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002716 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002718 qualname = c->u->u_qualname;
2719 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 compiler_exit_scope(c);
Pablo Galindo7fdab832021-01-29 22:40:59 +00002721 if (co == NULL) {
2722 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 return 0;
Pablo Galindo7fdab832021-01-29 22:40:59 +00002724 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002725
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002726 if (!compiler_make_closure(c, co, funcflags, qualname)) {
2727 Py_DECREF(qualname);
2728 Py_DECREF(co);
2729 return 0;
2730 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002731 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 Py_DECREF(co);
2733
2734 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002735}
2736
2737static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002738compiler_if(struct compiler *c, stmt_ty s)
2739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 assert(s->kind == If_kind);
2742 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002743 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002745 }
2746 if (asdl_seq_LEN(s->v.If.orelse)) {
2747 next = compiler_new_block(c);
2748 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002749 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002750 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002751 }
2752 else {
2753 next = end;
2754 }
2755 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2756 return 0;
2757 }
2758 VISIT_SEQ(c, stmt, s->v.If.body);
2759 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon127dde52021-01-04 18:06:55 +00002760 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Mark Shannon8473cf82020-12-15 11:07:50 +00002761 compiler_use_next_block(c, next);
2762 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 }
2764 compiler_use_next_block(c, end);
2765 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002766}
2767
2768static int
2769compiler_for(struct compiler *c, stmt_ty s)
2770{
Mark Shannon5977a792020-12-02 13:31:40 +00002771 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002774 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 cleanup = compiler_new_block(c);
2776 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002777 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002779 }
2780 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002782 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 VISIT(c, expr, s->v.For.iter);
2784 ADDOP(c, GET_ITER);
2785 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002786 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002787 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 VISIT(c, expr, s->v.For.target);
2789 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002790 /* Mark jump as artificial */
2791 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002792 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002794
2795 compiler_pop_fblock(c, FOR_LOOP, start);
2796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 VISIT_SEQ(c, stmt, s->v.For.orelse);
2798 compiler_use_next_block(c, end);
2799 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002800}
2801
Yury Selivanov75445082015-05-11 22:57:16 -04002802
2803static int
2804compiler_async_for(struct compiler *c, stmt_ty s)
2805{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002806 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002807 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002808 c->u->u_ste->ste_coroutine = 1;
2809 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002810 return compiler_error(c, "'async for' outside async function");
2811 }
2812
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002813 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002814 except = compiler_new_block(c);
2815 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002816
Mark Shannonfee55262019-11-21 09:11:43 +00002817 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002818 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002819 }
Yury Selivanov75445082015-05-11 22:57:16 -04002820 VISIT(c, expr, s->v.AsyncFor.iter);
2821 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002822
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002823 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002824 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002825 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002826 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002827 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002828 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002829 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002830 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002831 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002832 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002833
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002834 /* Success block for __anext__ */
2835 VISIT(c, expr, s->v.AsyncFor.target);
2836 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002837 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002838
2839 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002840
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002841 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002842 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002843
2844 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002845 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002846
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002847 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002848 VISIT_SEQ(c, stmt, s->v.For.orelse);
2849
2850 compiler_use_next_block(c, end);
2851
2852 return 1;
2853}
2854
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855static int
2856compiler_while(struct compiler *c, stmt_ty s)
2857{
Mark Shannon266b4622020-11-17 19:30:14 +00002858 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002860 body = compiler_new_block(c);
2861 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002863 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002867 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002870 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2871 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002872 }
2873
2874 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002876 SET_LOC(c, s);
2877 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2878 return 0;
2879 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 compiler_pop_fblock(c, WHILE_LOOP, loop);
2882
Mark Shannon266b4622020-11-17 19:30:14 +00002883 compiler_use_next_block(c, anchor);
2884 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002886 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890}
2891
2892static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002893compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002895 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002896 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002897 if (c->u->u_ste->ste_type != FunctionBlock)
2898 return compiler_error(c, "'return' outside function");
2899 if (s->v.Return.value != NULL &&
2900 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2901 {
2902 return compiler_error(
2903 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002905 if (preserve_tos) {
2906 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002907 } else {
2908 /* Emit instruction with line number for expression */
2909 if (s->v.Return.value != NULL) {
2910 SET_LOC(c, s->v.Return.value);
2911 ADDOP(c, NOP);
2912 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002913 }
Mark Shannonfee55262019-11-21 09:11:43 +00002914 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2915 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002916 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002917 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002918 }
2919 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00002920 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002921 }
2922 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002923 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002926}
2927
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002928static int
2929compiler_break(struct compiler *c)
2930{
Mark Shannonfee55262019-11-21 09:11:43 +00002931 struct fblockinfo *loop = NULL;
2932 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2933 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002934 }
Mark Shannonfee55262019-11-21 09:11:43 +00002935 if (loop == NULL) {
2936 return compiler_error(c, "'break' outside loop");
2937 }
2938 if (!compiler_unwind_fblock(c, loop, 0)) {
2939 return 0;
2940 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002941 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002942 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002943 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002944}
2945
2946static int
2947compiler_continue(struct compiler *c)
2948{
Mark Shannonfee55262019-11-21 09:11:43 +00002949 struct fblockinfo *loop = NULL;
2950 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2951 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002952 }
Mark Shannonfee55262019-11-21 09:11:43 +00002953 if (loop == NULL) {
2954 return compiler_error(c, "'continue' not properly in loop");
2955 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002956 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002957 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002958 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002959}
2960
2961
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002962/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963
2964 SETUP_FINALLY L
2965 <code for body>
2966 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002967 <code for finalbody>
2968 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002969 L:
2970 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002971 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973 The special instructions use the block stack. Each block
2974 stack entry contains the instruction that created it (here
2975 SETUP_FINALLY), the level of the value stack at the time the
2976 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002978 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 Pushes the current value stack level and the label
2980 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002981 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002982 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002984 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002985 when a SETUP_FINALLY entry is found, the raised and the caught
2986 exceptions are pushed onto the value stack (and the exception
2987 condition is cleared), and the interpreter jumps to the label
2988 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989*/
2990
2991static int
2992compiler_try_finally(struct compiler *c, stmt_ty s)
2993{
Mark Shannonfee55262019-11-21 09:11:43 +00002994 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 body = compiler_new_block(c);
2997 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002998 exit = compiler_new_block(c);
2999 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003001
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003002 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01003003 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003005 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003007 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
3008 if (!compiler_try_except(c, s))
3009 return 0;
3010 }
3011 else {
3012 VISIT_SEQ(c, stmt, s->v.Try.body);
3013 }
Mark Shannon3bd60352021-01-13 12:05:43 +00003014 ADDOP_NOLINE(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00003015 compiler_pop_fblock(c, FINALLY_TRY, body);
3016 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon127dde52021-01-04 18:06:55 +00003017 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00003018 /* `finally` block */
3019 compiler_use_next_block(c, end);
3020 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
3021 return 0;
3022 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3023 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00003024 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00003025 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027}
3028
3029/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003030 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003031 (The contents of the value stack is shown in [], with the top
3032 at the right; 'tb' is trace-back info, 'val' the exception's
3033 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034
3035 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003036 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 [] <code for S>
3038 [] POP_BLOCK
3039 [] JUMP_FORWARD L0
3040
3041 [tb, val, exc] L1: DUP )
3042 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003043 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 [tb, val, exc] POP
3045 [tb, val] <assign to V1> (or POP if no V1)
3046 [tb] POP
3047 [] <code for S1>
3048 JUMP_FORWARD L0
3049
3050 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003051 .............................etc.......................
3052
Mark Shannonfee55262019-11-21 09:11:43 +00003053 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054
3055 [] L0: <next statement>
3056
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057 Of course, parts are not generated if Vi or Ei is not present.
3058*/
3059static int
3060compiler_try_except(struct compiler *c, stmt_ty s)
3061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003063 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 body = compiler_new_block(c);
3066 except = compiler_new_block(c);
3067 orelse = compiler_new_block(c);
3068 end = compiler_new_block(c);
3069 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3070 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003071 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003073 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003075 VISIT_SEQ(c, stmt, s->v.Try.body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003076 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon3bd60352021-01-13 12:05:43 +00003077 ADDOP_NOLINE(c, POP_BLOCK);
3078 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003079 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003081 /* Runtime will push a block here, so we need to account for that */
3082 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3083 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 for (i = 0; i < n; i++) {
3085 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003086 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 if (!handler->v.ExceptHandler.type && i < n-1)
3088 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003089 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 except = compiler_new_block(c);
3091 if (except == NULL)
3092 return 0;
3093 if (handler->v.ExceptHandler.type) {
3094 ADDOP(c, DUP_TOP);
3095 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003096 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003097 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 }
3099 ADDOP(c, POP_TOP);
3100 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003102
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003103 cleanup_end = compiler_new_block(c);
3104 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003105 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003106 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003107 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003108
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3110 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003112 /*
3113 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003114 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003116 try:
3117 # body
3118 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003119 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003120 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003121 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003123 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003124 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003125 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003126 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003127 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003129 /* second # body */
3130 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003131 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003132 ADDOP(c, POP_BLOCK);
3133 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003134 /* name = None; del name; # Mark as artificial */
3135 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003136 ADDOP_LOAD_CONST(c, Py_None);
3137 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3138 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003139 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140
Mark Shannonfee55262019-11-21 09:11:43 +00003141 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003142 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143
Mark Shannon877df852020-11-12 09:43:29 +00003144 /* name = None; del name; # Mark as artificial */
3145 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003146 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003147 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003148 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149
Mark Shannonbf353f32020-12-17 13:55:28 +00003150 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 }
3152 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003153 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003155 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003156 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003157 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158
Guido van Rossumb940e112007-01-10 16:19:56 +00003159 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003160 ADDOP(c, POP_TOP);
3161 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003162 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003163 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003165 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannon127dde52021-01-04 18:06:55 +00003166 /* name = None; del name; # Mark as artificial */
3167 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003168 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003169 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 compiler_use_next_block(c, except);
3172 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003173 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003174 /* Mark as artificial */
3175 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003176 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003178 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 compiler_use_next_block(c, end);
3180 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181}
3182
3183static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003184compiler_try(struct compiler *c, stmt_ty s) {
3185 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3186 return compiler_try_finally(c, s);
3187 else
3188 return compiler_try_except(c, s);
3189}
3190
3191
3192static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003193compiler_import_as(struct compiler *c, identifier name, identifier asname)
3194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 /* The IMPORT_NAME opcode was already generated. This function
3196 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003199 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003201 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3202 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003203 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003204 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003205 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003207 while (1) {
3208 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003210 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003211 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003212 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003213 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003215 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003216 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003217 if (dot == -1) {
3218 break;
3219 }
3220 ADDOP(c, ROT_TWO);
3221 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003222 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003223 if (!compiler_nameop(c, asname, Store)) {
3224 return 0;
3225 }
3226 ADDOP(c, POP_TOP);
3227 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 }
3229 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003230}
3231
3232static int
3233compiler_import(struct compiler *c, stmt_ty s)
3234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 /* The Import node stores a module name like a.b.c as a single
3236 string. This is convenient for all cases except
3237 import a.b.c as d
3238 where we need to parse that string to extract the individual
3239 module names.
3240 XXX Perhaps change the representation to make this case simpler?
3241 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003242 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003243
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003244 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 for (i = 0; i < n; i++) {
3246 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3247 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003249 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003250 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 if (alias->asname) {
3254 r = compiler_import_as(c, alias->name, alias->asname);
3255 if (!r)
3256 return r;
3257 }
3258 else {
3259 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003260 Py_ssize_t dot = PyUnicode_FindChar(
3261 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003262 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003263 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003264 if (tmp == NULL)
3265 return 0;
3266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003268 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 Py_DECREF(tmp);
3270 }
3271 if (!r)
3272 return r;
3273 }
3274 }
3275 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276}
3277
3278static int
3279compiler_from_import(struct compiler *c, stmt_ty s)
3280{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003281 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003282 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 if (!empty_string) {
3286 empty_string = PyUnicode_FromString("");
3287 if (!empty_string)
3288 return 0;
3289 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003290
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003291 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003292
3293 names = PyTuple_New(n);
3294 if (!names)
3295 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 /* build up the names */
3298 for (i = 0; i < n; i++) {
3299 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3300 Py_INCREF(alias->name);
3301 PyTuple_SET_ITEM(names, i, alias->name);
3302 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003305 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 Py_DECREF(names);
3307 return compiler_error(c, "from __future__ imports must occur "
3308 "at the beginning of the file");
3309 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003310 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 if (s->v.ImportFrom.module) {
3313 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3314 }
3315 else {
3316 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3317 }
3318 for (i = 0; i < n; i++) {
3319 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3320 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003322 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003323 assert(n == 1);
3324 ADDOP(c, IMPORT_STAR);
3325 return 1;
3326 }
3327
3328 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3329 store_name = alias->name;
3330 if (alias->asname)
3331 store_name = alias->asname;
3332
3333 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 return 0;
3335 }
3336 }
3337 /* remove imported module */
3338 ADDOP(c, POP_TOP);
3339 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340}
3341
3342static int
3343compiler_assert(struct compiler *c, stmt_ty s)
3344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003346
tsukasa-aua8ef4572021-03-16 22:14:41 +11003347 /* Always emit a warning if the test is a non-zero length tuple */
3348 if ((s->v.Assert.test->kind == Tuple_kind &&
3349 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) ||
3350 (s->v.Assert.test->kind == Constant_kind &&
3351 PyTuple_Check(s->v.Assert.test->v.Constant.value) &&
3352 PyTuple_Size(s->v.Assert.test->v.Constant.value) > 0))
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003353 {
3354 if (!compiler_warn(c, "assertion is always true, "
3355 "perhaps remove parentheses?"))
3356 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003357 return 0;
3358 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 }
tsukasa-aua8ef4572021-03-16 22:14:41 +11003360 if (c->c_optimize)
3361 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 end = compiler_new_block(c);
3363 if (end == NULL)
3364 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003365 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3366 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003367 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 if (s->v.Assert.msg) {
3369 VISIT(c, expr, s->v.Assert.msg);
3370 ADDOP_I(c, CALL_FUNCTION, 1);
3371 }
3372 ADDOP_I(c, RAISE_VARARGS, 1);
3373 compiler_use_next_block(c, end);
3374 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003375}
3376
3377static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003378compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3379{
3380 if (c->c_interactive && c->c_nestlevel <= 1) {
3381 VISIT(c, expr, value);
3382 ADDOP(c, PRINT_EXPR);
3383 return 1;
3384 }
3385
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003386 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003387 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003388 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003389 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003390 }
3391
3392 VISIT(c, expr, value);
Mark Shannonc5440932021-03-15 14:24:25 +00003393 /* Mark POP_TOP as artificial */
3394 c->u->u_lineno = -1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003395 ADDOP(c, POP_TOP);
3396 return 1;
3397}
3398
3399static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003400compiler_visit_stmt(struct compiler *c, stmt_ty s)
3401{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003402 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003405 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 switch (s->kind) {
3408 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003409 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 case ClassDef_kind:
3411 return compiler_class(c, s);
3412 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003413 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 case Delete_kind:
3415 VISIT_SEQ(c, expr, s->v.Delete.targets)
3416 break;
3417 case Assign_kind:
3418 n = asdl_seq_LEN(s->v.Assign.targets);
3419 VISIT(c, expr, s->v.Assign.value);
3420 for (i = 0; i < n; i++) {
3421 if (i < n - 1)
3422 ADDOP(c, DUP_TOP);
3423 VISIT(c, expr,
3424 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3425 }
3426 break;
3427 case AugAssign_kind:
3428 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003429 case AnnAssign_kind:
3430 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003431 case For_kind:
3432 return compiler_for(c, s);
3433 case While_kind:
3434 return compiler_while(c, s);
3435 case If_kind:
3436 return compiler_if(c, s);
Brandt Bucher145bf262021-02-26 14:51:55 -08003437 case Match_kind:
3438 return compiler_match(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003439 case Raise_kind:
3440 n = 0;
3441 if (s->v.Raise.exc) {
3442 VISIT(c, expr, s->v.Raise.exc);
3443 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003444 if (s->v.Raise.cause) {
3445 VISIT(c, expr, s->v.Raise.cause);
3446 n++;
3447 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003449 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003450 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003452 case Try_kind:
3453 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 case Assert_kind:
3455 return compiler_assert(c, s);
3456 case Import_kind:
3457 return compiler_import(c, s);
3458 case ImportFrom_kind:
3459 return compiler_from_import(c, s);
3460 case Global_kind:
3461 case Nonlocal_kind:
3462 break;
3463 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003464 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003466 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 break;
3468 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003469 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 case Continue_kind:
3471 return compiler_continue(c);
3472 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003473 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003474 case AsyncFunctionDef_kind:
3475 return compiler_function(c, s, 1);
3476 case AsyncWith_kind:
3477 return compiler_async_with(c, s, 0);
3478 case AsyncFor_kind:
3479 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 }
Yury Selivanov75445082015-05-11 22:57:16 -04003481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003483}
3484
3485static int
3486unaryop(unaryop_ty op)
3487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003488 switch (op) {
3489 case Invert:
3490 return UNARY_INVERT;
3491 case Not:
3492 return UNARY_NOT;
3493 case UAdd:
3494 return UNARY_POSITIVE;
3495 case USub:
3496 return UNARY_NEGATIVE;
3497 default:
3498 PyErr_Format(PyExc_SystemError,
3499 "unary op %d should not be possible", op);
3500 return 0;
3501 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003502}
3503
3504static int
Andy Lester76d58772020-03-10 21:18:12 -05003505binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 switch (op) {
3508 case Add:
3509 return BINARY_ADD;
3510 case Sub:
3511 return BINARY_SUBTRACT;
3512 case Mult:
3513 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003514 case MatMult:
3515 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003516 case Div:
3517 return BINARY_TRUE_DIVIDE;
3518 case Mod:
3519 return BINARY_MODULO;
3520 case Pow:
3521 return BINARY_POWER;
3522 case LShift:
3523 return BINARY_LSHIFT;
3524 case RShift:
3525 return BINARY_RSHIFT;
3526 case BitOr:
3527 return BINARY_OR;
3528 case BitXor:
3529 return BINARY_XOR;
3530 case BitAnd:
3531 return BINARY_AND;
3532 case FloorDiv:
3533 return BINARY_FLOOR_DIVIDE;
3534 default:
3535 PyErr_Format(PyExc_SystemError,
3536 "binary op %d should not be possible", op);
3537 return 0;
3538 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003539}
3540
3541static int
Andy Lester76d58772020-03-10 21:18:12 -05003542inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003544 switch (op) {
3545 case Add:
3546 return INPLACE_ADD;
3547 case Sub:
3548 return INPLACE_SUBTRACT;
3549 case Mult:
3550 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003551 case MatMult:
3552 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 case Div:
3554 return INPLACE_TRUE_DIVIDE;
3555 case Mod:
3556 return INPLACE_MODULO;
3557 case Pow:
3558 return INPLACE_POWER;
3559 case LShift:
3560 return INPLACE_LSHIFT;
3561 case RShift:
3562 return INPLACE_RSHIFT;
3563 case BitOr:
3564 return INPLACE_OR;
3565 case BitXor:
3566 return INPLACE_XOR;
3567 case BitAnd:
3568 return INPLACE_AND;
3569 case FloorDiv:
3570 return INPLACE_FLOOR_DIVIDE;
3571 default:
3572 PyErr_Format(PyExc_SystemError,
3573 "inplace binary op %d should not be possible", op);
3574 return 0;
3575 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576}
3577
3578static int
3579compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3580{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003581 int op, scope;
3582 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 PyObject *dict = c->u->u_names;
3586 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003587
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003588 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3589 !_PyUnicode_EqualToASCIIString(name, "True") &&
3590 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003591
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003592 if (forbidden_name(c, name, ctx))
3593 return 0;
3594
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003595 mangled = _Py_Mangle(c->u->u_private, name);
3596 if (!mangled)
3597 return 0;
3598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 op = 0;
3600 optype = OP_NAME;
Victor Stinner28ad12f2021-03-19 12:41:49 +01003601 scope = _PyST_GetScope(c->u->u_ste, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 switch (scope) {
3603 case FREE:
3604 dict = c->u->u_freevars;
3605 optype = OP_DEREF;
3606 break;
3607 case CELL:
3608 dict = c->u->u_cellvars;
3609 optype = OP_DEREF;
3610 break;
3611 case LOCAL:
3612 if (c->u->u_ste->ste_type == FunctionBlock)
3613 optype = OP_FAST;
3614 break;
3615 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003616 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 optype = OP_GLOBAL;
3618 break;
3619 case GLOBAL_EXPLICIT:
3620 optype = OP_GLOBAL;
3621 break;
3622 default:
3623 /* scope can be 0 */
3624 break;
3625 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003627 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003628 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 switch (optype) {
3631 case OP_DEREF:
3632 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003633 case Load:
3634 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3635 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003636 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003637 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 }
3639 break;
3640 case OP_FAST:
3641 switch (ctx) {
3642 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003643 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003646 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003647 return 1;
3648 case OP_GLOBAL:
3649 switch (ctx) {
3650 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003651 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003652 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 }
3654 break;
3655 case OP_NAME:
3656 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003657 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003658 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003660 }
3661 break;
3662 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003665 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003666 Py_DECREF(mangled);
3667 if (arg < 0)
3668 return 0;
3669 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003670}
3671
3672static int
3673compiler_boolop(struct compiler *c, expr_ty e)
3674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003676 int jumpi;
3677 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003678 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003680 assert(e->kind == BoolOp_kind);
3681 if (e->v.BoolOp.op == And)
3682 jumpi = JUMP_IF_FALSE_OR_POP;
3683 else
3684 jumpi = JUMP_IF_TRUE_OR_POP;
3685 end = compiler_new_block(c);
3686 if (end == NULL)
3687 return 0;
3688 s = e->v.BoolOp.values;
3689 n = asdl_seq_LEN(s) - 1;
3690 assert(n >= 0);
3691 for (i = 0; i < n; ++i) {
3692 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003693 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003694 basicblock *next = compiler_new_block(c);
3695 if (next == NULL) {
3696 return 0;
3697 }
3698 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003699 }
3700 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3701 compiler_use_next_block(c, end);
3702 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003703}
3704
3705static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003706starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003707 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003708{
3709 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003710 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003711 if (n > 2 && are_all_items_const(elts, 0, n)) {
3712 PyObject *folded = PyTuple_New(n);
3713 if (folded == NULL) {
3714 return 0;
3715 }
3716 PyObject *val;
3717 for (i = 0; i < n; i++) {
3718 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3719 Py_INCREF(val);
3720 PyTuple_SET_ITEM(folded, i, val);
3721 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003722 if (tuple) {
3723 ADDOP_LOAD_CONST_NEW(c, folded);
3724 } else {
3725 if (add == SET_ADD) {
3726 Py_SETREF(folded, PyFrozenSet_New(folded));
3727 if (folded == NULL) {
3728 return 0;
3729 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003730 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003731 ADDOP_I(c, build, pushed);
3732 ADDOP_LOAD_CONST_NEW(c, folded);
3733 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003734 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003735 return 1;
3736 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003737
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003738 for (i = 0; i < n; i++) {
3739 expr_ty elt = asdl_seq_GET(elts, i);
3740 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003741 seen_star = 1;
3742 }
3743 }
3744 if (seen_star) {
3745 seen_star = 0;
3746 for (i = 0; i < n; i++) {
3747 expr_ty elt = asdl_seq_GET(elts, i);
3748 if (elt->kind == Starred_kind) {
3749 if (seen_star == 0) {
3750 ADDOP_I(c, build, i+pushed);
3751 seen_star = 1;
3752 }
3753 VISIT(c, expr, elt->v.Starred.value);
3754 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003755 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003756 else {
3757 VISIT(c, expr, elt);
3758 if (seen_star) {
3759 ADDOP_I(c, add, 1);
3760 }
3761 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003762 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003763 assert(seen_star);
3764 if (tuple) {
3765 ADDOP(c, LIST_TO_TUPLE);
3766 }
3767 }
3768 else {
3769 for (i = 0; i < n; i++) {
3770 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003771 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003772 }
3773 if (tuple) {
3774 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3775 } else {
3776 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003777 }
3778 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003779 return 1;
3780}
3781
3782static int
Brandt Bucher145bf262021-02-26 14:51:55 -08003783unpack_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003784{
3785 Py_ssize_t n = asdl_seq_LEN(elts);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003786 int seen_star = 0;
Brandt Bucher145bf262021-02-26 14:51:55 -08003787 for (Py_ssize_t i = 0; i < n; i++) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003788 expr_ty elt = asdl_seq_GET(elts, i);
3789 if (elt->kind == Starred_kind && !seen_star) {
3790 if ((i >= (1 << 8)) ||
3791 (n-i-1 >= (INT_MAX >> 8)))
3792 return compiler_error(c,
3793 "too many expressions in "
3794 "star-unpacking assignment");
3795 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3796 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003797 }
3798 else if (elt->kind == Starred_kind) {
3799 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003800 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003801 }
3802 }
3803 if (!seen_star) {
3804 ADDOP_I(c, UNPACK_SEQUENCE, n);
3805 }
Brandt Bucher145bf262021-02-26 14:51:55 -08003806 return 1;
3807}
3808
3809static int
3810assignment_helper(struct compiler *c, asdl_expr_seq *elts)
3811{
3812 Py_ssize_t n = asdl_seq_LEN(elts);
3813 RETURN_IF_FALSE(unpack_helper(c, elts));
3814 for (Py_ssize_t i = 0; i < n; i++) {
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003815 expr_ty elt = asdl_seq_GET(elts, i);
3816 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3817 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003818 return 1;
3819}
3820
3821static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003822compiler_list(struct compiler *c, expr_ty e)
3823{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003824 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003825 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003826 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003827 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003828 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003829 return starunpack_helper(c, elts, 0, BUILD_LIST,
3830 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003831 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003832 else
3833 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003834 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003835}
3836
3837static int
3838compiler_tuple(struct compiler *c, expr_ty e)
3839{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003840 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003841 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003842 return assignment_helper(c, elts);
3843 }
3844 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003845 return starunpack_helper(c, elts, 0, BUILD_LIST,
3846 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003847 }
3848 else
3849 VISIT_SEQ(c, expr, elts);
3850 return 1;
3851}
3852
3853static int
3854compiler_set(struct compiler *c, expr_ty e)
3855{
Mark Shannon13bc1392020-01-23 09:25:17 +00003856 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3857 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003858}
3859
3860static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003861are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003862{
3863 Py_ssize_t i;
3864 for (i = begin; i < end; i++) {
3865 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003866 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003867 return 0;
3868 }
3869 return 1;
3870}
3871
3872static int
3873compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3874{
3875 Py_ssize_t i, n = end - begin;
3876 PyObject *keys, *key;
3877 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3878 for (i = begin; i < end; i++) {
3879 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3880 }
3881 keys = PyTuple_New(n);
3882 if (keys == NULL) {
3883 return 0;
3884 }
3885 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003886 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003887 Py_INCREF(key);
3888 PyTuple_SET_ITEM(keys, i - begin, key);
3889 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003890 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003891 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3892 }
3893 else {
3894 for (i = begin; i < end; i++) {
3895 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3896 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3897 }
3898 ADDOP_I(c, BUILD_MAP, n);
3899 }
3900 return 1;
3901}
3902
3903static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003904compiler_dict(struct compiler *c, expr_ty e)
3905{
Victor Stinner976bb402016-03-23 11:36:19 +01003906 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003907 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003908 int is_unpacking = 0;
3909 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003910 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003911 elements = 0;
3912 for (i = 0; i < n; i++) {
3913 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003914 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003915 if (elements) {
3916 if (!compiler_subdict(c, e, i - elements, i)) {
3917 return 0;
3918 }
3919 if (have_dict) {
3920 ADDOP_I(c, DICT_UPDATE, 1);
3921 }
3922 have_dict = 1;
3923 elements = 0;
3924 }
3925 if (have_dict == 0) {
3926 ADDOP_I(c, BUILD_MAP, 0);
3927 have_dict = 1;
3928 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003929 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003930 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003931 }
3932 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003933 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003934 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003935 return 0;
3936 }
3937 if (have_dict) {
3938 ADDOP_I(c, DICT_UPDATE, 1);
3939 }
3940 have_dict = 1;
3941 elements = 0;
3942 }
3943 else {
3944 elements++;
3945 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 }
3947 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003948 if (elements) {
3949 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003950 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003951 }
3952 if (have_dict) {
3953 ADDOP_I(c, DICT_UPDATE, 1);
3954 }
3955 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003956 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003957 if (!have_dict) {
3958 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003959 }
3960 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003961}
3962
3963static int
3964compiler_compare(struct compiler *c, expr_ty e)
3965{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003966 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003967
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003968 if (!check_compare(c, e)) {
3969 return 0;
3970 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003971 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003972 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3973 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3974 if (n == 0) {
3975 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003976 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003977 }
3978 else {
3979 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003980 if (cleanup == NULL)
3981 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003982 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003983 VISIT(c, expr,
3984 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003985 ADDOP(c, DUP_TOP);
3986 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003987 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003988 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003989 NEXT_BLOCK(c);
3990 }
3991 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003992 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003993 basicblock *end = compiler_new_block(c);
3994 if (end == NULL)
3995 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00003996 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003997 compiler_use_next_block(c, cleanup);
3998 ADDOP(c, ROT_TWO);
3999 ADDOP(c, POP_TOP);
4000 compiler_use_next_block(c, end);
4001 }
4002 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004003}
4004
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004005static PyTypeObject *
4006infer_type(expr_ty e)
4007{
4008 switch (e->kind) {
4009 case Tuple_kind:
4010 return &PyTuple_Type;
4011 case List_kind:
4012 case ListComp_kind:
4013 return &PyList_Type;
4014 case Dict_kind:
4015 case DictComp_kind:
4016 return &PyDict_Type;
4017 case Set_kind:
4018 case SetComp_kind:
4019 return &PySet_Type;
4020 case GeneratorExp_kind:
4021 return &PyGen_Type;
4022 case Lambda_kind:
4023 return &PyFunction_Type;
4024 case JoinedStr_kind:
4025 case FormattedValue_kind:
4026 return &PyUnicode_Type;
4027 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01004028 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004029 default:
4030 return NULL;
4031 }
4032}
4033
4034static int
4035check_caller(struct compiler *c, expr_ty e)
4036{
4037 switch (e->kind) {
4038 case Constant_kind:
4039 case Tuple_kind:
4040 case List_kind:
4041 case ListComp_kind:
4042 case Dict_kind:
4043 case DictComp_kind:
4044 case Set_kind:
4045 case SetComp_kind:
4046 case GeneratorExp_kind:
4047 case JoinedStr_kind:
4048 case FormattedValue_kind:
4049 return compiler_warn(c, "'%.200s' object is not callable; "
4050 "perhaps you missed a comma?",
4051 infer_type(e)->tp_name);
4052 default:
4053 return 1;
4054 }
4055}
4056
4057static int
4058check_subscripter(struct compiler *c, expr_ty e)
4059{
4060 PyObject *v;
4061
4062 switch (e->kind) {
4063 case Constant_kind:
4064 v = e->v.Constant.value;
4065 if (!(v == Py_None || v == Py_Ellipsis ||
4066 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4067 PyAnySet_Check(v)))
4068 {
4069 return 1;
4070 }
4071 /* fall through */
4072 case Set_kind:
4073 case SetComp_kind:
4074 case GeneratorExp_kind:
4075 case Lambda_kind:
4076 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4077 "perhaps you missed a comma?",
4078 infer_type(e)->tp_name);
4079 default:
4080 return 1;
4081 }
4082}
4083
4084static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004085check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004086{
4087 PyObject *v;
4088
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004089 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004090 if (index_type == NULL
4091 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4092 || index_type == &PySlice_Type) {
4093 return 1;
4094 }
4095
4096 switch (e->kind) {
4097 case Constant_kind:
4098 v = e->v.Constant.value;
4099 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4100 return 1;
4101 }
4102 /* fall through */
4103 case Tuple_kind:
4104 case List_kind:
4105 case ListComp_kind:
4106 case JoinedStr_kind:
4107 case FormattedValue_kind:
4108 return compiler_warn(c, "%.200s indices must be integers or slices, "
4109 "not %.200s; "
4110 "perhaps you missed a comma?",
4111 infer_type(e)->tp_name,
4112 index_type->tp_name);
4113 default:
4114 return 1;
4115 }
4116}
4117
Zackery Spytz97f5de02019-03-22 01:30:32 -06004118// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004119static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004120maybe_optimize_method_call(struct compiler *c, expr_ty e)
4121{
4122 Py_ssize_t argsl, i;
4123 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004124 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004125
4126 /* Check that the call node is an attribute access, and that
4127 the call doesn't have keyword parameters. */
4128 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4129 asdl_seq_LEN(e->v.Call.keywords))
4130 return -1;
4131
4132 /* Check that there are no *varargs types of arguments. */
4133 argsl = asdl_seq_LEN(args);
4134 for (i = 0; i < argsl; i++) {
4135 expr_ty elt = asdl_seq_GET(args, i);
4136 if (elt->kind == Starred_kind) {
4137 return -1;
4138 }
4139 }
4140
4141 /* Alright, we can optimize the code. */
4142 VISIT(c, expr, meth->v.Attribute.value);
Mark Shannond48848c2021-03-14 18:01:30 +00004143 int old_lineno = c->u->u_lineno;
4144 c->u->u_lineno = meth->end_lineno;
Yury Selivanovf2392132016-12-13 19:03:51 -05004145 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4146 VISIT_SEQ(c, expr, e->v.Call.args);
4147 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
Mark Shannond48848c2021-03-14 18:01:30 +00004148 c->u->u_lineno = old_lineno;
Yury Selivanovf2392132016-12-13 19:03:51 -05004149 return 1;
4150}
4151
4152static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004153validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004154{
4155 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4156 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004157 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4158 if (key->arg == NULL) {
4159 continue;
4160 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004161 if (forbidden_name(c, key->arg, Store)) {
4162 return -1;
4163 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004164 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004165 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4166 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004167 c->u->u_col_offset = other->col_offset;
Brandt Bucher145bf262021-02-26 14:51:55 -08004168 compiler_error(c, "keyword argument repeated: %U", key->arg);
Pablo Galindo254ec782020-04-03 20:37:13 +01004169 return -1;
4170 }
4171 }
4172 }
4173 return 0;
4174}
4175
4176static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004177compiler_call(struct compiler *c, expr_ty e)
4178{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004179 int ret = maybe_optimize_method_call(c, e);
4180 if (ret >= 0) {
4181 return ret;
4182 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004183 if (!check_caller(c, e->v.Call.func)) {
4184 return 0;
4185 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004186 VISIT(c, expr, e->v.Call.func);
4187 return compiler_call_helper(c, 0,
4188 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004189 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004190}
4191
Eric V. Smith235a6f02015-09-19 14:51:32 -04004192static int
4193compiler_joined_str(struct compiler *c, expr_ty e)
4194{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004195 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004196 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4197 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004198 return 1;
4199}
4200
Eric V. Smitha78c7952015-11-03 12:45:05 -05004201/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004202static int
4203compiler_formatted_value(struct compiler *c, expr_ty e)
4204{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004205 /* Our oparg encodes 2 pieces of information: the conversion
4206 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004207
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004208 Convert the conversion char to 3 bits:
4209 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004210 !s : 001 0x1 FVC_STR
4211 !r : 010 0x2 FVC_REPR
4212 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004213
Eric V. Smitha78c7952015-11-03 12:45:05 -05004214 next bit is whether or not we have a format spec:
4215 yes : 100 0x4
4216 no : 000 0x0
4217 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004218
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004219 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004220 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004221
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004222 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004223 VISIT(c, expr, e->v.FormattedValue.value);
4224
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004225 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004226 case 's': oparg = FVC_STR; break;
4227 case 'r': oparg = FVC_REPR; break;
4228 case 'a': oparg = FVC_ASCII; break;
4229 case -1: oparg = FVC_NONE; break;
4230 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004231 PyErr_Format(PyExc_SystemError,
4232 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004233 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004234 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004235 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004236 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004237 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004238 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004239 }
4240
Eric V. Smitha78c7952015-11-03 12:45:05 -05004241 /* And push our opcode and oparg */
4242 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004243
Eric V. Smith235a6f02015-09-19 14:51:32 -04004244 return 1;
4245}
4246
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004247static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004248compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004249{
4250 Py_ssize_t i, n = end - begin;
4251 keyword_ty kw;
4252 PyObject *keys, *key;
4253 assert(n > 0);
4254 if (n > 1) {
4255 for (i = begin; i < end; i++) {
4256 kw = asdl_seq_GET(keywords, i);
4257 VISIT(c, expr, kw->value);
4258 }
4259 keys = PyTuple_New(n);
4260 if (keys == NULL) {
4261 return 0;
4262 }
4263 for (i = begin; i < end; i++) {
4264 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4265 Py_INCREF(key);
4266 PyTuple_SET_ITEM(keys, i - begin, key);
4267 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004268 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004269 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4270 }
4271 else {
4272 /* a for loop only executes once */
4273 for (i = begin; i < end; i++) {
4274 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004275 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004276 VISIT(c, expr, kw->value);
4277 }
4278 ADDOP_I(c, BUILD_MAP, n);
4279 }
4280 return 1;
4281}
4282
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004283/* shared code between compiler_call and compiler_class */
4284static int
4285compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004286 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004287 asdl_expr_seq *args,
4288 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004289{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004290 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004291
Pablo Galindo254ec782020-04-03 20:37:13 +01004292 if (validate_keywords(c, keywords) == -1) {
4293 return 0;
4294 }
4295
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004296 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004297 nkwelts = asdl_seq_LEN(keywords);
4298
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004299 for (i = 0; i < nelts; i++) {
4300 expr_ty elt = asdl_seq_GET(args, i);
4301 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004302 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004303 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004304 }
4305 for (i = 0; i < nkwelts; i++) {
4306 keyword_ty kw = asdl_seq_GET(keywords, i);
4307 if (kw->arg == NULL) {
4308 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004309 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004310 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004311
Mark Shannon13bc1392020-01-23 09:25:17 +00004312 /* No * or ** args, so can use faster calling sequence */
4313 for (i = 0; i < nelts; i++) {
4314 expr_ty elt = asdl_seq_GET(args, i);
4315 assert(elt->kind != Starred_kind);
4316 VISIT(c, expr, elt);
4317 }
4318 if (nkwelts) {
4319 PyObject *names;
4320 VISIT_SEQ(c, keyword, keywords);
4321 names = PyTuple_New(nkwelts);
4322 if (names == NULL) {
4323 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004324 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004325 for (i = 0; i < nkwelts; i++) {
4326 keyword_ty kw = asdl_seq_GET(keywords, i);
4327 Py_INCREF(kw->arg);
4328 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004329 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004330 ADDOP_LOAD_CONST_NEW(c, names);
4331 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4332 return 1;
4333 }
4334 else {
4335 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4336 return 1;
4337 }
4338
4339ex_call:
4340
4341 /* Do positional arguments. */
4342 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4343 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4344 }
4345 else if (starunpack_helper(c, args, n, BUILD_LIST,
4346 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4347 return 0;
4348 }
4349 /* Then keyword arguments */
4350 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004351 /* Has a new dict been pushed */
4352 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004353
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004354 nseen = 0; /* the number of keyword arguments on the stack following */
4355 for (i = 0; i < nkwelts; i++) {
4356 keyword_ty kw = asdl_seq_GET(keywords, i);
4357 if (kw->arg == NULL) {
4358 /* A keyword argument unpacking. */
4359 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004360 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004361 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004362 }
Mark Shannondb64f122020-06-01 10:42:42 +01004363 if (have_dict) {
4364 ADDOP_I(c, DICT_MERGE, 1);
4365 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004366 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004367 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004368 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004369 if (!have_dict) {
4370 ADDOP_I(c, BUILD_MAP, 0);
4371 have_dict = 1;
4372 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004373 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004374 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004375 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004376 else {
4377 nseen++;
4378 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004379 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004380 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004381 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004382 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004383 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004384 }
4385 if (have_dict) {
4386 ADDOP_I(c, DICT_MERGE, 1);
4387 }
4388 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004389 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004390 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004392 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4393 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004394}
4395
Nick Coghlan650f0d02007-04-15 12:05:43 +00004396
4397/* List and set comprehensions and generator expressions work by creating a
4398 nested function to perform the actual iteration. This means that the
4399 iteration variables don't leak into the current scope.
4400 The defined function is called immediately following its definition, with the
4401 result of that call being the result of the expression.
4402 The LC/SC version returns the populated container, while the GE version is
4403 flagged in symtable.c as a generator, so it returns the generator object
4404 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004405
4406 Possible cleanups:
4407 - iterate over the generator sequence instead of using recursion
4408*/
4409
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004410
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004413 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004414 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004416{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004417 comprehension_ty gen;
4418 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4419 if (gen->is_async) {
4420 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004421 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004422 } else {
4423 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004424 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004425 }
4426}
4427
4428static int
4429compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004430 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004431 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004432 expr_ty elt, expr_ty val, int type)
4433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004434 /* generate code for the iterator, then each of the ifs,
4435 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004437 comprehension_ty gen;
4438 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004439 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 start = compiler_new_block(c);
4442 skip = compiler_new_block(c);
4443 if_cleanup = compiler_new_block(c);
4444 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4447 anchor == NULL)
4448 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004452 if (gen_index == 0) {
4453 /* Receive outermost iter as an implicit argument */
4454 c->u->u_argcount = 1;
4455 ADDOP_I(c, LOAD_FAST, 0);
4456 }
4457 else {
4458 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004459 /* Fast path for the temporary variable assignment idiom:
4460 for y in [f(x)]
4461 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004462 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004463 switch (gen->iter->kind) {
4464 case List_kind:
4465 elts = gen->iter->v.List.elts;
4466 break;
4467 case Tuple_kind:
4468 elts = gen->iter->v.Tuple.elts;
4469 break;
4470 default:
4471 elts = NULL;
4472 }
4473 if (asdl_seq_LEN(elts) == 1) {
4474 expr_ty elt = asdl_seq_GET(elts, 0);
4475 if (elt->kind != Starred_kind) {
4476 VISIT(c, expr, elt);
4477 start = NULL;
4478 }
4479 }
4480 if (start) {
4481 VISIT(c, expr, gen->iter);
4482 ADDOP(c, GET_ITER);
4483 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004485 if (start) {
4486 depth++;
4487 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004488 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004489 NEXT_BLOCK(c);
4490 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 /* XXX this needs to be cleaned up...a lot! */
4494 n = asdl_seq_LEN(gen->ifs);
4495 for (i = 0; i < n; i++) {
4496 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004497 if (!compiler_jump_if(c, e, if_cleanup, 0))
4498 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 NEXT_BLOCK(c);
4500 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 if (++gen_index < asdl_seq_LEN(generators))
4503 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004504 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 elt, val, type))
4506 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004508 /* only append after the last for generator */
4509 if (gen_index >= asdl_seq_LEN(generators)) {
4510 /* comprehension specific code */
4511 switch (type) {
4512 case COMP_GENEXP:
4513 VISIT(c, expr, elt);
4514 ADDOP(c, YIELD_VALUE);
4515 ADDOP(c, POP_TOP);
4516 break;
4517 case COMP_LISTCOMP:
4518 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004519 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004520 break;
4521 case COMP_SETCOMP:
4522 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004523 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004524 break;
4525 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004526 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004527 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004528 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004529 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004530 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004531 break;
4532 default:
4533 return 0;
4534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004536 compiler_use_next_block(c, skip);
4537 }
4538 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004539 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004540 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004541 compiler_use_next_block(c, anchor);
4542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004543
4544 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004545}
4546
4547static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004548compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004549 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004550 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004551 expr_ty elt, expr_ty val, int type)
4552{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004554 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004555 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004556 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004558 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004559
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004560 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004561 return 0;
4562 }
4563
4564 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4565
4566 if (gen_index == 0) {
4567 /* Receive outermost iter as an implicit argument */
4568 c->u->u_argcount = 1;
4569 ADDOP_I(c, LOAD_FAST, 0);
4570 }
4571 else {
4572 /* Sub-iter - calculate on the fly */
4573 VISIT(c, expr, gen->iter);
4574 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004575 }
4576
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004577 compiler_use_next_block(c, start);
tomKPZ7a7ba3d2021-04-07 07:43:45 -07004578 /* Runtime will push a block here, so we need to account for that */
4579 if (!compiler_push_fblock(c, ASYNC_COMPREHENSION_GENERATOR, start,
4580 NULL, NULL)) {
4581 return 0;
4582 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004583
Mark Shannon582aaf12020-08-04 17:30:11 +01004584 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004585 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004586 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004587 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004588 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004589 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004590
4591 n = asdl_seq_LEN(gen->ifs);
4592 for (i = 0; i < n; i++) {
4593 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004594 if (!compiler_jump_if(c, e, if_cleanup, 0))
4595 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004596 NEXT_BLOCK(c);
4597 }
4598
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004599 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004600 if (++gen_index < asdl_seq_LEN(generators))
4601 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004602 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004603 elt, val, type))
4604 return 0;
4605
4606 /* only append after the last for generator */
4607 if (gen_index >= asdl_seq_LEN(generators)) {
4608 /* comprehension specific code */
4609 switch (type) {
4610 case COMP_GENEXP:
4611 VISIT(c, expr, elt);
4612 ADDOP(c, YIELD_VALUE);
4613 ADDOP(c, POP_TOP);
4614 break;
4615 case COMP_LISTCOMP:
4616 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004617 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004618 break;
4619 case COMP_SETCOMP:
4620 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004621 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004622 break;
4623 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004624 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004625 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004626 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004627 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004628 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004629 break;
4630 default:
4631 return 0;
4632 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004633 }
4634 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004635 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004636
tomKPZ7a7ba3d2021-04-07 07:43:45 -07004637 compiler_pop_fblock(c, ASYNC_COMPREHENSION_GENERATOR, start);
4638
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004639 compiler_use_next_block(c, except);
4640 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004641
4642 return 1;
4643}
4644
4645static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004646compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004647 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004648 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004651 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004652 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004653 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004654 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004655
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004656
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004657 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004658
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004659 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004660 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4661 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004662 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004664 }
4665
4666 is_async_generator = c->u->u_ste->ste_coroutine;
4667
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004668 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004669 compiler_error(c, "asynchronous comprehension outside of "
4670 "an asynchronous function");
4671 goto error_in_scope;
4672 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 if (type != COMP_GENEXP) {
4675 int op;
4676 switch (type) {
4677 case COMP_LISTCOMP:
4678 op = BUILD_LIST;
4679 break;
4680 case COMP_SETCOMP:
4681 op = BUILD_SET;
4682 break;
4683 case COMP_DICTCOMP:
4684 op = BUILD_MAP;
4685 break;
4686 default:
4687 PyErr_Format(PyExc_SystemError,
4688 "unknown comprehension type %d", type);
4689 goto error_in_scope;
4690 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004692 ADDOP_I(c, op, 0);
4693 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004694
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004695 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004696 val, type))
4697 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 if (type != COMP_GENEXP) {
4700 ADDOP(c, RETURN_VALUE);
4701 }
4702
4703 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004704 qualname = c->u->u_qualname;
4705 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004707 if (top_level_await && is_async_generator){
4708 c->u->u_ste->ste_coroutine = 1;
4709 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004710 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 goto error;
4712
Victor Stinnerba7a99d2021-01-30 01:46:44 +01004713 if (!compiler_make_closure(c, co, 0, qualname)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 goto error;
Victor Stinnerba7a99d2021-01-30 01:46:44 +01004715 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004716 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 Py_DECREF(co);
4718
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004719 VISIT(c, expr, outermost->iter);
4720
4721 if (outermost->is_async) {
4722 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004723 } else {
4724 ADDOP(c, GET_ITER);
4725 }
4726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004728
4729 if (is_async_generator && type != COMP_GENEXP) {
4730 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004731 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004732 ADDOP(c, YIELD_FROM);
4733 }
4734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004735 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004736error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004738error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004739 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 Py_XDECREF(co);
4741 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004742}
4743
4744static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004745compiler_genexp(struct compiler *c, expr_ty e)
4746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004747 static identifier name;
4748 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004749 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 if (!name)
4751 return 0;
4752 }
4753 assert(e->kind == GeneratorExp_kind);
4754 return compiler_comprehension(c, e, COMP_GENEXP, name,
4755 e->v.GeneratorExp.generators,
4756 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004757}
4758
4759static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004760compiler_listcomp(struct compiler *c, expr_ty e)
4761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 static identifier name;
4763 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004764 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004765 if (!name)
4766 return 0;
4767 }
4768 assert(e->kind == ListComp_kind);
4769 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4770 e->v.ListComp.generators,
4771 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004772}
4773
4774static int
4775compiler_setcomp(struct compiler *c, expr_ty e)
4776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004777 static identifier name;
4778 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004779 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 if (!name)
4781 return 0;
4782 }
4783 assert(e->kind == SetComp_kind);
4784 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4785 e->v.SetComp.generators,
4786 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004787}
4788
4789
4790static int
4791compiler_dictcomp(struct compiler *c, expr_ty e)
4792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004793 static identifier name;
4794 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004795 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004796 if (!name)
4797 return 0;
4798 }
4799 assert(e->kind == DictComp_kind);
4800 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4801 e->v.DictComp.generators,
4802 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004803}
4804
4805
4806static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004807compiler_visit_keyword(struct compiler *c, keyword_ty k)
4808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004809 VISIT(c, expr, k->value);
4810 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004811}
4812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004813/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004814 whether they are true or false.
4815
4816 Return values: 1 for true, 0 for false, -1 for non-constant.
4817 */
4818
4819static int
Mark Shannonfee55262019-11-21 09:11:43 +00004820compiler_with_except_finish(struct compiler *c) {
4821 basicblock *exit;
4822 exit = compiler_new_block(c);
4823 if (exit == NULL)
4824 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004825 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004826 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004827 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004828 compiler_use_next_block(c, exit);
4829 ADDOP(c, POP_TOP);
4830 ADDOP(c, POP_TOP);
4831 ADDOP(c, POP_TOP);
4832 ADDOP(c, POP_EXCEPT);
4833 ADDOP(c, POP_TOP);
4834 return 1;
4835}
Yury Selivanov75445082015-05-11 22:57:16 -04004836
4837/*
4838 Implements the async with statement.
4839
4840 The semantics outlined in that PEP are as follows:
4841
4842 async with EXPR as VAR:
4843 BLOCK
4844
4845 It is implemented roughly as:
4846
4847 context = EXPR
4848 exit = context.__aexit__ # not calling it
4849 value = await context.__aenter__()
4850 try:
4851 VAR = value # if VAR present in the syntax
4852 BLOCK
4853 finally:
4854 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004855 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004856 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004857 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004858 if not (await exit(*exc)):
4859 raise
4860 */
4861static int
4862compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4863{
Mark Shannonfee55262019-11-21 09:11:43 +00004864 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004865 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4866
4867 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004868 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004869 c->u->u_ste->ste_coroutine = 1;
4870 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004871 return compiler_error(c, "'async with' outside async function");
4872 }
Yury Selivanov75445082015-05-11 22:57:16 -04004873
4874 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004875 final = compiler_new_block(c);
4876 exit = compiler_new_block(c);
4877 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004878 return 0;
4879
4880 /* Evaluate EXPR */
4881 VISIT(c, expr, item->context_expr);
4882
4883 ADDOP(c, BEFORE_ASYNC_WITH);
4884 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004885 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004886 ADDOP(c, YIELD_FROM);
4887
Mark Shannon582aaf12020-08-04 17:30:11 +01004888 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004889
4890 /* SETUP_ASYNC_WITH pushes a finally block. */
4891 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004892 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004893 return 0;
4894 }
4895
4896 if (item->optional_vars) {
4897 VISIT(c, expr, item->optional_vars);
4898 }
4899 else {
4900 /* Discard result from context.__aenter__() */
4901 ADDOP(c, POP_TOP);
4902 }
4903
4904 pos++;
4905 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4906 /* BLOCK code */
4907 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4908 else if (!compiler_async_with(c, s, pos))
4909 return 0;
4910
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004911 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004912 ADDOP(c, POP_BLOCK);
4913 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004914
Mark Shannonfee55262019-11-21 09:11:43 +00004915 /* For successful outcome:
4916 * call __exit__(None, None, None)
4917 */
4918 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004919 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004920 ADDOP(c, GET_AWAITABLE);
4921 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4922 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004923
Mark Shannonfee55262019-11-21 09:11:43 +00004924 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004925
Mark Shannon582aaf12020-08-04 17:30:11 +01004926 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004927
4928 /* For exceptional outcome: */
4929 compiler_use_next_block(c, final);
4930
4931 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004932 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004933 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004934 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004935 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004936
Mark Shannonfee55262019-11-21 09:11:43 +00004937compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004938 return 1;
4939}
4940
4941
Guido van Rossumc2e20742006-02-27 22:32:47 +00004942/*
4943 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004944 with EXPR as VAR:
4945 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004946 is implemented as:
4947 <code for EXPR>
4948 SETUP_WITH E
4949 <code to store to VAR> or POP_TOP
4950 <code for BLOCK>
4951 LOAD_CONST (None, None, None)
4952 CALL_FUNCTION_EX 0
4953 JUMP_FORWARD EXIT
4954 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4955 POP_JUMP_IF_TRUE T:
4956 RERAISE
4957 T: POP_TOP * 3 (remove exception from stack)
4958 POP_EXCEPT
4959 POP_TOP
4960 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004961 */
Mark Shannonfee55262019-11-21 09:11:43 +00004962
Guido van Rossumc2e20742006-02-27 22:32:47 +00004963static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004964compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004965{
Mark Shannonfee55262019-11-21 09:11:43 +00004966 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004967 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004968
4969 assert(s->kind == With_kind);
4970
Guido van Rossumc2e20742006-02-27 22:32:47 +00004971 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004972 final = compiler_new_block(c);
4973 exit = compiler_new_block(c);
4974 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004975 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004976
Thomas Wouters477c8d52006-05-27 19:21:47 +00004977 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004978 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004979 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004980 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004981
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004982 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004983 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004984 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004985 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004986 }
4987
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004988 if (item->optional_vars) {
4989 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004990 }
4991 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004993 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004994 }
4995
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004996 pos++;
4997 if (pos == asdl_seq_LEN(s->v.With.items))
4998 /* BLOCK code */
4999 VISIT_SEQ(c, stmt, s->v.With.body)
5000 else if (!compiler_with(c, s, pos))
5001 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00005002
Mark Shannon3bd60352021-01-13 12:05:43 +00005003
5004 /* Mark all following code as artificial */
5005 c->u->u_lineno = -1;
Guido van Rossumc2e20742006-02-27 22:32:47 +00005006 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005007 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00005008
Mark Shannonfee55262019-11-21 09:11:43 +00005009 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00005010
Mark Shannonfee55262019-11-21 09:11:43 +00005011 /* For successful outcome:
5012 * call __exit__(None, None, None)
5013 */
5014 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00005015 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00005016 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01005017 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005018
Mark Shannonfee55262019-11-21 09:11:43 +00005019 /* For exceptional outcome: */
5020 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005021
Mark Shannonfee55262019-11-21 09:11:43 +00005022 ADDOP(c, WITH_EXCEPT_START);
5023 compiler_with_except_finish(c);
5024
5025 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005026 return 1;
5027}
5028
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005029static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005030compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07005033 case NamedExpr_kind:
5034 VISIT(c, expr, e->v.NamedExpr.value);
5035 ADDOP(c, DUP_TOP);
5036 VISIT(c, expr, e->v.NamedExpr.target);
5037 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 case BoolOp_kind:
5039 return compiler_boolop(c, e);
5040 case BinOp_kind:
5041 VISIT(c, expr, e->v.BinOp.left);
5042 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05005043 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 break;
5045 case UnaryOp_kind:
5046 VISIT(c, expr, e->v.UnaryOp.operand);
5047 ADDOP(c, unaryop(e->v.UnaryOp.op));
5048 break;
5049 case Lambda_kind:
5050 return compiler_lambda(c, e);
5051 case IfExp_kind:
5052 return compiler_ifexp(c, e);
5053 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005054 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005055 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005056 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 case GeneratorExp_kind:
5058 return compiler_genexp(c, e);
5059 case ListComp_kind:
5060 return compiler_listcomp(c, e);
5061 case SetComp_kind:
5062 return compiler_setcomp(c, e);
5063 case DictComp_kind:
5064 return compiler_dictcomp(c, e);
5065 case Yield_kind:
5066 if (c->u->u_ste->ste_type != FunctionBlock)
5067 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005068 if (e->v.Yield.value) {
5069 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 }
5071 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005072 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005074 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005075 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005076 case YieldFrom_kind:
5077 if (c->u->u_ste->ste_type != FunctionBlock)
5078 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005079
5080 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5081 return compiler_error(c, "'yield from' inside async function");
5082
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005083 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005084 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005085 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005086 ADDOP(c, YIELD_FROM);
5087 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005088 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005089 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005090 if (c->u->u_ste->ste_type != FunctionBlock){
5091 return compiler_error(c, "'await' outside function");
5092 }
Yury Selivanov75445082015-05-11 22:57:16 -04005093
Victor Stinner331a6a52019-05-27 16:39:22 +02005094 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005095 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5096 return compiler_error(c, "'await' outside async function");
5097 }
5098 }
Yury Selivanov75445082015-05-11 22:57:16 -04005099
5100 VISIT(c, expr, e->v.Await.value);
5101 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005102 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005103 ADDOP(c, YIELD_FROM);
5104 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005105 case Compare_kind:
5106 return compiler_compare(c, e);
5107 case Call_kind:
5108 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005109 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005110 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005111 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005112 case JoinedStr_kind:
5113 return compiler_joined_str(c, e);
5114 case FormattedValue_kind:
5115 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 /* The following exprs can be assignment targets. */
5117 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005118 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 case Load:
Mark Shannond48848c2021-03-14 18:01:30 +00005121 {
5122 int old_lineno = c->u->u_lineno;
5123 c->u->u_lineno = e->end_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005124 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005125 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 break;
Mark Shannond48848c2021-03-14 18:01:30 +00005127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 case Store:
Mark Shannond48848c2021-03-14 18:01:30 +00005129 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005130 return 0;
Mark Shannond48848c2021-03-14 18:01:30 +00005131 }
5132 int old_lineno = c->u->u_lineno;
5133 c->u->u_lineno = e->end_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005135 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 break;
5137 case Del:
5138 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5139 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 }
5141 break;
5142 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005143 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 case Starred_kind:
5145 switch (e->v.Starred.ctx) {
5146 case Store:
5147 /* In all legitimate cases, the Starred node was already replaced
5148 * by compiler_list/compiler_tuple. XXX: is that okay? */
5149 return compiler_error(c,
5150 "starred assignment target must be in a list or tuple");
5151 default:
5152 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005153 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005154 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005155 break;
5156 case Slice_kind:
5157 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 case Name_kind:
5159 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5160 /* child nodes of List and Tuple will have expr_context set */
5161 case List_kind:
5162 return compiler_list(c, e);
5163 case Tuple_kind:
5164 return compiler_tuple(c, e);
Brandt Bucher145bf262021-02-26 14:51:55 -08005165 case MatchAs_kind:
5166 case MatchOr_kind:
5167 // Can only occur in patterns, which are handled elsewhere.
5168 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 }
5170 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005171}
5172
5173static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005174compiler_visit_expr(struct compiler *c, expr_ty e)
5175{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005176 int old_lineno = c->u->u_lineno;
5177 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005178 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005179 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005180 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005181 c->u->u_col_offset = old_col_offset;
5182 return res;
5183}
5184
5185static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005186compiler_augassign(struct compiler *c, stmt_ty s)
5187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005188 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005189 expr_ty e = s->v.AugAssign.target;
5190
5191 int old_lineno = c->u->u_lineno;
5192 int old_col_offset = c->u->u_col_offset;
5193 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005195 switch (e->kind) {
5196 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005197 VISIT(c, expr, e->v.Attribute.value);
5198 ADDOP(c, DUP_TOP);
Mark Shannond48848c2021-03-14 18:01:30 +00005199 int old_lineno = c->u->u_lineno;
5200 c->u->u_lineno = e->end_lineno;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005201 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005202 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005203 break;
5204 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005205 VISIT(c, expr, e->v.Subscript.value);
5206 VISIT(c, expr, e->v.Subscript.slice);
5207 ADDOP(c, DUP_TOP_TWO);
5208 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005209 break;
5210 case Name_kind:
5211 if (!compiler_nameop(c, e->v.Name.id, Load))
5212 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005213 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005214 default:
5215 PyErr_Format(PyExc_SystemError,
5216 "invalid node type (%d) for augmented assignment",
5217 e->kind);
5218 return 0;
5219 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005220
5221 c->u->u_lineno = old_lineno;
5222 c->u->u_col_offset = old_col_offset;
5223
5224 VISIT(c, expr, s->v.AugAssign.value);
5225 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5226
5227 SET_LOC(c, e);
5228
5229 switch (e->kind) {
5230 case Attribute_kind:
Mark Shannond48848c2021-03-14 18:01:30 +00005231 c->u->u_lineno = e->end_lineno;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005232 ADDOP(c, ROT_TWO);
5233 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5234 break;
5235 case Subscript_kind:
5236 ADDOP(c, ROT_THREE);
5237 ADDOP(c, STORE_SUBSCR);
5238 break;
5239 case Name_kind:
5240 return compiler_nameop(c, e->v.Name.id, Store);
5241 default:
5242 Py_UNREACHABLE();
5243 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005244 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005245}
5246
5247static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005248check_ann_expr(struct compiler *c, expr_ty e)
5249{
5250 VISIT(c, expr, e);
5251 ADDOP(c, POP_TOP);
5252 return 1;
5253}
5254
5255static int
5256check_annotation(struct compiler *c, stmt_ty s)
5257{
5258 /* Annotations are only evaluated in a module or class. */
5259 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5260 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5261 return check_ann_expr(c, s->v.AnnAssign.annotation);
5262 }
5263 return 1;
5264}
5265
5266static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005267check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005268{
5269 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005270 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005271 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005272 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005273 return 0;
5274 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005275 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5276 return 0;
5277 }
5278 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5279 return 0;
5280 }
5281 return 1;
5282 case Tuple_kind: {
5283 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005284 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005285 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005286 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005287 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005288 return 0;
5289 }
5290 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005291 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005292 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005293 default:
5294 return check_ann_expr(c, e);
5295 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005296}
5297
5298static int
5299compiler_annassign(struct compiler *c, stmt_ty s)
5300{
5301 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005302 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005303
5304 assert(s->kind == AnnAssign_kind);
5305
5306 /* We perform the actual assignment first. */
5307 if (s->v.AnnAssign.value) {
5308 VISIT(c, expr, s->v.AnnAssign.value);
5309 VISIT(c, expr, targ);
5310 }
5311 switch (targ->kind) {
5312 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005313 if (forbidden_name(c, targ->v.Name.id, Store))
5314 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005315 /* If we have a simple name in a module or class, store annotation. */
5316 if (s->v.AnnAssign.simple &&
5317 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5318 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005319 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005320 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005321 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005322 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005323 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005324 }
5325 break;
5326 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005327 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5328 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005329 if (!s->v.AnnAssign.value &&
5330 !check_ann_expr(c, targ->v.Attribute.value)) {
5331 return 0;
5332 }
5333 break;
5334 case Subscript_kind:
5335 if (!s->v.AnnAssign.value &&
5336 (!check_ann_expr(c, targ->v.Subscript.value) ||
5337 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5338 return 0;
5339 }
5340 break;
5341 default:
5342 PyErr_Format(PyExc_SystemError,
5343 "invalid node type (%d) for annotated assignment",
5344 targ->kind);
5345 return 0;
5346 }
5347 /* Annotation is evaluated last. */
5348 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5349 return 0;
5350 }
5351 return 1;
5352}
5353
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005354/* Raises a SyntaxError and returns 0.
5355 If something goes wrong, a different exception may be raised.
5356*/
5357
5358static int
Brandt Bucher145bf262021-02-26 14:51:55 -08005359compiler_error(struct compiler *c, const char *format, ...)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005360{
Brandt Bucher145bf262021-02-26 14:51:55 -08005361 va_list vargs;
5362#ifdef HAVE_STDARG_PROTOTYPES
5363 va_start(vargs, format);
5364#else
5365 va_start(vargs);
5366#endif
5367 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5368 va_end(vargs);
5369 if (msg == NULL) {
5370 return 0;
5371 }
5372 PyObject *loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
5373 if (loc == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 Py_INCREF(Py_None);
5375 loc = Py_None;
5376 }
Brandt Bucher145bf262021-02-26 14:51:55 -08005377 PyObject *args = Py_BuildValue("O(OiiO)", msg, c->c_filename,
5378 c->u->u_lineno, c->u->u_col_offset + 1, loc);
5379 Py_DECREF(msg);
5380 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 goto exit;
Brandt Bucher145bf262021-02-26 14:51:55 -08005382 }
5383 PyErr_SetObject(PyExc_SyntaxError, args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005384 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 Py_DECREF(loc);
Brandt Bucher145bf262021-02-26 14:51:55 -08005386 Py_XDECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005388}
5389
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005390/* Emits a SyntaxWarning and returns 1 on success.
5391 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5392 and returns 0.
5393*/
5394static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005395compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005396{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005397 va_list vargs;
5398#ifdef HAVE_STDARG_PROTOTYPES
5399 va_start(vargs, format);
5400#else
5401 va_start(vargs);
5402#endif
5403 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5404 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005405 if (msg == NULL) {
5406 return 0;
5407 }
5408 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5409 c->u->u_lineno, NULL, NULL) < 0)
5410 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005411 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005412 /* Replace the SyntaxWarning exception with a SyntaxError
5413 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005414 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005415 assert(PyUnicode_AsUTF8(msg) != NULL);
5416 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005417 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005418 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005419 return 0;
5420 }
5421 Py_DECREF(msg);
5422 return 1;
5423}
5424
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005425static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005426compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005427{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005428 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005429 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005430
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005431 if (ctx == Load) {
5432 if (!check_subscripter(c, e->v.Subscript.value)) {
5433 return 0;
5434 }
5435 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5436 return 0;
5437 }
5438 }
5439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 case Store: op = STORE_SUBSCR; break;
5443 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005445 assert(op);
5446 VISIT(c, expr, e->v.Subscript.value);
5447 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005448 ADDOP(c, op);
5449 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005450}
5451
5452static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005453compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 int n = 2;
5456 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005458 /* only handles the cases where BUILD_SLICE is emitted */
5459 if (s->v.Slice.lower) {
5460 VISIT(c, expr, s->v.Slice.lower);
5461 }
5462 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005463 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005466 if (s->v.Slice.upper) {
5467 VISIT(c, expr, s->v.Slice.upper);
5468 }
5469 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005470 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 }
5472
5473 if (s->v.Slice.step) {
5474 n++;
5475 VISIT(c, expr, s->v.Slice.step);
5476 }
5477 ADDOP_I(c, BUILD_SLICE, n);
5478 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005479}
5480
Brandt Bucher145bf262021-02-26 14:51:55 -08005481
5482// PEP 634: Structural Pattern Matching
5483
5484// To keep things simple, all compiler_pattern_* routines follow the convention
5485// of replacing TOS (the subject for the given pattern) with either True (match)
5486// or False (no match). We do this even for irrefutable patterns; the idea is
5487// that it's much easier to smooth out any redundant pushing, popping, and
5488// jumping in the peephole optimizer than to detect or predict it here.
5489
5490
5491#define WILDCARD_CHECK(N) \
5492 ((N)->kind == Name_kind && \
5493 _PyUnicode_EqualToASCIIString((N)->v.Name.id, "_"))
5494
5495
5496static int
5497pattern_helper_store_name(struct compiler *c, identifier n, pattern_context *pc)
5498{
5499 assert(!_PyUnicode_EqualToASCIIString(n, "_"));
5500 // Can't assign to the same name twice:
5501 if (pc->stores == NULL) {
5502 RETURN_IF_FALSE(pc->stores = PySet_New(NULL));
5503 }
5504 else {
5505 int duplicate = PySet_Contains(pc->stores, n);
5506 if (duplicate < 0) {
5507 return 0;
5508 }
5509 if (duplicate) {
5510 const char *e = "multiple assignments to name %R in pattern";
5511 return compiler_error(c, e, n);
5512 }
5513 }
5514 RETURN_IF_FALSE(!PySet_Add(pc->stores, n));
5515 RETURN_IF_FALSE(compiler_nameop(c, n, Store));
5516 return 1;
5517}
5518
5519
5520static int
5521pattern_helper_sequence_unpack(struct compiler *c, asdl_expr_seq *values,
5522 Py_ssize_t star, pattern_context *pc)
5523{
5524 RETURN_IF_FALSE(unpack_helper(c, values));
5525 // We've now got a bunch of new subjects on the stack. If any of them fail
5526 // to match, we need to pop everything else off, then finally push False.
5527 // fails is an array of blocks that correspond to the necessary amount of
5528 // popping for each element:
5529 basicblock **fails;
5530 Py_ssize_t size = asdl_seq_LEN(values);
5531 fails = (basicblock **)PyObject_Malloc(sizeof(basicblock*) * size);
5532 if (fails == NULL) {
5533 PyErr_NoMemory();
5534 return 0;
5535 }
5536 // NOTE: Can't use our nice returning macros anymore: they'll leak memory!
5537 // goto error on error.
5538 for (Py_ssize_t i = 0; i < size; i++) {
5539 fails[i] = compiler_new_block(c);
5540 if (fails[i] == NULL) {
5541 goto error;
5542 }
5543 }
5544 for (Py_ssize_t i = 0; i < size; i++) {
5545 expr_ty value = asdl_seq_GET(values, i);
5546 if (i == star) {
5547 assert(value->kind == Starred_kind);
5548 value = value->v.Starred.value;
5549 }
5550 if (!compiler_pattern_subpattern(c, value, pc) ||
5551 !compiler_addop_j(c, POP_JUMP_IF_FALSE, fails[i]) ||
5552 compiler_next_block(c) == NULL)
5553 {
5554 goto error;
5555 }
5556 }
5557 // Success!
5558 basicblock *end = compiler_new_block(c);
5559 if (end == NULL ||
5560 !compiler_addop_load_const(c, Py_True) ||
5561 !compiler_addop_j(c, JUMP_FORWARD, end))
5562 {
5563 goto error;
5564 }
5565 // This is where we handle failed sub-patterns. For a sequence pattern like
5566 // [a, b, c, d], this will look like:
5567 // fails[0]: POP_TOP
5568 // fails[1]: POP_TOP
5569 // fails[2]: POP_TOP
5570 // fails[3]: LOAD_CONST False
5571 for (Py_ssize_t i = 0; i < size - 1; i++) {
5572 compiler_use_next_block(c, fails[i]);
5573 if (!compiler_addop(c, POP_TOP)) {
5574 goto error;
5575 }
5576 }
5577 compiler_use_next_block(c, fails[size - 1]);
5578 if (!compiler_addop_load_const(c, Py_False)) {
5579 goto error;
5580 }
5581 compiler_use_next_block(c, end);
5582 PyObject_Free(fails);
5583 return 1;
5584error:
5585 PyObject_Free(fails);
5586 return 0;
5587}
5588
5589// Like pattern_helper_sequence_unpack, but uses BINARY_SUBSCR instead of
5590// UNPACK_SEQUENCE / UNPACK_EX. This is more efficient for patterns with a
5591// starred wildcard like [first, *_] / [first, *_, last] / [*_, last] / etc.
5592static int
5593pattern_helper_sequence_subscr(struct compiler *c, asdl_expr_seq *values,
5594 Py_ssize_t star, pattern_context *pc)
5595{
5596 basicblock *end, *fail_pop_1;
5597 RETURN_IF_FALSE(end = compiler_new_block(c));
5598 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5599 Py_ssize_t size = asdl_seq_LEN(values);
5600 for (Py_ssize_t i = 0; i < size; i++) {
5601 expr_ty value = asdl_seq_GET(values, i);
5602 if (WILDCARD_CHECK(value)) {
5603 continue;
5604 }
5605 if (i == star) {
5606 assert(value->kind == Starred_kind);
5607 assert(WILDCARD_CHECK(value->v.Starred.value));
5608 continue;
5609 }
5610 ADDOP(c, DUP_TOP);
5611 if (i < star) {
5612 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
5613 }
5614 else {
5615 // The subject may not support negative indexing! Compute a
5616 // nonnegative index:
5617 ADDOP(c, GET_LEN);
5618 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size - i));
5619 ADDOP(c, BINARY_SUBTRACT);
5620 }
5621 ADDOP(c, BINARY_SUBSCR);
5622 RETURN_IF_FALSE(compiler_pattern_subpattern(c, value, pc));
5623 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5624 NEXT_BLOCK(c);
5625 }
5626 ADDOP(c, POP_TOP);
5627 ADDOP_LOAD_CONST(c, Py_True);
5628 ADDOP_JUMP(c, JUMP_FORWARD, end);
5629 compiler_use_next_block(c, fail_pop_1);
5630 ADDOP(c, POP_TOP);
5631 ADDOP_LOAD_CONST(c, Py_False);
5632 compiler_use_next_block(c, end);
5633 return 1;
5634}
5635
5636
5637// Like compiler_pattern, but turn off checks for irrefutability.
5638static int
5639compiler_pattern_subpattern(struct compiler *c, expr_ty p, pattern_context *pc)
5640{
5641 int allow_irrefutable = pc->allow_irrefutable;
5642 pc->allow_irrefutable = 1;
5643 RETURN_IF_FALSE(compiler_pattern(c, p, pc));
5644 pc->allow_irrefutable = allow_irrefutable;
5645 return 1;
5646}
5647
5648
5649static int
5650compiler_pattern_as(struct compiler *c, expr_ty p, pattern_context *pc)
5651{
5652 assert(p->kind == MatchAs_kind);
5653 basicblock *end, *fail_pop_1;
5654 RETURN_IF_FALSE(end = compiler_new_block(c));
5655 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5656 // Need to make a copy for (possibly) storing later:
5657 ADDOP(c, DUP_TOP);
5658 RETURN_IF_FALSE(compiler_pattern(c, p->v.MatchAs.pattern, pc));
5659 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5660 NEXT_BLOCK(c);
5661 RETURN_IF_FALSE(pattern_helper_store_name(c, p->v.MatchAs.name, pc));
5662 ADDOP_LOAD_CONST(c, Py_True);
5663 ADDOP_JUMP(c, JUMP_FORWARD, end);
5664 compiler_use_next_block(c, fail_pop_1);
5665 // Need to pop that unused copy from before:
5666 ADDOP(c, POP_TOP);
5667 ADDOP_LOAD_CONST(c, Py_False);
5668 compiler_use_next_block(c, end);
5669 return 1;
5670}
5671
5672
5673static int
5674compiler_pattern_capture(struct compiler *c, expr_ty p, pattern_context *pc)
5675{
5676 assert(p->kind == Name_kind);
5677 assert(p->v.Name.ctx == Store);
5678 assert(!WILDCARD_CHECK(p));
5679 if (!pc->allow_irrefutable) {
5680 // Whoops, can't have a name capture here!
5681 const char *e = "name capture %R makes remaining patterns unreachable";
5682 return compiler_error(c, e, p->v.Name.id);
5683 }
5684 RETURN_IF_FALSE(pattern_helper_store_name(c, p->v.Name.id, pc));
5685 ADDOP_LOAD_CONST(c, Py_True);
5686 return 1;
5687}
5688
5689
5690static int
5691compiler_pattern_class(struct compiler *c, expr_ty p, pattern_context *pc)
5692{
5693 asdl_expr_seq *args = p->v.Call.args;
5694 asdl_keyword_seq *kwargs = p->v.Call.keywords;
5695 Py_ssize_t nargs = asdl_seq_LEN(args);
5696 Py_ssize_t nkwargs = asdl_seq_LEN(kwargs);
5697 if (INT_MAX < nargs || INT_MAX < nargs + nkwargs - 1) {
5698 const char *e = "too many sub-patterns in class pattern %R";
5699 return compiler_error(c, e, p->v.Call.func);
5700 }
5701 RETURN_IF_FALSE(!validate_keywords(c, kwargs));
5702 basicblock *end, *fail_pop_1;
5703 RETURN_IF_FALSE(end = compiler_new_block(c));
5704 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5705 VISIT(c, expr, p->v.Call.func);
5706 PyObject *kwnames;
5707 RETURN_IF_FALSE(kwnames = PyTuple_New(nkwargs));
5708 Py_ssize_t i;
5709 for (i = 0; i < nkwargs; i++) {
5710 PyObject *name = ((keyword_ty) asdl_seq_GET(kwargs, i))->arg;
5711 Py_INCREF(name);
5712 PyTuple_SET_ITEM(kwnames, i, name);
5713 }
5714 ADDOP_LOAD_CONST_NEW(c, kwnames);
5715 ADDOP_I(c, MATCH_CLASS, nargs);
5716 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5717 NEXT_BLOCK(c);
5718 // TOS is now a tuple of (nargs + nkwargs) attributes.
5719 for (i = 0; i < nargs + nkwargs; i++) {
5720 expr_ty arg;
5721 if (i < nargs) {
5722 // Positional:
5723 arg = asdl_seq_GET(args, i);
5724 }
5725 else {
5726 // Keyword:
5727 arg = ((keyword_ty) asdl_seq_GET(kwargs, i - nargs))->value;
5728 }
5729 if (WILDCARD_CHECK(arg)) {
5730 continue;
5731 }
5732 // Get the i-th attribute, and match it against the i-th pattern:
5733 ADDOP(c, DUP_TOP);
5734 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
5735 ADDOP(c, BINARY_SUBSCR);
5736 RETURN_IF_FALSE(compiler_pattern_subpattern(c, arg, pc));
5737 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5738 NEXT_BLOCK(c);
5739 }
5740 // Success! Pop the tuple of attributes:
5741 ADDOP(c, POP_TOP);
5742 ADDOP_LOAD_CONST(c, Py_True);
5743 ADDOP_JUMP(c, JUMP_FORWARD, end);
5744 compiler_use_next_block(c, fail_pop_1);
5745 ADDOP(c, POP_TOP);
5746 ADDOP_LOAD_CONST(c, Py_False);
5747 compiler_use_next_block(c, end);
5748 return 1;
5749}
5750
5751
5752static int
5753compiler_pattern_literal(struct compiler *c, expr_ty p, pattern_context *pc)
5754{
5755 assert(p->kind == Constant_kind);
5756 PyObject *v = p->v.Constant.value;
5757 ADDOP_LOAD_CONST(c, v);
5758 // Literal True, False, and None are compared by identity. All others use
5759 // equality:
5760 ADDOP_COMPARE(c, (v == Py_None || PyBool_Check(v)) ? Is : Eq);
5761 return 1;
5762}
5763
5764
5765static int
5766compiler_pattern_mapping(struct compiler *c, expr_ty p, pattern_context *pc)
5767{
5768 basicblock *end, *fail_pop_1, *fail_pop_3;
5769 RETURN_IF_FALSE(end = compiler_new_block(c));
5770 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5771 RETURN_IF_FALSE(fail_pop_3 = compiler_new_block(c));
5772 asdl_expr_seq *keys = p->v.Dict.keys;
5773 asdl_expr_seq *values = p->v.Dict.values;
5774 Py_ssize_t size = asdl_seq_LEN(values);
Ikko Ashimine57827f82021-03-10 19:39:51 +09005775 // A starred pattern will be a keyless value. It is guaranteed to be last:
Brandt Bucher145bf262021-02-26 14:51:55 -08005776 int star = size ? !asdl_seq_GET(keys, size - 1) : 0;
5777 ADDOP(c, MATCH_MAPPING);
5778 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5779 NEXT_BLOCK(c);
5780 if (!size) {
5781 // If the pattern is just "{}", we're done!
5782 ADDOP(c, POP_TOP);
5783 ADDOP_LOAD_CONST(c, Py_True);
5784 ADDOP_JUMP(c, JUMP_FORWARD, end);
5785 compiler_use_next_block(c, fail_pop_1);
5786 ADDOP(c, POP_TOP);
5787 ADDOP_LOAD_CONST(c, Py_False);
5788 compiler_use_next_block(c, end);
5789 return 1;
5790 }
5791 if (size - star) {
5792 // If the pattern has any keys in it, perform a length check:
5793 ADDOP(c, GET_LEN);
5794 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size - star));
5795 ADDOP_COMPARE(c, GtE);
5796 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5797 NEXT_BLOCK(c);
5798 }
5799 if (INT_MAX < size - star - 1) {
5800 return compiler_error(c, "too many sub-patterns in mapping pattern");
5801 }
5802 // Collect all of the keys into a tuple for MATCH_KEYS and
5803 // COPY_DICT_WITHOUT_KEYS. They can either be dotted names or literals:
5804 for (Py_ssize_t i = 0; i < size - star; i++) {
5805 expr_ty key = asdl_seq_GET(keys, i);
5806 if (key == NULL) {
5807 const char *e = "can't use starred name here "
5808 "(consider moving to end)";
5809 return compiler_error(c, e);
5810 }
5811 VISIT(c, expr, key);
5812 }
5813 ADDOP_I(c, BUILD_TUPLE, size - star);
5814 ADDOP(c, MATCH_KEYS);
5815 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_3);
5816 NEXT_BLOCK(c);
5817 // So far so good. There's now a tuple of values on the stack to match
5818 // sub-patterns against:
5819 for (Py_ssize_t i = 0; i < size - star; i++) {
5820 expr_ty value = asdl_seq_GET(values, i);
5821 if (WILDCARD_CHECK(value)) {
5822 continue;
5823 }
5824 ADDOP(c, DUP_TOP);
5825 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
5826 ADDOP(c, BINARY_SUBSCR);
5827 RETURN_IF_FALSE(compiler_pattern_subpattern(c, value, pc));
5828 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_3);
5829 NEXT_BLOCK(c);
5830 }
5831 // If we get this far, it's a match! We're done with that tuple of values.
5832 ADDOP(c, POP_TOP);
5833 if (star) {
5834 // If we had a starred name, bind a dict of remaining items to it:
5835 ADDOP(c, COPY_DICT_WITHOUT_KEYS);
5836 PyObject *id = asdl_seq_GET(values, size - 1)->v.Name.id;
5837 RETURN_IF_FALSE(pattern_helper_store_name(c, id, pc));
5838 }
5839 else {
5840 // Otherwise, we don't care about this tuple of keys anymore:
5841 ADDOP(c, POP_TOP);
5842 }
5843 // Pop the subject:
5844 ADDOP(c, POP_TOP);
5845 ADDOP_LOAD_CONST(c, Py_True);
5846 ADDOP_JUMP(c, JUMP_FORWARD, end);
5847 // The top two items are a tuple of values or None, followed by a tuple of
5848 // keys. Pop them both:
5849 compiler_use_next_block(c, fail_pop_3);
5850 ADDOP(c, POP_TOP);
5851 ADDOP(c, POP_TOP);
5852 compiler_use_next_block(c, fail_pop_1);
5853 // Pop the subject:
5854 ADDOP(c, POP_TOP);
5855 ADDOP_LOAD_CONST(c, Py_False);
5856 compiler_use_next_block(c, end);
5857 return 1;
5858}
5859
5860
5861static int
5862compiler_pattern_or(struct compiler *c, expr_ty p, pattern_context *pc)
5863{
5864 assert(p->kind == MatchOr_kind);
5865 // control is the set of names bound by the first alternative. If all of the
5866 // others bind the same names (they should), then this becomes pc->stores.
5867 PyObject *control = NULL;
5868 basicblock *end, *pass_pop_1;
5869 RETURN_IF_FALSE(end = compiler_new_block(c));
5870 RETURN_IF_FALSE(pass_pop_1 = compiler_new_block(c));
5871 Py_ssize_t size = asdl_seq_LEN(p->v.MatchOr.patterns);
5872 assert(size > 1);
5873 // We're going to be messing with pc. Keep the original info handy:
5874 PyObject *stores_init = pc->stores;
5875 int allow_irrefutable = pc->allow_irrefutable;
5876 for (Py_ssize_t i = 0; i < size; i++) {
5877 // NOTE: Can't use our nice returning macros in here: they'll leak sets!
5878 expr_ty alt = asdl_seq_GET(p->v.MatchOr.patterns, i);
5879 pc->stores = PySet_New(stores_init);
5880 // An irrefutable sub-pattern must be last, if it is allowed at all:
5881 int is_last = i == size - 1;
5882 pc->allow_irrefutable = allow_irrefutable && is_last;
5883 SET_LOC(c, alt);
5884 if (pc->stores == NULL ||
5885 // Only copy the subject if we're *not* on the last alternative:
5886 (!is_last && !compiler_addop(c, DUP_TOP)) ||
5887 !compiler_pattern(c, alt, pc) ||
5888 // Only jump if we're *not* on the last alternative:
5889 (!is_last && !compiler_addop_j(c, POP_JUMP_IF_TRUE, pass_pop_1)) ||
5890 !compiler_next_block(c))
5891 {
5892 goto fail;
5893 }
5894 if (!i) {
5895 // If this is the first alternative, save its stores as a "control"
5896 // for the others (they can't bind a different set of names):
5897 control = pc->stores;
5898 continue;
5899 }
5900 if (PySet_GET_SIZE(pc->stores) || PySet_GET_SIZE(control)) {
5901 // Otherwise, check to see if we differ from the control set:
5902 PyObject *diff = PyNumber_InPlaceXor(pc->stores, control);
5903 if (diff == NULL) {
5904 goto fail;
5905 }
5906 if (PySet_GET_SIZE(diff)) {
5907 // The names differ! Raise.
5908 Py_DECREF(diff);
5909 compiler_error(c, "alternative patterns bind different names");
5910 goto fail;
5911 }
5912 Py_DECREF(diff);
5913 }
5914 Py_DECREF(pc->stores);
5915 }
5916 Py_XDECREF(stores_init);
5917 // Update pc->stores and restore pc->allow_irrefutable:
5918 pc->stores = control;
5919 pc->allow_irrefutable = allow_irrefutable;
5920 ADDOP_JUMP(c, JUMP_FORWARD, end);
5921 compiler_use_next_block(c, pass_pop_1);
5922 ADDOP(c, POP_TOP);
5923 ADDOP_LOAD_CONST(c, Py_True);
5924 compiler_use_next_block(c, end);
5925 return 1;
5926fail:
5927 Py_XDECREF(stores_init);
5928 Py_XDECREF(control);
5929 return 0;
5930}
5931
5932
5933static int
5934compiler_pattern_sequence(struct compiler *c, expr_ty p, pattern_context *pc)
5935{
5936 assert(p->kind == List_kind || p->kind == Tuple_kind);
5937 asdl_expr_seq *values = (p->kind == Tuple_kind) ? p->v.Tuple.elts
5938 : p->v.List.elts;
5939 Py_ssize_t size = asdl_seq_LEN(values);
5940 Py_ssize_t star = -1;
5941 int only_wildcard = 1;
5942 int star_wildcard = 0;
5943 // Find a starred name, if it exists. There may be at most one:
5944 for (Py_ssize_t i = 0; i < size; i++) {
5945 expr_ty value = asdl_seq_GET(values, i);
5946 if (value->kind == Starred_kind) {
5947 value = value->v.Starred.value;
5948 if (star >= 0) {
5949 const char *e = "multiple starred names in sequence pattern";
5950 return compiler_error(c, e);
5951 }
5952 star_wildcard = WILDCARD_CHECK(value);
5953 star = i;
5954 }
5955 only_wildcard &= WILDCARD_CHECK(value);
5956 }
5957 basicblock *end, *fail_pop_1;
5958 RETURN_IF_FALSE(end = compiler_new_block(c));
5959 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5960 ADDOP(c, MATCH_SEQUENCE);
5961 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5962 NEXT_BLOCK(c);
5963 if (star < 0) {
5964 // No star: len(subject) == size
5965 ADDOP(c, GET_LEN);
5966 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size));
5967 ADDOP_COMPARE(c, Eq);
5968 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5969 NEXT_BLOCK(c);
5970 }
5971 else if (size > 1) {
5972 // Star: len(subject) >= size - 1
5973 ADDOP(c, GET_LEN);
5974 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size - 1));
5975 ADDOP_COMPARE(c, GtE);
5976 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5977 NEXT_BLOCK(c);
5978 }
5979 if (only_wildcard) {
5980 // Patterns like: [] / [_] / [_, _] / [*_] / [_, *_] / [_, _, *_] / etc.
5981 ADDOP(c, POP_TOP);
5982 ADDOP_LOAD_CONST(c, Py_True);
5983 }
5984 else if (star_wildcard) {
5985 RETURN_IF_FALSE(pattern_helper_sequence_subscr(c, values, star, pc));
5986 }
5987 else {
5988 RETURN_IF_FALSE(pattern_helper_sequence_unpack(c, values, star, pc));
5989 }
5990 ADDOP_JUMP(c, JUMP_FORWARD, end);
5991 compiler_use_next_block(c, fail_pop_1);
5992 ADDOP(c, POP_TOP)
5993 ADDOP_LOAD_CONST(c, Py_False);
5994 compiler_use_next_block(c, end);
5995 return 1;
5996}
5997
5998
5999static int
6000compiler_pattern_value(struct compiler *c, expr_ty p, pattern_context *pc)
6001{
6002 assert(p->kind == Attribute_kind);
6003 assert(p->v.Attribute.ctx == Load);
6004 VISIT(c, expr, p);
6005 ADDOP_COMPARE(c, Eq);
6006 return 1;
6007}
6008
6009
6010static int
6011compiler_pattern_wildcard(struct compiler *c, expr_ty p, pattern_context *pc)
6012{
6013 assert(p->kind == Name_kind);
6014 assert(p->v.Name.ctx == Store);
6015 assert(WILDCARD_CHECK(p));
6016 if (!pc->allow_irrefutable) {
6017 // Whoops, can't have a wildcard here!
6018 const char *e = "wildcard makes remaining patterns unreachable";
6019 return compiler_error(c, e);
6020 }
6021 ADDOP(c, POP_TOP);
6022 ADDOP_LOAD_CONST(c, Py_True);
6023 return 1;
6024}
6025
6026
6027static int
6028compiler_pattern(struct compiler *c, expr_ty p, pattern_context *pc)
6029{
6030 SET_LOC(c, p);
6031 switch (p->kind) {
6032 case Attribute_kind:
6033 return compiler_pattern_value(c, p, pc);
6034 case BinOp_kind:
6035 // Because we allow "2+2j", things like "2+2" make it this far:
6036 return compiler_error(c, "patterns cannot include operators");
6037 case Call_kind:
6038 return compiler_pattern_class(c, p, pc);
6039 case Constant_kind:
6040 return compiler_pattern_literal(c, p, pc);
6041 case Dict_kind:
6042 return compiler_pattern_mapping(c, p, pc);
6043 case JoinedStr_kind:
6044 // Because we allow strings, f-strings make it this far:
6045 return compiler_error(c, "patterns cannot include f-strings");
6046 case List_kind:
6047 case Tuple_kind:
6048 return compiler_pattern_sequence(c, p, pc);
6049 case MatchAs_kind:
6050 return compiler_pattern_as(c, p, pc);
6051 case MatchOr_kind:
6052 return compiler_pattern_or(c, p, pc);
6053 case Name_kind:
6054 if (WILDCARD_CHECK(p)) {
6055 return compiler_pattern_wildcard(c, p, pc);
6056 }
6057 return compiler_pattern_capture(c, p, pc);
6058 default:
6059 Py_UNREACHABLE();
6060 }
6061}
6062
6063
6064static int
6065compiler_match(struct compiler *c, stmt_ty s)
6066{
6067 VISIT(c, expr, s->v.Match.subject);
6068 basicblock *next, *end;
6069 RETURN_IF_FALSE(end = compiler_new_block(c));
6070 Py_ssize_t cases = asdl_seq_LEN(s->v.Match.cases);
6071 assert(cases);
6072 pattern_context pc;
6073 // We use pc.stores to track:
6074 // - Repeated name assignments in the same pattern.
6075 // - Different name assignments in alternatives.
6076 // It's a set of names, but we don't create it until it's needed:
6077 pc.stores = NULL;
6078 match_case_ty m = asdl_seq_GET(s->v.Match.cases, cases - 1);
6079 int has_default = WILDCARD_CHECK(m->pattern) && 1 < cases;
6080 for (Py_ssize_t i = 0; i < cases - has_default; i++) {
6081 m = asdl_seq_GET(s->v.Match.cases, i);
6082 SET_LOC(c, m->pattern);
6083 RETURN_IF_FALSE(next = compiler_new_block(c));
6084 // If pc.allow_irrefutable is 0, any name captures against our subject
6085 // will raise. Irrefutable cases must be either guarded, last, or both:
6086 pc.allow_irrefutable = m->guard != NULL || i == cases - 1;
6087 // Only copy the subject if we're *not* on the last case:
6088 if (i != cases - has_default - 1) {
6089 ADDOP(c, DUP_TOP);
6090 }
6091 int result = compiler_pattern(c, m->pattern, &pc);
6092 Py_CLEAR(pc.stores);
6093 RETURN_IF_FALSE(result);
6094 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, next);
6095 NEXT_BLOCK(c);
6096 if (m->guard) {
6097 RETURN_IF_FALSE(compiler_jump_if(c, m->guard, next, 0));
6098 }
6099 // Success! Pop the subject off, we're done with it:
6100 if (i != cases - has_default - 1) {
6101 ADDOP(c, POP_TOP);
6102 }
6103 VISIT_SEQ(c, stmt, m->body);
6104 ADDOP_JUMP(c, JUMP_FORWARD, end);
6105 compiler_use_next_block(c, next);
6106 }
6107 if (has_default) {
6108 if (cases == 1) {
6109 // No matches. Done with the subject:
6110 ADDOP(c, POP_TOP);
6111 }
6112 // A trailing "case _" is common, and lets us save a bit of redundant
6113 // pushing and popping in the loop above:
6114 m = asdl_seq_GET(s->v.Match.cases, cases - 1);
6115 SET_LOC(c, m->pattern);
6116 if (m->guard) {
6117 RETURN_IF_FALSE(compiler_jump_if(c, m->guard, end, 0));
6118 }
6119 VISIT_SEQ(c, stmt, m->body);
6120 }
6121 compiler_use_next_block(c, end);
6122 return 1;
6123}
6124
6125
6126#undef WILDCARD_CHECK
6127
6128
Thomas Wouters89f507f2006-12-13 04:49:30 +00006129/* End of the compiler section, beginning of the assembler section */
6130
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006131/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07006132 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006133
6134 XXX must handle implicit jumps from one block to next
6135*/
6136
Thomas Wouters89f507f2006-12-13 04:49:30 +00006137struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006138 PyObject *a_bytecode; /* string containing bytecode */
6139 int a_offset; /* offset into bytecode */
6140 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006141 PyObject *a_lnotab; /* string containing lnotab */
6142 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00006143 int a_prevlineno; /* lineno of last emitted line in line table */
6144 int a_lineno; /* lineno of last emitted instruction */
6145 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006146 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00006147};
6148
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006149Py_LOCAL_INLINE(void)
6150stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006151{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02006152 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00006153 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006154 assert(b->b_startdepth < 0);
6155 b->b_startdepth = depth;
6156 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02006157 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006158}
6159
6160/* Find the flow path that needs the largest stack. We assume that
6161 * cycles in the flow graph have no net effect on the stack depth.
6162 */
6163static int
6164stackdepth(struct compiler *c)
6165{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006166 basicblock *b, *entryblock = NULL;
6167 basicblock **stack, **sp;
6168 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006169 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006170 b->b_startdepth = INT_MIN;
6171 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006172 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006173 }
Mark Shannon67969f52021-04-07 10:52:07 +01006174 assert(entryblock!= NULL);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006175 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
6176 if (!stack) {
6177 PyErr_NoMemory();
6178 return -1;
6179 }
6180
6181 sp = stack;
Mark Shannonb37181e2021-04-06 11:48:59 +01006182 if (c->u->u_ste->ste_generator || c->u->u_ste->ste_coroutine) {
6183 stackdepth_push(&sp, entryblock, 1);
6184 } else {
6185 stackdepth_push(&sp, entryblock, 0);
6186 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006187 while (sp != stack) {
6188 b = *--sp;
6189 int depth = b->b_startdepth;
6190 assert(depth >= 0);
6191 basicblock *next = b->b_next;
6192 for (int i = 0; i < b->b_iused; i++) {
6193 struct instr *instr = &b->b_instr[i];
6194 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
6195 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01006196 PyErr_Format(PyExc_SystemError,
6197 "compiler stack_effect(opcode=%d, arg=%i) failed",
6198 instr->i_opcode, instr->i_oparg);
6199 return -1;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006200 }
6201 int new_depth = depth + effect;
6202 if (new_depth > maxdepth) {
6203 maxdepth = new_depth;
6204 }
6205 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01006206 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006207 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
6208 assert(effect != PY_INVALID_STACK_EFFECT);
6209 int target_depth = depth + effect;
6210 if (target_depth > maxdepth) {
6211 maxdepth = target_depth;
6212 }
6213 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006214 stackdepth_push(&sp, instr->i_target, target_depth);
6215 }
6216 depth = new_depth;
6217 if (instr->i_opcode == JUMP_ABSOLUTE ||
6218 instr->i_opcode == JUMP_FORWARD ||
6219 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00006220 instr->i_opcode == RAISE_VARARGS ||
6221 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006222 {
6223 /* remaining code is dead */
6224 next = NULL;
6225 break;
6226 }
6227 }
6228 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00006229 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006230 stackdepth_push(&sp, next, depth);
6231 }
6232 }
6233 PyObject_Free(stack);
6234 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006235}
6236
6237static int
6238assemble_init(struct assembler *a, int nblocks, int firstlineno)
6239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006240 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00006241 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00006242 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006243 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00006244 if (a->a_bytecode == NULL) {
6245 goto error;
6246 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006247 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00006248 if (a->a_lnotab == NULL) {
6249 goto error;
6250 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07006251 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006252 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00006253 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006254 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006255 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00006256error:
6257 Py_XDECREF(a->a_bytecode);
6258 Py_XDECREF(a->a_lnotab);
6259 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006260}
6261
6262static void
6263assemble_free(struct assembler *a)
6264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006265 Py_XDECREF(a->a_bytecode);
6266 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006267}
6268
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006269static int
6270blocksize(basicblock *b)
6271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006272 int i;
6273 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006275 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006276 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006277 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006278}
6279
Guido van Rossumf68d8e52001-04-14 17:55:09 +00006280static int
Mark Shannon877df852020-11-12 09:43:29 +00006281assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006282{
Mark Shannon877df852020-11-12 09:43:29 +00006283 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006284 if (a->a_lnotab_off + 2 >= len) {
6285 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
6286 return 0;
6287 }
Pablo Galindo86e322f2021-01-30 13:54:22 +00006288 unsigned char *lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab);
6289 lnotab += a->a_lnotab_off;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006290 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00006291 *lnotab++ = bdelta;
6292 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006293 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006294}
6295
Mark Shannon877df852020-11-12 09:43:29 +00006296/* Appends a range to the end of the line number table. See
6297 * Objects/lnotab_notes.txt for the description of the line number table. */
6298
6299static int
6300assemble_line_range(struct assembler *a)
6301{
6302 int ldelta, bdelta;
6303 bdelta = (a->a_offset - a->a_lineno_start) * 2;
6304 if (bdelta == 0) {
6305 return 1;
6306 }
6307 if (a->a_lineno < 0) {
6308 ldelta = -128;
6309 }
6310 else {
6311 ldelta = a->a_lineno - a->a_prevlineno;
6312 a->a_prevlineno = a->a_lineno;
6313 while (ldelta > 127) {
6314 if (!assemble_emit_linetable_pair(a, 0, 127)) {
6315 return 0;
6316 }
6317 ldelta -= 127;
6318 }
6319 while (ldelta < -127) {
6320 if (!assemble_emit_linetable_pair(a, 0, -127)) {
6321 return 0;
6322 }
6323 ldelta += 127;
6324 }
6325 }
6326 assert(-128 <= ldelta && ldelta < 128);
6327 while (bdelta > 254) {
6328 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
6329 return 0;
6330 }
6331 ldelta = a->a_lineno < 0 ? -128 : 0;
6332 bdelta -= 254;
6333 }
6334 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
6335 return 0;
6336 }
6337 a->a_lineno_start = a->a_offset;
6338 return 1;
6339}
6340
6341static int
6342assemble_lnotab(struct assembler *a, struct instr *i)
6343{
6344 if (i->i_lineno == a->a_lineno) {
6345 return 1;
6346 }
6347 if (!assemble_line_range(a)) {
6348 return 0;
6349 }
6350 a->a_lineno = i->i_lineno;
6351 return 1;
6352}
6353
6354
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006355/* assemble_emit()
6356 Extend the bytecode with a new instruction.
6357 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00006358*/
6359
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00006360static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006361assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00006362{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006363 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006364 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03006365 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006366
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006367 arg = i->i_oparg;
6368 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006369 if (i->i_lineno && !assemble_lnotab(a, i))
6370 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006371 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006372 if (len > PY_SSIZE_T_MAX / 2)
6373 return 0;
6374 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
6375 return 0;
6376 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03006377 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006378 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006379 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006380 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00006381}
6382
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00006383static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006384assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00006385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006386 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006387 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006388 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00006389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006390 /* Compute the size of each block and fixup jump args.
6391 Replace block pointer with position in bytecode. */
6392 do {
6393 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006394 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006395 bsize = blocksize(b);
6396 b->b_offset = totsize;
6397 totsize += bsize;
6398 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006399 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006400 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6401 bsize = b->b_offset;
6402 for (i = 0; i < b->b_iused; i++) {
6403 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006404 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006405 /* Relative jumps are computed relative to
6406 the instruction pointer after fetching
6407 the jump instruction.
6408 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006409 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01006410 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006411 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01006412 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006413 instr->i_oparg -= bsize;
6414 }
6415 if (instrsize(instr->i_oparg) != isize) {
6416 extended_arg_recompile = 1;
6417 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006418 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006419 }
6420 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00006421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006422 /* XXX: This is an awful hack that could hurt performance, but
6423 on the bright side it should work until we come up
6424 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00006425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006426 The issue is that in the first loop blocksize() is called
6427 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006428 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006429 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00006430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006431 So we loop until we stop seeing new EXTENDED_ARGs.
6432 The only EXTENDED_ARGs that could be popping up are
6433 ones in jump instructions. So this should converge
6434 fairly quickly.
6435 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006436 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00006437}
6438
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006439static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01006440dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006442 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006443 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006445 tuple = PyTuple_New(size);
6446 if (tuple == NULL)
6447 return NULL;
6448 while (PyDict_Next(dict, &pos, &k, &v)) {
6449 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006450 Py_INCREF(k);
6451 assert((i - offset) < size);
6452 assert((i - offset) >= 0);
6453 PyTuple_SET_ITEM(tuple, i - offset, k);
6454 }
6455 return tuple;
6456}
6457
6458static PyObject *
6459consts_dict_keys_inorder(PyObject *dict)
6460{
6461 PyObject *consts, *k, *v;
6462 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
6463
6464 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
6465 if (consts == NULL)
6466 return NULL;
6467 while (PyDict_Next(dict, &pos, &k, &v)) {
6468 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03006469 /* The keys of the dictionary can be tuples wrapping a contant.
6470 * (see compiler_add_o and _PyCode_ConstantKey). In that case
6471 * the object we want is always second. */
6472 if (PyTuple_CheckExact(k)) {
6473 k = PyTuple_GET_ITEM(k, 1);
6474 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006475 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006476 assert(i < size);
6477 assert(i >= 0);
6478 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006479 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006480 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006481}
6482
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006483static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006484compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006486 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006487 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006488 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04006489 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006490 if (ste->ste_nested)
6491 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07006492 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006493 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07006494 if (!ste->ste_generator && ste->ste_coroutine)
6495 flags |= CO_COROUTINE;
6496 if (ste->ste_generator && ste->ste_coroutine)
6497 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006498 if (ste->ste_varargs)
6499 flags |= CO_VARARGS;
6500 if (ste->ste_varkeywords)
6501 flags |= CO_VARKEYWORDS;
6502 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00006503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006504 /* (Only) inherit compilerflags in PyCF_MASK */
6505 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00006506
Pablo Galindo90235812020-03-15 04:29:22 +00006507 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07006508 ste->ste_coroutine &&
6509 !ste->ste_generator) {
6510 flags |= CO_COROUTINE;
6511 }
6512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006513 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00006514}
6515
Inada Naokibdb941b2021-02-10 09:20:42 +09006516// Merge *obj* with constant cache.
INADA Naokic2e16072018-11-26 21:23:22 +09006517// Unlike merge_consts_recursive(), this function doesn't work recursively.
6518static int
Inada Naokibdb941b2021-02-10 09:20:42 +09006519merge_const_one(struct compiler *c, PyObject **obj)
INADA Naokic2e16072018-11-26 21:23:22 +09006520{
Inada Naokibdb941b2021-02-10 09:20:42 +09006521 PyObject *key = _PyCode_ConstantKey(*obj);
INADA Naokic2e16072018-11-26 21:23:22 +09006522 if (key == NULL) {
6523 return 0;
6524 }
6525
6526 // t is borrowed reference
6527 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
6528 Py_DECREF(key);
6529 if (t == NULL) {
6530 return 0;
6531 }
Inada Naokibdb941b2021-02-10 09:20:42 +09006532 if (t == key) { // obj is new constant.
INADA Naokic2e16072018-11-26 21:23:22 +09006533 return 1;
6534 }
6535
Inada Naokibdb941b2021-02-10 09:20:42 +09006536 if (PyTuple_CheckExact(t)) {
6537 // t is still borrowed reference
6538 t = PyTuple_GET_ITEM(t, 1);
6539 }
6540
6541 Py_INCREF(t);
6542 Py_DECREF(*obj);
6543 *obj = t;
INADA Naokic2e16072018-11-26 21:23:22 +09006544 return 1;
6545}
6546
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006547static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01006548makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006550 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006551 PyObject *names = NULL;
6552 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006553 PyObject *name = NULL;
6554 PyObject *freevars = NULL;
6555 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006556 Py_ssize_t nlocals;
6557 int nlocals_int;
6558 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01006559 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006561 names = dict_keys_inorder(c->u->u_names, 0);
6562 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006563 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006564 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006565 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006566 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
6567 if (!cellvars)
6568 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006569 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006570 if (!freevars)
6571 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006572
Inada Naokibdb941b2021-02-10 09:20:42 +09006573 if (!merge_const_one(c, &names) ||
6574 !merge_const_one(c, &varnames) ||
6575 !merge_const_one(c, &cellvars) ||
6576 !merge_const_one(c, &freevars))
INADA Naokic2e16072018-11-26 21:23:22 +09006577 {
6578 goto error;
6579 }
6580
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006581 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01006582 assert(nlocals < INT_MAX);
6583 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
6584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006585 flags = compute_code_flags(c);
6586 if (flags < 0)
6587 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006588
Mark Shannon6e8128f2020-07-30 10:03:00 +01006589 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
6590 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006591 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006592 }
Inada Naokibdb941b2021-02-10 09:20:42 +09006593 if (!merge_const_one(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006594 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09006595 goto error;
6596 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006597
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01006598 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01006599 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01006600 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006601 maxdepth = stackdepth(c);
6602 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006603 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006604 goto error;
6605 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006606 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00006607 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01006608 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006609 varnames, freevars, cellvars, c->c_filename,
6610 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006611 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006612 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006613 Py_XDECREF(names);
6614 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006615 Py_XDECREF(name);
6616 Py_XDECREF(freevars);
6617 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006618 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006619}
6620
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006621
6622/* For debugging purposes only */
6623#if 0
6624static void
6625dump_instr(const struct instr *i)
6626{
Mark Shannon582aaf12020-08-04 17:30:11 +01006627 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
6628 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006629 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006631 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006632 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006633 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006634 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006635 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6636 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006637}
6638
6639static void
6640dump_basicblock(const basicblock *b)
6641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006642 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01006643 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
6644 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006645 if (b->b_instr) {
6646 int i;
6647 for (i = 0; i < b->b_iused; i++) {
6648 fprintf(stderr, " [%02d] ", i);
6649 dump_instr(b->b_instr + i);
6650 }
6651 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006652}
6653#endif
6654
Mark Shannon5977a792020-12-02 13:31:40 +00006655
6656static int
6657normalize_basic_block(basicblock *bb);
6658
Mark Shannon6e8128f2020-07-30 10:03:00 +01006659static int
6660optimize_cfg(struct assembler *a, PyObject *consts);
6661
Mark Shannon5977a792020-12-02 13:31:40 +00006662static int
6663ensure_exits_have_lineno(struct compiler *c);
6664
Mark Shannonb37181e2021-04-06 11:48:59 +01006665static int
6666insert_generator_prefix(struct compiler *c, basicblock *entryblock) {
6667
6668 int flags = compute_code_flags(c);
6669 if (flags < 0) {
6670 return -1;
6671 }
6672 int kind;
6673 if (flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
6674 if (flags & CO_COROUTINE) {
6675 kind = 1;
6676 }
6677 else if (flags & CO_ASYNC_GENERATOR) {
6678 kind = 2;
6679 }
6680 else {
6681 kind = 0;
6682 }
6683 }
6684 else {
6685 return 0;
6686 }
6687 if (compiler_next_instr(entryblock) < 0) {
6688 return -1;
6689 }
6690 for (int i = entryblock->b_iused-1; i > 0; i--) {
6691 entryblock->b_instr[i] = entryblock->b_instr[i-1];
6692 }
6693 entryblock->b_instr[0].i_opcode = GEN_START;
6694 entryblock->b_instr[0].i_oparg = kind;
6695 entryblock->b_instr[0].i_lineno = -1;
6696 entryblock->b_instr[0].i_target = NULL;
6697 return 0;
6698}
6699
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006700static PyCodeObject *
6701assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006703 basicblock *b, *entryblock;
6704 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006705 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006706 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006707 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006709 /* Make sure every block that falls off the end returns None.
6710 XXX NEXT_BLOCK() isn't quite right, because if the last
6711 block ends with a jump or return b_next shouldn't set.
6712 */
6713 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00006714 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006715 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006716 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006717 ADDOP(c, RETURN_VALUE);
6718 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006719
Mark Shannon5977a792020-12-02 13:31:40 +00006720 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6721 if (normalize_basic_block(b)) {
Alex Henrie503627f2021-03-02 03:20:25 -07006722 return NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006723 }
6724 }
6725
6726 if (ensure_exits_have_lineno(c)) {
Alex Henrie503627f2021-03-02 03:20:25 -07006727 return NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006728 }
6729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006730 nblocks = 0;
6731 entryblock = NULL;
6732 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6733 nblocks++;
6734 entryblock = b;
6735 }
Mark Shannon67969f52021-04-07 10:52:07 +01006736 assert(entryblock != NULL);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006737
Mark Shannonb37181e2021-04-06 11:48:59 +01006738 if (insert_generator_prefix(c, entryblock)) {
6739 goto error;
6740 }
6741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006742 /* Set firstlineno if it wasn't explicitly set. */
6743 if (!c->u->u_firstlineno) {
Mark Shannon67969f52021-04-07 10:52:07 +01006744 if (entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006745 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00006746 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006747 c->u->u_firstlineno = 1;
6748 }
Mark Shannon5977a792020-12-02 13:31:40 +00006749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006750 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6751 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006752 a.a_entry = entryblock;
6753 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006754
Mark Shannon6e8128f2020-07-30 10:03:00 +01006755 consts = consts_dict_keys_inorder(c->u->u_consts);
6756 if (consts == NULL) {
6757 goto error;
6758 }
6759 if (optimize_cfg(&a, consts)) {
6760 goto error;
6761 }
6762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006763 /* Can't modify the bytecode after computing jump offsets. */
6764 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006765
Mark Shannoncc75ab72020-11-12 19:49:33 +00006766 /* Emit code. */
6767 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006768 for (j = 0; j < b->b_iused; j++)
6769 if (!assemble_emit(&a, &b->b_instr[j]))
6770 goto error;
6771 }
Mark Shannon877df852020-11-12 09:43:29 +00006772 if (!assemble_line_range(&a)) {
6773 return 0;
6774 }
6775 /* Emit sentinel at end of line number table */
6776 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
6777 goto error;
6778 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006779
Inada Naokibdb941b2021-02-10 09:20:42 +09006780 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006781 goto error;
Inada Naokibdb941b2021-02-10 09:20:42 +09006782 }
6783 if (!merge_const_one(c, &a.a_lnotab)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006784 goto error;
Inada Naokibdb941b2021-02-10 09:20:42 +09006785 }
6786 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0) {
6787 goto error;
6788 }
6789 if (!merge_const_one(c, &a.a_bytecode)) {
6790 goto error;
6791 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006792
Mark Shannon6e8128f2020-07-30 10:03:00 +01006793 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006794 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006795 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006796 assemble_free(&a);
6797 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006798}
Georg Brandl8334fd92010-12-04 10:26:46 +00006799
Mark Shannon6e8128f2020-07-30 10:03:00 +01006800/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6801 with LOAD_CONST (c1, c2, ... cn).
6802 The consts table must still be in list form so that the
6803 new constant (c1, c2, ... cn) can be appended.
6804 Called with codestr pointing to the first LOAD_CONST.
6805*/
6806static int
6807fold_tuple_on_constants(struct instr *inst,
6808 int n, PyObject *consts)
6809{
6810 /* Pre-conditions */
6811 assert(PyList_CheckExact(consts));
6812 assert(inst[n].i_opcode == BUILD_TUPLE);
6813 assert(inst[n].i_oparg == n);
6814
6815 for (int i = 0; i < n; i++) {
6816 if (inst[i].i_opcode != LOAD_CONST) {
6817 return 0;
6818 }
6819 }
6820
6821 /* Buildup new tuple of constants */
6822 PyObject *newconst = PyTuple_New(n);
6823 if (newconst == NULL) {
6824 return -1;
6825 }
6826 for (int i = 0; i < n; i++) {
6827 int arg = inst[i].i_oparg;
6828 PyObject *constant = PyList_GET_ITEM(consts, arg);
6829 Py_INCREF(constant);
6830 PyTuple_SET_ITEM(newconst, i, constant);
6831 }
6832 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006833 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006834 Py_DECREF(newconst);
6835 PyErr_SetString(PyExc_OverflowError, "too many constants");
6836 return -1;
6837 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006838 if (PyList_Append(consts, newconst)) {
6839 Py_DECREF(newconst);
6840 return -1;
6841 }
6842 Py_DECREF(newconst);
6843 for (int i = 0; i < n; i++) {
6844 inst[i].i_opcode = NOP;
6845 }
6846 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006847 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006848 return 0;
6849}
6850
Mark Shannon28b75c82020-12-23 11:43:10 +00006851
6852static int
6853eliminate_jump_to_jump(basicblock *bb, int opcode) {
6854 assert (bb->b_iused > 0);
6855 struct instr *inst = &bb->b_instr[bb->b_iused-1];
6856 assert (is_jump(inst));
6857 assert (inst->i_target->b_iused > 0);
6858 struct instr *target = &inst->i_target->b_instr[0];
6859 if (inst->i_target == target->i_target) {
6860 /* Nothing to do */
6861 return 0;
6862 }
6863 int lineno = target->i_lineno;
6864 if (add_jump_to_block(bb, opcode, lineno, target->i_target) == 0) {
6865 return -1;
6866 }
6867 assert (bb->b_iused >= 2);
6868 bb->b_instr[bb->b_iused-2].i_opcode = NOP;
6869 return 0;
6870}
6871
Mark Shannoncc75ab72020-11-12 19:49:33 +00006872/* Maximum size of basic block that should be copied in optimizer */
6873#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006874
6875/* Optimization */
6876static int
6877optimize_basic_block(basicblock *bb, PyObject *consts)
6878{
6879 assert(PyList_CheckExact(consts));
6880 struct instr nop;
6881 nop.i_opcode = NOP;
6882 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006883 for (int i = 0; i < bb->b_iused; i++) {
6884 struct instr *inst = &bb->b_instr[i];
6885 int oparg = inst->i_oparg;
6886 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006887 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006888 /* Skip over empty basic blocks. */
6889 while (inst->i_target->b_iused == 0) {
6890 inst->i_target = inst->i_target->b_next;
6891 }
6892 target = &inst->i_target->b_instr[0];
6893 }
6894 else {
6895 target = &nop;
6896 }
6897 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006898 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006899 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006900 {
6901 PyObject* cnt;
6902 int is_true;
6903 int jump_if_true;
6904 switch(nextop) {
6905 case POP_JUMP_IF_FALSE:
6906 case POP_JUMP_IF_TRUE:
6907 cnt = PyList_GET_ITEM(consts, oparg);
6908 is_true = PyObject_IsTrue(cnt);
6909 if (is_true == -1) {
6910 goto error;
6911 }
6912 inst->i_opcode = NOP;
6913 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6914 if (is_true == jump_if_true) {
6915 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6916 bb->b_nofallthrough = 1;
6917 }
6918 else {
6919 bb->b_instr[i+1].i_opcode = NOP;
6920 }
6921 break;
6922 case JUMP_IF_FALSE_OR_POP:
6923 case JUMP_IF_TRUE_OR_POP:
6924 cnt = PyList_GET_ITEM(consts, oparg);
6925 is_true = PyObject_IsTrue(cnt);
6926 if (is_true == -1) {
6927 goto error;
6928 }
6929 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6930 if (is_true == jump_if_true) {
6931 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6932 bb->b_nofallthrough = 1;
6933 }
6934 else {
6935 inst->i_opcode = NOP;
6936 bb->b_instr[i+1].i_opcode = NOP;
6937 }
6938 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006939 }
6940 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006941 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006942
6943 /* Try to fold tuples of constants.
6944 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6945 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6946 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6947 case BUILD_TUPLE:
6948 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6949 switch(oparg) {
6950 case 1:
6951 inst->i_opcode = NOP;
6952 bb->b_instr[i+1].i_opcode = NOP;
6953 break;
6954 case 2:
6955 inst->i_opcode = ROT_TWO;
6956 bb->b_instr[i+1].i_opcode = NOP;
6957 break;
6958 case 3:
6959 inst->i_opcode = ROT_THREE;
6960 bb->b_instr[i+1].i_opcode = ROT_TWO;
6961 }
6962 break;
6963 }
6964 if (i >= oparg) {
6965 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6966 goto error;
6967 }
6968 }
6969 break;
6970
6971 /* Simplify conditional jump to conditional jump where the
6972 result of the first test implies the success of a similar
6973 test or the failure of the opposite test.
6974 Arises in code like:
6975 "a and b or c"
6976 "(a and b) and c"
6977 "(a or b) or c"
6978 "(a or b) and c"
6979 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6980 --> x:JUMP_IF_FALSE_OR_POP z
6981 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6982 --> x:POP_JUMP_IF_FALSE y+1
6983 where y+1 is the instruction following the second test.
6984 */
6985 case JUMP_IF_FALSE_OR_POP:
6986 switch(target->i_opcode) {
6987 case POP_JUMP_IF_FALSE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006988 if (inst->i_lineno == target->i_lineno) {
6989 *inst = *target;
6990 i--;
6991 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006992 break;
6993 case JUMP_ABSOLUTE:
6994 case JUMP_FORWARD:
6995 case JUMP_IF_FALSE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006996 if (inst->i_lineno == target->i_lineno &&
6997 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006998 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006999 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007000 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007001 break;
7002 case JUMP_IF_TRUE_OR_POP:
7003 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00007004 if (inst->i_lineno == target->i_lineno) {
7005 inst->i_opcode = POP_JUMP_IF_FALSE;
7006 inst->i_target = inst->i_target->b_next;
7007 --i;
7008 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007009 break;
7010 }
7011 break;
7012
7013 case JUMP_IF_TRUE_OR_POP:
7014 switch(target->i_opcode) {
7015 case POP_JUMP_IF_TRUE:
Mark Shannon28b75c82020-12-23 11:43:10 +00007016 if (inst->i_lineno == target->i_lineno) {
7017 *inst = *target;
7018 i--;
7019 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007020 break;
7021 case JUMP_ABSOLUTE:
7022 case JUMP_FORWARD:
7023 case JUMP_IF_TRUE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00007024 if (inst->i_lineno == target->i_lineno &&
7025 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00007026 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007027 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007028 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007029 break;
7030 case JUMP_IF_FALSE_OR_POP:
7031 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00007032 if (inst->i_lineno == target->i_lineno) {
7033 inst->i_opcode = POP_JUMP_IF_TRUE;
7034 inst->i_target = inst->i_target->b_next;
7035 --i;
7036 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007037 break;
7038 }
7039 break;
7040
7041 case POP_JUMP_IF_FALSE:
7042 switch(target->i_opcode) {
7043 case JUMP_ABSOLUTE:
7044 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007045 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00007046 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007047 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007048 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007049 break;
7050 }
7051 break;
7052
7053 case POP_JUMP_IF_TRUE:
7054 switch(target->i_opcode) {
7055 case JUMP_ABSOLUTE:
7056 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007057 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00007058 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007059 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007060 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007061 break;
7062 }
7063 break;
7064
7065 case JUMP_ABSOLUTE:
7066 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007067 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007068 switch(target->i_opcode) {
7069 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007070 if (eliminate_jump_to_jump(bb, inst->i_opcode)) {
7071 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00007072 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007073 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00007074
Mark Shannon6e8128f2020-07-30 10:03:00 +01007075 case JUMP_ABSOLUTE:
Mark Shannon28b75c82020-12-23 11:43:10 +00007076 if (eliminate_jump_to_jump(bb, JUMP_ABSOLUTE)) {
7077 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00007078 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007079 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00007080 default:
7081 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
7082 basicblock *to_copy = inst->i_target;
7083 inst->i_opcode = NOP;
7084 for (i = 0; i < to_copy->b_iused; i++) {
7085 int index = compiler_next_instr(bb);
7086 if (index < 0) {
7087 return -1;
7088 }
7089 bb->b_instr[index] = to_copy->b_instr[i];
7090 }
7091 bb->b_exit = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007092 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00007093 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007094 }
7095 }
7096 return 0;
7097error:
7098 return -1;
7099}
7100
7101
7102static void
Mark Shannon1659ad12021-01-13 15:05:04 +00007103clean_basic_block(basicblock *bb, int prev_lineno) {
7104 /* Remove NOPs when legal to do so. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01007105 int dest = 0;
7106 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00007107 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007108 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00007109 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007110 if (lineno < 0) {
7111 continue;
7112 }
Mark Shannon266b4622020-11-17 19:30:14 +00007113 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007114 if (prev_lineno == lineno) {
7115 continue;
7116 }
Mark Shannon266b4622020-11-17 19:30:14 +00007117 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007118 if (src < bb->b_iused - 1) {
7119 int next_lineno = bb->b_instr[src+1].i_lineno;
7120 if (next_lineno < 0 || next_lineno == lineno) {
7121 bb->b_instr[src+1].i_lineno = lineno;
7122 continue;
Mark Shannon877df852020-11-12 09:43:29 +00007123 }
7124 }
Mark Shannon266b4622020-11-17 19:30:14 +00007125 else {
7126 basicblock* next = bb->b_next;
7127 while (next && next->b_iused == 0) {
7128 next = next->b_next;
7129 }
7130 /* or if last instruction in BB and next BB has same line number */
7131 if (next) {
7132 if (lineno == next->b_instr[0].i_lineno) {
7133 continue;
7134 }
7135 }
7136 }
7137
Mark Shannon6e8128f2020-07-30 10:03:00 +01007138 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00007139 if (dest != src) {
7140 bb->b_instr[dest] = bb->b_instr[src];
7141 }
7142 dest++;
7143 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007144 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007145 assert(dest <= bb->b_iused);
7146 bb->b_iused = dest;
7147}
7148
Mark Shannon266b4622020-11-17 19:30:14 +00007149static int
7150normalize_basic_block(basicblock *bb) {
7151 /* Mark blocks as exit and/or nofallthrough.
7152 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007153 for (int i = 0; i < bb->b_iused; i++) {
7154 switch(bb->b_instr[i].i_opcode) {
7155 case RETURN_VALUE:
7156 case RAISE_VARARGS:
7157 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007158 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00007159 bb->b_nofallthrough = 1;
7160 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007161 case JUMP_ABSOLUTE:
7162 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007163 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00007164 /* fall through */
7165 case POP_JUMP_IF_FALSE:
7166 case POP_JUMP_IF_TRUE:
7167 case JUMP_IF_FALSE_OR_POP:
7168 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00007169 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00007170 if (i != bb->b_iused-1) {
7171 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
7172 return -1;
7173 }
Mark Shannon5977a792020-12-02 13:31:40 +00007174 /* Skip over empty basic blocks. */
7175 while (bb->b_instr[i].i_target->b_iused == 0) {
7176 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
7177 }
7178
Mark Shannoncc75ab72020-11-12 19:49:33 +00007179 }
7180 }
Mark Shannon266b4622020-11-17 19:30:14 +00007181 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007182}
7183
Mark Shannon6e8128f2020-07-30 10:03:00 +01007184static int
7185mark_reachable(struct assembler *a) {
7186 basicblock **stack, **sp;
7187 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
7188 if (stack == NULL) {
7189 return -1;
7190 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007191 a->a_entry->b_predecessors = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007192 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007193 while (sp > stack) {
7194 basicblock *b = *(--sp);
Mark Shannon3bd60352021-01-13 12:05:43 +00007195 if (b->b_next && !b->b_nofallthrough) {
7196 if (b->b_next->b_predecessors == 0) {
7197 *sp++ = b->b_next;
7198 }
7199 b->b_next->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007200 }
7201 for (int i = 0; i < b->b_iused; i++) {
7202 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01007203 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007204 target = b->b_instr[i].i_target;
Mark Shannon3bd60352021-01-13 12:05:43 +00007205 if (target->b_predecessors == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007206 *sp++ = target;
7207 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007208 target->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007209 }
7210 }
7211 }
7212 PyObject_Free(stack);
7213 return 0;
7214}
7215
Mark Shannon3bd60352021-01-13 12:05:43 +00007216static void
7217eliminate_empty_basic_blocks(basicblock *entry) {
7218 /* Eliminate empty blocks */
7219 for (basicblock *b = entry; b != NULL; b = b->b_next) {
7220 basicblock *next = b->b_next;
7221 if (next) {
7222 while (next->b_iused == 0 && next->b_next) {
7223 next = next->b_next;
7224 }
7225 b->b_next = next;
7226 }
7227 }
7228 for (basicblock *b = entry; b != NULL; b = b->b_next) {
7229 if (b->b_iused == 0) {
7230 continue;
7231 }
7232 if (is_jump(&b->b_instr[b->b_iused-1])) {
7233 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7234 while (target->b_iused == 0) {
7235 target = target->b_next;
7236 }
7237 b->b_instr[b->b_iused-1].i_target = target;
7238 }
7239 }
7240}
7241
7242
Mark Shannon5977a792020-12-02 13:31:40 +00007243/* If an instruction has no line number, but it's predecessor in the BB does,
Mark Shannon3bd60352021-01-13 12:05:43 +00007244 * then copy the line number. If a successor block has no line number, and only
7245 * one predecessor, then inherit the line number.
7246 * This ensures that all exit blocks (with one predecessor) receive a line number.
7247 * Also reduces the size of the line number table,
Mark Shannon5977a792020-12-02 13:31:40 +00007248 * but has no impact on the generated line number events.
7249 */
7250static void
Mark Shannon3bd60352021-01-13 12:05:43 +00007251propogate_line_numbers(struct assembler *a) {
Mark Shannon5977a792020-12-02 13:31:40 +00007252 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007253 if (b->b_iused == 0) {
7254 continue;
7255 }
Mark Shannon5977a792020-12-02 13:31:40 +00007256 int prev_lineno = -1;
7257 for (int i = 0; i < b->b_iused; i++) {
7258 if (b->b_instr[i].i_lineno < 0) {
7259 b->b_instr[i].i_lineno = prev_lineno;
7260 }
7261 else {
7262 prev_lineno = b->b_instr[i].i_lineno;
7263 }
7264 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007265 if (!b->b_nofallthrough && b->b_next->b_predecessors == 1) {
7266 assert(b->b_next->b_iused);
7267 if (b->b_next->b_instr[0].i_lineno < 0) {
7268 b->b_next->b_instr[0].i_lineno = prev_lineno;
7269 }
7270 }
7271 if (is_jump(&b->b_instr[b->b_iused-1])) {
7272 switch (b->b_instr[b->b_iused-1].i_opcode) {
7273 /* Note: Only actual jumps, not exception handlers */
7274 case SETUP_ASYNC_WITH:
7275 case SETUP_WITH:
7276 case SETUP_FINALLY:
7277 continue;
7278 }
7279 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7280 if (target->b_predecessors == 1) {
7281 if (target->b_instr[0].i_lineno < 0) {
7282 target->b_instr[0].i_lineno = prev_lineno;
7283 }
7284 }
7285 }
Mark Shannon5977a792020-12-02 13:31:40 +00007286 }
7287}
7288
7289/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01007290 The consts object should still be in list form to allow new constants
7291 to be appended.
7292
7293 All transformations keep the code size the same or smaller.
7294 For those that reduce size, the gaps are initially filled with
7295 NOPs. Later those NOPs are removed.
7296*/
7297
7298static int
7299optimize_cfg(struct assembler *a, PyObject *consts)
7300{
Mark Shannoncc75ab72020-11-12 19:49:33 +00007301 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00007302 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007303 return -1;
7304 }
Mark Shannon1659ad12021-01-13 15:05:04 +00007305 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00007306 assert(b->b_predecessors == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007307 }
7308 if (mark_reachable(a)) {
7309 return -1;
7310 }
7311 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007312 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007313 if (b->b_predecessors == 0) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00007314 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05307315 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007316 }
7317 }
Mark Shannon1659ad12021-01-13 15:05:04 +00007318 basicblock *pred = NULL;
7319 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
7320 int prev_lineno = -1;
7321 if (pred && pred->b_iused) {
7322 prev_lineno = pred->b_instr[pred->b_iused-1].i_lineno;
7323 }
7324 clean_basic_block(b, prev_lineno);
7325 pred = b->b_nofallthrough ? NULL : b;
7326 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007327 eliminate_empty_basic_blocks(a->a_entry);
Om Gc71581c2020-12-16 17:48:05 +05307328 /* Delete jump instructions made redundant by previous step. If a non-empty
7329 block ends with a jump instruction, check if the next non-empty block
7330 reached through normal flow control is the target of that jump. If it
7331 is, then the jump instruction is redundant and can be deleted.
7332 */
Mark Shannon3bd60352021-01-13 12:05:43 +00007333 int maybe_empty_blocks = 0;
Om Gc71581c2020-12-16 17:48:05 +05307334 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
7335 if (b->b_iused > 0) {
7336 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
Mark Shannon802b6452021-02-02 14:59:15 +00007337 if (b_last_instr->i_opcode == JUMP_ABSOLUTE ||
Om Gc71581c2020-12-16 17:48:05 +05307338 b_last_instr->i_opcode == JUMP_FORWARD) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007339 if (b_last_instr->i_target == b->b_next) {
7340 assert(b->b_next->b_iused);
Om Gc71581c2020-12-16 17:48:05 +05307341 b->b_nofallthrough = 0;
Mark Shannon802b6452021-02-02 14:59:15 +00007342 b_last_instr->i_opcode = NOP;
7343 clean_basic_block(b, -1);
7344 maybe_empty_blocks = 1;
Om Gc71581c2020-12-16 17:48:05 +05307345 }
7346 }
7347 }
7348 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007349 if (maybe_empty_blocks) {
7350 eliminate_empty_basic_blocks(a->a_entry);
7351 }
7352 propogate_line_numbers(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007353 return 0;
7354}
7355
Mark Shannon5977a792020-12-02 13:31:40 +00007356static inline int
7357is_exit_without_lineno(basicblock *b) {
7358 return b->b_exit && b->b_instr[0].i_lineno < 0;
7359}
7360
7361/* PEP 626 mandates that the f_lineno of a frame is correct
7362 * after a frame terminates. It would be prohibitively expensive
7363 * to continuously update the f_lineno field at runtime,
7364 * so we make sure that all exiting instruction (raises and returns)
7365 * have a valid line number, allowing us to compute f_lineno lazily.
7366 * We can do this by duplicating the exit blocks without line number
7367 * so that none have more than one predecessor. We can then safely
7368 * copy the line number from the sole predecessor block.
7369 */
7370static int
7371ensure_exits_have_lineno(struct compiler *c)
7372{
Mark Shannoneaccc122020-12-04 15:22:12 +00007373 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00007374 /* Copy all exit blocks without line number that are targets of a jump.
7375 */
7376 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7377 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
7378 switch (b->b_instr[b->b_iused-1].i_opcode) {
7379 /* Note: Only actual jumps, not exception handlers */
7380 case SETUP_ASYNC_WITH:
7381 case SETUP_WITH:
7382 case SETUP_FINALLY:
7383 continue;
7384 }
7385 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7386 if (is_exit_without_lineno(target)) {
7387 basicblock *new_target = compiler_copy_block(c, target);
7388 if (new_target == NULL) {
7389 return -1;
7390 }
7391 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
7392 b->b_instr[b->b_iused-1].i_target = new_target;
7393 }
7394 }
Mark Shannoneaccc122020-12-04 15:22:12 +00007395 entry = b;
7396 }
7397 assert(entry != NULL);
7398 if (is_exit_without_lineno(entry)) {
7399 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00007400 }
Mark Shannonee9f98d2021-01-05 12:04:10 +00007401 /* Eliminate empty blocks */
7402 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7403 while (b->b_next && b->b_next->b_iused == 0) {
7404 b->b_next = b->b_next->b_next;
7405 }
7406 }
Mark Shannon5977a792020-12-02 13:31:40 +00007407 /* Any remaining reachable exit blocks without line number can only be reached by
7408 * fall through, and thus can only have a single predecessor */
7409 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7410 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
7411 if (is_exit_without_lineno(b->b_next)) {
7412 assert(b->b_next->b_iused > 0);
7413 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
7414 }
7415 }
7416 }
7417 return 0;
7418}
7419
7420
Mark Shannon6e8128f2020-07-30 10:03:00 +01007421/* Retained for API compatibility.
7422 * Optimization is now done in optimize_cfg */
7423
7424PyObject *
7425PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
7426 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
7427{
7428 Py_INCREF(code);
7429 return code;
7430}