blob: 65dacc2da64bd634e9a973d42c6c6e8d0a96b45e [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,
119 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000120
121struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 enum fblocktype fb_type;
123 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200124 /* (optional) type-specific exit or cleanup block */
125 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +0000126 /* (optional) additional information required for unwinding */
127 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000128};
129
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100130enum {
131 COMPILER_SCOPE_MODULE,
132 COMPILER_SCOPE_CLASS,
133 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400134 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400135 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100136 COMPILER_SCOPE_COMPREHENSION,
137};
138
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000139/* The following items change on entry and exit of code blocks.
140 They must be saved and restored when returning to a block.
141*/
142struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400146 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100147 int u_scope_type;
148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 /* The following fields are dicts that map objects to
150 the index of them in co_XXX. The index is used as
151 the argument for opcodes that refer to those collections.
152 */
153 PyObject *u_consts; /* all constants */
154 PyObject *u_names; /* all names */
155 PyObject *u_varnames; /* local variables */
156 PyObject *u_cellvars; /* cell variables */
157 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160
Victor Stinnerf8e32212013-11-19 23:56:34 +0100161 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100162 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100163 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 /* Pointer to the most recently allocated block. By following b_list
165 members, you can reach all early allocated blocks. */
166 basicblock *u_blocks;
167 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 int u_nfblocks;
170 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 int u_firstlineno; /* the first lineno of the block */
173 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000174 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000175};
176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000178
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000179The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000181managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000182
183Note that we don't track recursion levels during compilation - the
184task of detecting and rejecting excessive levels of nesting is
185handled by the symbol analysis pass.
186
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187*/
188
189struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200190 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 struct symtable *c_st;
192 PyFutureFeatures *c_future; /* pointer to module's __future__ */
193 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194
Georg Brandl8334fd92010-12-04 10:26:46 +0000195 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 int c_interactive; /* true if in interactive mode */
197 int c_nestlevel;
INADA Naokic2e16072018-11-26 21:23:22 +0900198 PyObject *c_const_cache; /* Python dict holding all constants,
199 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 struct compiler_unit *u; /* compiler state for current block */
201 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
202 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000203};
204
Brandt Bucher145bf262021-02-26 14:51:55 -0800205typedef struct {
206 PyObject *stores;
207 int allow_irrefutable;
208} pattern_context;
209
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100210static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211static void compiler_free(struct compiler *);
212static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500213static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100215static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100216static int compiler_addop_j(struct compiler *, int, basicblock *);
Mark Shannon127dde52021-01-04 18:06:55 +0000217static int compiler_addop_j_noline(struct compiler *, int, basicblock *);
Brandt Bucher145bf262021-02-26 14:51:55 -0800218static int compiler_error(struct compiler *, const char *, ...);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200219static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
221
222static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
223static int compiler_visit_stmt(struct compiler *, stmt_ty);
224static int compiler_visit_keyword(struct compiler *, keyword_ty);
225static int compiler_visit_expr(struct compiler *, expr_ty);
226static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700227static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200228static int compiler_subscript(struct compiler *, expr_ty);
229static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000230
Andy Lester76d58772020-03-10 21:18:12 -0500231static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100232static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Mark Shannon8473cf82020-12-15 11:07:50 +0000233
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000234
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500235static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400236static int compiler_async_with(struct compiler *, stmt_ty, int);
237static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100238static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100239 asdl_expr_seq *args,
240 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500241static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400242static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000243
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700244static int compiler_sync_comprehension_generator(
245 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100246 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200247 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700248 expr_ty elt, expr_ty val, int type);
249
250static int compiler_async_comprehension_generator(
251 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100252 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200253 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700254 expr_ty elt, expr_ty val, int type);
255
Brandt Bucher145bf262021-02-26 14:51:55 -0800256static int compiler_pattern(struct compiler *, expr_ty, pattern_context *);
257static int compiler_match(struct compiler *, stmt_ty);
258static int compiler_pattern_subpattern(struct compiler *, expr_ty,
259 pattern_context *);
260
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000261static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000262static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400264#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000265
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000266PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000267_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 /* Name mangling: __private becomes _classname__private.
270 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200271 PyObject *result;
272 size_t nlen, plen, ipriv;
273 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200275 PyUnicode_READ_CHAR(ident, 0) != '_' ||
276 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 Py_INCREF(ident);
278 return ident;
279 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200280 nlen = PyUnicode_GET_LENGTH(ident);
281 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 The only time a name with a dot can occur is when
285 we are compiling an import statement that has a
286 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 TODO(jhylton): Decide whether we want to support
289 mangling of the module name, e.g. __M.X.
290 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200291 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
292 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
293 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_INCREF(ident);
295 return ident; /* Don't mangle __whatever__ */
296 }
297 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200298 ipriv = 0;
299 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
300 ipriv++;
301 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 Py_INCREF(ident);
303 return ident; /* Don't mangle if class is just underscores */
304 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200305 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000306
Antoine Pitrou55bff892013-04-06 21:21:04 +0200307 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
308 PyErr_SetString(PyExc_OverflowError,
309 "private identifier too large to be mangled");
310 return NULL;
311 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000312
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200313 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
314 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
315 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
316
317 result = PyUnicode_New(1 + nlen + plen, maxchar);
318 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200320 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
321 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200322 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
323 Py_DECREF(result);
324 return NULL;
325 }
326 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
327 Py_DECREF(result);
328 return NULL;
329 }
Victor Stinner8f825062012-04-27 13:55:39 +0200330 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200331 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000332}
333
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000334static int
335compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000338
INADA Naokic2e16072018-11-26 21:23:22 +0900339 c->c_const_cache = PyDict_New();
340 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900342 }
343
344 c->c_stack = PyList_New(0);
345 if (!c->c_stack) {
346 Py_CLEAR(c->c_const_cache);
347 return 0;
348 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351}
352
353PyCodeObject *
Victor Stinnera81fca62021-03-24 00:51:50 +0100354_PyAST_Compile(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
355 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 struct compiler c;
358 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200359 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (!__doc__) {
363 __doc__ = PyUnicode_InternFromString("__doc__");
364 if (!__doc__)
365 return NULL;
366 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000367 if (!__annotations__) {
368 __annotations__ = PyUnicode_InternFromString("__annotations__");
369 if (!__annotations__)
370 return NULL;
371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (!compiler_init(&c))
373 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200374 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 c.c_filename = filename;
376 c.c_arena = arena;
Victor Stinnera81fca62021-03-24 00:51:50 +0100377 c.c_future = _PyFuture_FromAST(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (c.c_future == NULL)
379 goto finally;
380 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 flags = &local_flags;
382 }
383 merged = c.c_future->ff_features | flags->cf_flags;
384 c.c_future->ff_features = merged;
385 flags->cf_flags = merged;
386 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200387 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389
Pablo Galindod112c602020-03-18 23:02:09 +0000390 _PyASTOptimizeState state;
391 state.optimize = c.c_optimize;
392 state.ff_features = merged;
393
394 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900395 goto finally;
396 }
397
Victor Stinner28ad12f2021-03-19 12:41:49 +0100398 c.c_st = _PySymtable_Build(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (c.c_st == NULL) {
400 if (!PyErr_Occurred())
401 PyErr_SetString(PyExc_SystemError, "no symtable");
402 goto finally;
403 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000406
Thomas Wouters1175c432006-02-27 22:49:54 +0000407 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 compiler_free(&c);
409 assert(co || PyErr_Occurred());
410 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000411}
412
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000413static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000414compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (c->c_st)
Victor Stinner28ad12f2021-03-19 12:41:49 +0100417 _PySymtable_Free(c->c_st);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (c->c_future)
419 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200420 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900421 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000423}
424
Guido van Rossum79f25d91997-04-29 20:08:16 +0000425static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000426list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 Py_ssize_t i, n;
429 PyObject *v, *k;
430 PyObject *dict = PyDict_New();
431 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 n = PyList_Size(list);
434 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100435 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (!v) {
437 Py_DECREF(dict);
438 return NULL;
439 }
440 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300441 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 Py_DECREF(v);
443 Py_DECREF(dict);
444 return NULL;
445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 Py_DECREF(v);
447 }
448 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000449}
450
451/* Return new dict containing names from src that match scope(s).
452
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000453src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000455values are integers, starting at offset and increasing by one for
456each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000457*/
458
459static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100460dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700462 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500464 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 assert(offset >= 0);
467 if (dest == NULL)
468 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469
Meador Inge2ca63152012-07-18 14:20:11 -0500470 /* Sort the keys so that we have a deterministic order on the indexes
471 saved in the returned dictionary. These indexes are used as indexes
472 into the free and cell var storage. Therefore if they aren't
473 deterministic, then the generated bytecode is not deterministic.
474 */
475 sorted_keys = PyDict_Keys(src);
476 if (sorted_keys == NULL)
477 return NULL;
478 if (PyList_Sort(sorted_keys) != 0) {
479 Py_DECREF(sorted_keys);
480 return NULL;
481 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500482 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500483
484 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* XXX this should probably be a macro in symtable.h */
486 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500487 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200488 v = PyDict_GetItemWithError(src, k);
489 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 vi = PyLong_AS_LONG(v);
491 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300494 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500496 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 Py_DECREF(dest);
498 return NULL;
499 }
500 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300501 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500502 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 Py_DECREF(item);
504 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 return NULL;
506 }
507 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 }
509 }
Meador Inge2ca63152012-07-18 14:20:11 -0500510 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000512}
513
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000514static void
515compiler_unit_check(struct compiler_unit *u)
516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 basicblock *block;
518 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +0100519 assert(!_PyMem_IsPtrFreed(block));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (block->b_instr != NULL) {
521 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100522 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 assert(block->b_ialloc >= block->b_iused);
524 }
525 else {
526 assert (block->b_iused == 0);
527 assert (block->b_ialloc == 0);
528 }
529 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000530}
531
532static void
533compiler_unit_free(struct compiler_unit *u)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 compiler_unit_check(u);
538 b = u->u_blocks;
539 while (b != NULL) {
540 if (b->b_instr)
541 PyObject_Free((void *)b->b_instr);
542 next = b->b_list;
543 PyObject_Free((void *)b);
544 b = next;
545 }
546 Py_CLEAR(u->u_ste);
547 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400548 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 Py_CLEAR(u->u_consts);
550 Py_CLEAR(u->u_names);
551 Py_CLEAR(u->u_varnames);
552 Py_CLEAR(u->u_freevars);
553 Py_CLEAR(u->u_cellvars);
554 Py_CLEAR(u->u_private);
555 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000556}
557
558static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100559compiler_enter_scope(struct compiler *c, identifier name,
560 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100563 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564
Andy Lester7668a8b2020-03-24 23:26:44 -0500565 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 struct compiler_unit));
567 if (!u) {
568 PyErr_NoMemory();
569 return 0;
570 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100571 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100573 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 u->u_kwonlyargcount = 0;
575 u->u_ste = PySymtable_Lookup(c->c_st, key);
576 if (!u->u_ste) {
577 compiler_unit_free(u);
578 return 0;
579 }
580 Py_INCREF(name);
581 u->u_name = name;
582 u->u_varnames = list2dict(u->u_ste->ste_varnames);
583 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
584 if (!u->u_varnames || !u->u_cellvars) {
585 compiler_unit_free(u);
586 return 0;
587 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500588 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000589 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500590 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300591 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500592 int res;
593 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200594 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500595 name = _PyUnicode_FromId(&PyId___class__);
596 if (!name) {
597 compiler_unit_free(u);
598 return 0;
599 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100600 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500601 if (res < 0) {
602 compiler_unit_free(u);
603 return 0;
604 }
605 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200608 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (!u->u_freevars) {
610 compiler_unit_free(u);
611 return 0;
612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 u->u_blocks = NULL;
615 u->u_nfblocks = 0;
616 u->u_firstlineno = lineno;
617 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000618 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 u->u_consts = PyDict_New();
620 if (!u->u_consts) {
621 compiler_unit_free(u);
622 return 0;
623 }
624 u->u_names = PyDict_New();
625 if (!u->u_names) {
626 compiler_unit_free(u);
627 return 0;
628 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 /* Push the old compiler_unit on the stack. */
633 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400634 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
636 Py_XDECREF(capsule);
637 compiler_unit_free(u);
638 return 0;
639 }
640 Py_DECREF(capsule);
641 u->u_private = c->u->u_private;
642 Py_XINCREF(u->u_private);
643 }
644 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100647
648 block = compiler_new_block(c);
649 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100651 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000652
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400653 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
654 if (!compiler_set_qualname(c))
655 return 0;
656 }
657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000659}
660
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000661static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662compiler_exit_scope(struct compiler *c)
663{
Victor Stinnera6192632021-01-29 16:53:03 +0100664 // Don't call PySequence_DelItem() with an exception raised
665 PyObject *exc_type, *exc_val, *exc_tb;
666 PyErr_Fetch(&exc_type, &exc_val, &exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 c->c_nestlevel--;
669 compiler_unit_free(c->u);
670 /* Restore c->u to the parent unit. */
Victor Stinnera6192632021-01-29 16:53:03 +0100671 Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (n >= 0) {
Victor Stinnera6192632021-01-29 16:53:03 +0100673 PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400674 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 assert(c->u);
676 /* we are deleting from a list so this really shouldn't fail */
Victor Stinnera6192632021-01-29 16:53:03 +0100677 if (PySequence_DelItem(c->c_stack, n) < 0) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +0100678 _PyErr_WriteUnraisableMsg("on removing the last compiler "
679 "stack item", NULL);
Victor Stinnera6192632021-01-29 16:53:03 +0100680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 compiler_unit_check(c->u);
682 }
Victor Stinnera6192632021-01-29 16:53:03 +0100683 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 c->u = NULL;
Victor Stinnera6192632021-01-29 16:53:03 +0100685 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000686
Victor Stinnera6192632021-01-29 16:53:03 +0100687 PyErr_Restore(exc_type, exc_val, exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000688}
689
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690static int
691compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100692{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100693 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 _Py_static_string(dot_locals, ".<locals>");
695 Py_ssize_t stack_size;
696 struct compiler_unit *u = c->u;
697 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100700 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400701 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400702 if (stack_size > 1) {
703 int scope, force_global = 0;
704 struct compiler_unit *parent;
705 PyObject *mangled, *capsule;
706
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400707 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400708 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 assert(parent);
710
Yury Selivanov75445082015-05-11 22:57:16 -0400711 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
712 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
713 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400714 assert(u->u_name);
715 mangled = _Py_Mangle(parent->u_private, u->u_name);
716 if (!mangled)
717 return 0;
Victor Stinner28ad12f2021-03-19 12:41:49 +0100718 scope = _PyST_GetScope(parent->u_ste, mangled);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400719 Py_DECREF(mangled);
720 assert(scope != GLOBAL_IMPLICIT);
721 if (scope == GLOBAL_EXPLICIT)
722 force_global = 1;
723 }
724
725 if (!force_global) {
726 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400727 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400728 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
729 dot_locals_str = _PyUnicode_FromId(&dot_locals);
730 if (dot_locals_str == NULL)
731 return 0;
732 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
733 if (base == NULL)
734 return 0;
735 }
736 else {
737 Py_INCREF(parent->u_qualname);
738 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400739 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100740 }
741 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400742
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400743 if (base != NULL) {
744 dot_str = _PyUnicode_FromId(&dot);
745 if (dot_str == NULL) {
746 Py_DECREF(base);
747 return 0;
748 }
749 name = PyUnicode_Concat(base, dot_str);
750 Py_DECREF(base);
751 if (name == NULL)
752 return 0;
753 PyUnicode_Append(&name, u->u_name);
754 if (name == NULL)
755 return 0;
756 }
757 else {
758 Py_INCREF(u->u_name);
759 name = u->u_name;
760 }
761 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100762
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400763 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100764}
765
Eric V. Smith235a6f02015-09-19 14:51:32 -0400766
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767/* Allocate a new block and return a pointer to it.
768 Returns NULL on error.
769*/
770
771static basicblock *
772compiler_new_block(struct compiler *c)
773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 basicblock *b;
775 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500778 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (b == NULL) {
780 PyErr_NoMemory();
781 return NULL;
782 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* Extend the singly linked list of blocks with new block. */
784 b->b_list = u->u_blocks;
785 u->u_blocks = b;
786 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790compiler_next_block(struct compiler *c)
791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 basicblock *block = compiler_new_block(c);
793 if (block == NULL)
794 return NULL;
795 c->u->u_curblock->b_next = block;
796 c->u->u_curblock = block;
797 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000798}
799
800static basicblock *
801compiler_use_next_block(struct compiler *c, basicblock *block)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 assert(block != NULL);
804 c->u->u_curblock->b_next = block;
805 c->u->u_curblock = block;
806 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000807}
808
Mark Shannon5977a792020-12-02 13:31:40 +0000809static basicblock *
810compiler_copy_block(struct compiler *c, basicblock *block)
811{
812 /* Cannot copy a block if it has a fallthrough, since
813 * a block can only have one fallthrough predecessor.
814 */
815 assert(block->b_nofallthrough);
816 basicblock *result = compiler_next_block(c);
817 if (result == NULL) {
818 return NULL;
819 }
820 for (int i = 0; i < block->b_iused; i++) {
821 int n = compiler_next_instr(result);
822 if (n < 0) {
823 return NULL;
824 }
825 result->b_instr[n] = block->b_instr[i];
826 }
827 result->b_exit = block->b_exit;
Mark Shannon3bd60352021-01-13 12:05:43 +0000828 result->b_nofallthrough = 1;
Mark Shannon5977a792020-12-02 13:31:40 +0000829 return result;
830}
831
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000832/* Returns the offset of the next instruction in the current block's
833 b_instr array. Resizes the b_instr as necessary.
834 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000835*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000836
837static int
Andy Lester76d58772020-03-10 21:18:12 -0500838compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 assert(b != NULL);
841 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500842 b->b_instr = (struct instr *)PyObject_Calloc(
843 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (b->b_instr == NULL) {
845 PyErr_NoMemory();
846 return -1;
847 }
848 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 }
850 else if (b->b_iused == b->b_ialloc) {
851 struct instr *tmp;
852 size_t oldsize, newsize;
853 oldsize = b->b_ialloc * sizeof(struct instr);
854 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000855
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700856 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyErr_NoMemory();
858 return -1;
859 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (newsize == 0) {
862 PyErr_NoMemory();
863 return -1;
864 }
865 b->b_ialloc <<= 1;
866 tmp = (struct instr *)PyObject_Realloc(
867 (void *)b->b_instr, newsize);
868 if (tmp == NULL) {
869 PyErr_NoMemory();
870 return -1;
871 }
872 b->b_instr = tmp;
873 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
874 }
875 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000876}
877
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200878/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000879
Christian Heimes2202f872008-02-06 14:31:34 +0000880 The line number is reset in the following cases:
881 - when entering a new scope
882 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200883 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200884 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000885*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000886
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200887#define SET_LOC(c, x) \
888 (c)->u->u_lineno = (x)->lineno; \
889 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000890
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200891/* Return the stack effect of opcode with argument oparg.
892
893 Some opcodes have different stack effect when jump to the target and
894 when not jump. The 'jump' parameter specifies the case:
895
896 * 0 -- when not jump
897 * 1 -- when jump
898 * -1 -- maximal
899 */
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200900static int
901stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300904 case NOP:
905 case EXTENDED_ARG:
906 return 0;
907
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200908 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 case POP_TOP:
910 return -1;
911 case ROT_TWO:
912 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200913 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 return 0;
915 case DUP_TOP:
916 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000917 case DUP_TOP_TWO:
918 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000919
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200920 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 case UNARY_POSITIVE:
922 case UNARY_NEGATIVE:
923 case UNARY_NOT:
924 case UNARY_INVERT:
925 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 case SET_ADD:
928 case LIST_APPEND:
929 return -1;
930 case MAP_ADD:
931 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000932
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200933 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case BINARY_POWER:
935 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400936 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 case BINARY_MODULO:
938 case BINARY_ADD:
939 case BINARY_SUBTRACT:
940 case BINARY_SUBSCR:
941 case BINARY_FLOOR_DIVIDE:
942 case BINARY_TRUE_DIVIDE:
943 return -1;
944 case INPLACE_FLOOR_DIVIDE:
945 case INPLACE_TRUE_DIVIDE:
946 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 case INPLACE_ADD:
949 case INPLACE_SUBTRACT:
950 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400951 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 case INPLACE_MODULO:
953 return -1;
954 case STORE_SUBSCR:
955 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 case DELETE_SUBSCR:
957 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 case BINARY_LSHIFT:
960 case BINARY_RSHIFT:
961 case BINARY_AND:
962 case BINARY_XOR:
963 case BINARY_OR:
964 return -1;
965 case INPLACE_POWER:
966 return -1;
967 case GET_ITER:
968 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 case PRINT_EXPR:
971 return -1;
972 case LOAD_BUILD_CLASS:
973 return 1;
974 case INPLACE_LSHIFT:
975 case INPLACE_RSHIFT:
976 case INPLACE_AND:
977 case INPLACE_XOR:
978 case INPLACE_OR:
979 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200982 /* 1 in the normal flow.
983 * Restore the stack position and push 6 values before jumping to
984 * the handler if an exception be raised. */
985 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 case RETURN_VALUE:
987 return -1;
988 case IMPORT_STAR:
989 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700990 case SETUP_ANNOTATIONS:
991 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 case YIELD_VALUE:
993 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500994 case YIELD_FROM:
995 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 case POP_BLOCK:
997 return 0;
998 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200999 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case STORE_NAME:
1002 return -1;
1003 case DELETE_NAME:
1004 return 0;
1005 case UNPACK_SEQUENCE:
1006 return oparg-1;
1007 case UNPACK_EX:
1008 return (oparg&0xFF) + (oparg>>8);
1009 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001010 /* -1 at end of iterator, 1 if continue iterating. */
1011 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 case STORE_ATTR:
1014 return -2;
1015 case DELETE_ATTR:
1016 return -1;
1017 case STORE_GLOBAL:
1018 return -1;
1019 case DELETE_GLOBAL:
1020 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 case LOAD_CONST:
1022 return 1;
1023 case LOAD_NAME:
1024 return 1;
1025 case BUILD_TUPLE:
1026 case BUILD_LIST:
1027 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001028 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 return 1-oparg;
1030 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001031 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001032 case BUILD_CONST_KEY_MAP:
1033 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case LOAD_ATTR:
1035 return 0;
1036 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001037 case IS_OP:
1038 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001040 case JUMP_IF_NOT_EXC_MATCH:
1041 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 case IMPORT_NAME:
1043 return -1;
1044 case IMPORT_FROM:
1045 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001046
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001047 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case JUMP_ABSOLUTE:
1050 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001052 case JUMP_IF_TRUE_OR_POP:
1053 case JUMP_IF_FALSE_OR_POP:
1054 return jump ? 0 : -1;
1055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 case POP_JUMP_IF_FALSE:
1057 case POP_JUMP_IF_TRUE:
1058 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case LOAD_GLOBAL:
1061 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001062
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001063 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001065 /* 0 in the normal flow.
1066 * Restore the stack position and push 6 values before jumping to
1067 * the handler if an exception be raised. */
1068 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001069 case RERAISE:
1070 return -3;
1071
1072 case WITH_EXCEPT_START:
1073 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case LOAD_FAST:
1076 return 1;
1077 case STORE_FAST:
1078 return -1;
1079 case DELETE_FAST:
1080 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 case RAISE_VARARGS:
1083 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001084
1085 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001087 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001088 case CALL_METHOD:
1089 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001091 return -oparg-1;
1092 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001093 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001094 case MAKE_FUNCTION:
1095 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1096 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 case BUILD_SLICE:
1098 if (oparg == 3)
1099 return -2;
1100 else
1101 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001102
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001103 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 case LOAD_CLOSURE:
1105 return 1;
1106 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001107 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 return 1;
1109 case STORE_DEREF:
1110 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001111 case DELETE_DEREF:
1112 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001113
1114 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001115 case GET_AWAITABLE:
1116 return 0;
1117 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001118 /* 0 in the normal flow.
1119 * Restore the stack position to the position before the result
1120 * of __aenter__ and push 6 values before jumping to the handler
1121 * if an exception be raised. */
1122 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001123 case BEFORE_ASYNC_WITH:
1124 return 1;
1125 case GET_AITER:
1126 return 0;
1127 case GET_ANEXT:
1128 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001129 case GET_YIELD_FROM_ITER:
1130 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001131 case END_ASYNC_FOR:
1132 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001133 case FORMAT_VALUE:
1134 /* If there's a fmt_spec on the stack, we go from 2->1,
1135 else 1->1. */
1136 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001137 case LOAD_METHOD:
1138 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001139 case LOAD_ASSERTION_ERROR:
1140 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001141 case LIST_TO_TUPLE:
1142 return 0;
Mark Shannonb37181e2021-04-06 11:48:59 +01001143 case GEN_START:
1144 return -1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001145 case LIST_EXTEND:
1146 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001147 case DICT_MERGE:
1148 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001149 return -1;
Brandt Bucher145bf262021-02-26 14:51:55 -08001150 case COPY_DICT_WITHOUT_KEYS:
1151 return 0;
1152 case MATCH_CLASS:
1153 return -1;
1154 case GET_LEN:
1155 case MATCH_MAPPING:
1156 case MATCH_SEQUENCE:
1157 return 1;
1158 case MATCH_KEYS:
1159 return 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001161 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 }
Larry Hastings3a907972013-11-23 14:49:22 -08001163 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001164}
1165
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001166int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001167PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1168{
1169 return stack_effect(opcode, oparg, jump);
1170}
1171
1172int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001173PyCompile_OpcodeStackEffect(int opcode, int oparg)
1174{
1175 return stack_effect(opcode, oparg, -1);
1176}
1177
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001178/* Add an opcode with no argument.
1179 Returns 0 on failure, 1 on success.
1180*/
1181
1182static int
Mark Shannon3bd60352021-01-13 12:05:43 +00001183compiler_addop_line(struct compiler *c, int opcode, int line)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 basicblock *b;
1186 struct instr *i;
1187 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001188 assert(!HAS_ARG(opcode));
Andy Lester76d58772020-03-10 21:18:12 -05001189 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 if (off < 0)
1191 return 0;
1192 b = c->u->u_curblock;
1193 i = &b->b_instr[off];
1194 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001195 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (opcode == RETURN_VALUE)
1197 b->b_return = 1;
Mark Shannon3bd60352021-01-13 12:05:43 +00001198 i->i_lineno = line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001200}
1201
Mark Shannon3bd60352021-01-13 12:05:43 +00001202static int
1203compiler_addop(struct compiler *c, int opcode)
1204{
1205 return compiler_addop_line(c, opcode, c->u->u_lineno);
1206}
1207
1208static int
1209compiler_addop_noline(struct compiler *c, int opcode)
1210{
1211 return compiler_addop_line(c, opcode, -1);
1212}
1213
1214
Victor Stinnerf8e32212013-11-19 23:56:34 +01001215static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001216compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001217{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001218 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001220
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001221 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001223 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001225 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001226 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001227 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 return -1;
1230 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001231 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 Py_DECREF(v);
1233 return -1;
1234 }
1235 Py_DECREF(v);
1236 }
1237 else
1238 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001239 return arg;
1240}
1241
INADA Naokic2e16072018-11-26 21:23:22 +09001242// Merge const *o* recursively and return constant key object.
1243static PyObject*
1244merge_consts_recursive(struct compiler *c, PyObject *o)
1245{
1246 // None and Ellipsis are singleton, and key is the singleton.
1247 // No need to merge object and key.
1248 if (o == Py_None || o == Py_Ellipsis) {
1249 Py_INCREF(o);
1250 return o;
1251 }
1252
1253 PyObject *key = _PyCode_ConstantKey(o);
1254 if (key == NULL) {
1255 return NULL;
1256 }
1257
1258 // t is borrowed reference
1259 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1260 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001261 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001262 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001263 Py_DECREF(key);
1264 return t;
1265 }
1266
INADA Naokif7e4d362018-11-29 00:58:46 +09001267 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001268 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001269 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001270 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001271 Py_ssize_t len = PyTuple_GET_SIZE(o);
1272 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001273 PyObject *item = PyTuple_GET_ITEM(o, i);
1274 PyObject *u = merge_consts_recursive(c, item);
1275 if (u == NULL) {
1276 Py_DECREF(key);
1277 return NULL;
1278 }
1279
1280 // See _PyCode_ConstantKey()
1281 PyObject *v; // borrowed
1282 if (PyTuple_CheckExact(u)) {
1283 v = PyTuple_GET_ITEM(u, 1);
1284 }
1285 else {
1286 v = u;
1287 }
1288 if (v != item) {
1289 Py_INCREF(v);
1290 PyTuple_SET_ITEM(o, i, v);
1291 Py_DECREF(item);
1292 }
1293
1294 Py_DECREF(u);
1295 }
1296 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001297 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001298 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001299 // constant keys.
1300 // See _PyCode_ConstantKey() for detail.
1301 assert(PyTuple_CheckExact(key));
1302 assert(PyTuple_GET_SIZE(key) == 2);
1303
1304 Py_ssize_t len = PySet_GET_SIZE(o);
1305 if (len == 0) { // empty frozenset should not be re-created.
1306 return key;
1307 }
1308 PyObject *tuple = PyTuple_New(len);
1309 if (tuple == NULL) {
1310 Py_DECREF(key);
1311 return NULL;
1312 }
1313 Py_ssize_t i = 0, pos = 0;
1314 PyObject *item;
1315 Py_hash_t hash;
1316 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1317 PyObject *k = merge_consts_recursive(c, item);
1318 if (k == NULL) {
1319 Py_DECREF(tuple);
1320 Py_DECREF(key);
1321 return NULL;
1322 }
1323 PyObject *u;
1324 if (PyTuple_CheckExact(k)) {
1325 u = PyTuple_GET_ITEM(k, 1);
1326 Py_INCREF(u);
1327 Py_DECREF(k);
1328 }
1329 else {
1330 u = k;
1331 }
1332 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1333 i++;
1334 }
1335
1336 // Instead of rewriting o, we create new frozenset and embed in the
1337 // key tuple. Caller should get merged frozenset from the key tuple.
1338 PyObject *new = PyFrozenSet_New(tuple);
1339 Py_DECREF(tuple);
1340 if (new == NULL) {
1341 Py_DECREF(key);
1342 return NULL;
1343 }
1344 assert(PyTuple_GET_ITEM(key, 1) == o);
1345 Py_DECREF(o);
1346 PyTuple_SET_ITEM(key, 1, new);
1347 }
INADA Naokic2e16072018-11-26 21:23:22 +09001348
1349 return key;
1350}
1351
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001352static Py_ssize_t
1353compiler_add_const(struct compiler *c, PyObject *o)
1354{
INADA Naokic2e16072018-11-26 21:23:22 +09001355 PyObject *key = merge_consts_recursive(c, o);
1356 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001357 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001358 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001359
Andy Lester76d58772020-03-10 21:18:12 -05001360 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001361 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363}
1364
1365static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001366compiler_addop_load_const(struct compiler *c, PyObject *o)
1367{
1368 Py_ssize_t arg = compiler_add_const(c, o);
1369 if (arg < 0)
1370 return 0;
1371 return compiler_addop_i(c, LOAD_CONST, arg);
1372}
1373
1374static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001375compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001377{
Andy Lester76d58772020-03-10 21:18:12 -05001378 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001380 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001381 return compiler_addop_i(c, opcode, arg);
1382}
1383
1384static int
1385compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001388 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001389
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1391 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001392 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001393 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001394 Py_DECREF(mangled);
1395 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001396 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001397 return compiler_addop_i(c, opcode, arg);
1398}
1399
1400/* Add an opcode with an integer argument.
1401 Returns 0 on failure, 1 on success.
1402*/
1403
1404static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001405compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 struct instr *i;
1408 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001409
Victor Stinner2ad474b2016-03-01 23:34:47 +01001410 /* oparg value is unsigned, but a signed C int is usually used to store
1411 it in the C code (like Python/ceval.c).
1412
1413 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1414
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001415 The argument of a concrete bytecode instruction is limited to 8-bit.
1416 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1417 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001418 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001419
Andy Lester76d58772020-03-10 21:18:12 -05001420 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (off < 0)
1422 return 0;
1423 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001424 i->i_opcode = opcode;
1425 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001426 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428}
1429
Mark Shannon28b75c82020-12-23 11:43:10 +00001430static int add_jump_to_block(basicblock *b, int opcode, int lineno, basicblock *target)
1431{
1432 assert(HAS_ARG(opcode));
1433 assert(b != NULL);
1434 assert(target != NULL);
1435
1436 int off = compiler_next_instr(b);
1437 struct instr *i = &b->b_instr[off];
1438 if (off < 0) {
1439 return 0;
1440 }
1441 i->i_opcode = opcode;
1442 i->i_target = target;
1443 i->i_lineno = lineno;
1444 return 1;
1445}
1446
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001448compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449{
Mark Shannon28b75c82020-12-23 11:43:10 +00001450 return add_jump_to_block(c->u->u_curblock, opcode, c->u->u_lineno, b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001451}
1452
Mark Shannon127dde52021-01-04 18:06:55 +00001453static int
1454compiler_addop_j_noline(struct compiler *c, int opcode, basicblock *b)
1455{
1456 return add_jump_to_block(c->u->u_curblock, opcode, -1, b);
1457}
1458
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001459/* NEXT_BLOCK() creates an implicit jump from the current block
1460 to the new block.
1461
1462 The returns inside this macro make it impossible to decref objects
1463 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001465#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (compiler_next_block((C)) == NULL) \
1467 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001468}
1469
1470#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 if (!compiler_addop((C), (OP))) \
1472 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473}
1474
Mark Shannon3bd60352021-01-13 12:05:43 +00001475#define ADDOP_NOLINE(C, OP) { \
1476 if (!compiler_addop_noline((C), (OP))) \
1477 return 0; \
1478}
1479
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001480#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (!compiler_addop((C), (OP))) { \
1482 compiler_exit_scope(c); \
1483 return 0; \
1484 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001485}
1486
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001487#define ADDOP_LOAD_CONST(C, O) { \
1488 if (!compiler_addop_load_const((C), (O))) \
1489 return 0; \
1490}
1491
1492/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1493#define ADDOP_LOAD_CONST_NEW(C, O) { \
1494 PyObject *__new_const = (O); \
1495 if (__new_const == NULL) { \
1496 return 0; \
1497 } \
1498 if (!compiler_addop_load_const((C), __new_const)) { \
1499 Py_DECREF(__new_const); \
1500 return 0; \
1501 } \
1502 Py_DECREF(__new_const); \
1503}
1504
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1507 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508}
1509
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001510/* Same as ADDOP_O, but steals a reference. */
1511#define ADDOP_N(C, OP, O, TYPE) { \
1512 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1513 Py_DECREF((O)); \
1514 return 0; \
1515 } \
1516 Py_DECREF((O)); \
1517}
1518
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1521 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522}
1523
1524#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (!compiler_addop_i((C), (OP), (O))) \
1526 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001527}
1528
Mark Shannon582aaf12020-08-04 17:30:11 +01001529#define ADDOP_JUMP(C, OP, O) { \
1530 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532}
1533
Mark Shannon127dde52021-01-04 18:06:55 +00001534/* Add a jump with no line number.
1535 * Used for artificial jumps that have no corresponding
1536 * token in the source code. */
1537#define ADDOP_JUMP_NOLINE(C, OP, O) { \
1538 if (!compiler_addop_j_noline((C), (OP), (O))) \
1539 return 0; \
1540}
1541
Mark Shannon9af0e472020-01-14 10:12:45 +00001542#define ADDOP_COMPARE(C, CMP) { \
1543 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1544 return 0; \
1545}
1546
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1548 the ASDL name to synthesize the name of the C type and the visit function.
1549*/
1550
1551#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 if (!compiler_visit_ ## TYPE((C), (V))) \
1553 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001554}
1555
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001556#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 if (!compiler_visit_ ## TYPE((C), (V))) { \
1558 compiler_exit_scope(c); \
1559 return 0; \
1560 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001561}
1562
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001563#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 if (!compiler_visit_slice((C), (V), (CTX))) \
1565 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001566}
1567
1568#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001570 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1572 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1573 if (!compiler_visit_ ## TYPE((C), elt)) \
1574 return 0; \
1575 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001576}
1577
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001578#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001580 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1582 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1583 if (!compiler_visit_ ## TYPE((C), elt)) { \
1584 compiler_exit_scope(c); \
1585 return 0; \
1586 } \
1587 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001588}
1589
Brandt Bucher145bf262021-02-26 14:51:55 -08001590#define RETURN_IF_FALSE(X) \
1591 if (!(X)) { \
1592 return 0; \
1593 }
1594
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001595/* Search if variable annotations are present statically in a block. */
1596
1597static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001598find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001599{
1600 int i, j, res = 0;
1601 stmt_ty st;
1602
1603 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1604 st = (stmt_ty)asdl_seq_GET(stmts, i);
1605 switch (st->kind) {
1606 case AnnAssign_kind:
1607 return 1;
1608 case For_kind:
1609 res = find_ann(st->v.For.body) ||
1610 find_ann(st->v.For.orelse);
1611 break;
1612 case AsyncFor_kind:
1613 res = find_ann(st->v.AsyncFor.body) ||
1614 find_ann(st->v.AsyncFor.orelse);
1615 break;
1616 case While_kind:
1617 res = find_ann(st->v.While.body) ||
1618 find_ann(st->v.While.orelse);
1619 break;
1620 case If_kind:
1621 res = find_ann(st->v.If.body) ||
1622 find_ann(st->v.If.orelse);
1623 break;
1624 case With_kind:
1625 res = find_ann(st->v.With.body);
1626 break;
1627 case AsyncWith_kind:
1628 res = find_ann(st->v.AsyncWith.body);
1629 break;
1630 case Try_kind:
1631 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1632 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1633 st->v.Try.handlers, j);
1634 if (find_ann(handler->v.ExceptHandler.body)) {
1635 return 1;
1636 }
1637 }
1638 res = find_ann(st->v.Try.body) ||
1639 find_ann(st->v.Try.finalbody) ||
1640 find_ann(st->v.Try.orelse);
1641 break;
1642 default:
1643 res = 0;
1644 }
1645 if (res) {
1646 break;
1647 }
1648 }
1649 return res;
1650}
1651
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001652/*
1653 * Frame block handling functions
1654 */
1655
1656static int
1657compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001658 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001659{
1660 struct fblockinfo *f;
1661 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001662 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001663 }
1664 f = &c->u->u_fblock[c->u->u_nfblocks++];
1665 f->fb_type = t;
1666 f->fb_block = b;
1667 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001668 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001669 return 1;
1670}
1671
1672static void
1673compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1674{
1675 struct compiler_unit *u = c->u;
1676 assert(u->u_nfblocks > 0);
1677 u->u_nfblocks--;
1678 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1679 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1680}
1681
Mark Shannonfee55262019-11-21 09:11:43 +00001682static int
1683compiler_call_exit_with_nones(struct compiler *c) {
1684 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1685 ADDOP(c, DUP_TOP);
1686 ADDOP(c, DUP_TOP);
1687 ADDOP_I(c, CALL_FUNCTION, 3);
1688 return 1;
1689}
1690
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001691/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001692 * popping the blocks will be restored afterwards, unless another
1693 * return, break or continue is found. In which case, the TOS will
1694 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001695 */
1696static int
1697compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1698 int preserve_tos)
1699{
1700 switch (info->fb_type) {
1701 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001702 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001703 return 1;
1704
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001705 case FOR_LOOP:
1706 /* Pop the iterator */
1707 if (preserve_tos) {
1708 ADDOP(c, ROT_TWO);
1709 }
1710 ADDOP(c, POP_TOP);
1711 return 1;
1712
Mark Shannon02d126a2020-09-25 14:04:19 +01001713 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001714 ADDOP(c, POP_BLOCK);
1715 return 1;
1716
1717 case FINALLY_TRY:
Mark Shannon5274b682020-12-16 13:07:01 +00001718 /* This POP_BLOCK gets the line number of the unwinding statement */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001719 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001720 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001721 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1722 return 0;
1723 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001724 }
Mark Shannon5274b682020-12-16 13:07:01 +00001725 /* Emit the finally block */
Mark Shannonfee55262019-11-21 09:11:43 +00001726 VISIT_SEQ(c, stmt, info->fb_datum);
1727 if (preserve_tos) {
1728 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001729 }
Mark Shannon5274b682020-12-16 13:07:01 +00001730 /* The finally block should appear to execute after the
1731 * statement causing the unwinding, so make the unwinding
1732 * instruction artificial */
1733 c->u->u_lineno = -1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001734 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001735
Mark Shannonfee55262019-11-21 09:11:43 +00001736 case FINALLY_END:
1737 if (preserve_tos) {
1738 ADDOP(c, ROT_FOUR);
1739 }
1740 ADDOP(c, POP_TOP);
1741 ADDOP(c, POP_TOP);
1742 ADDOP(c, POP_TOP);
1743 if (preserve_tos) {
1744 ADDOP(c, ROT_FOUR);
1745 }
1746 ADDOP(c, POP_EXCEPT);
1747 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001748
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001749 case WITH:
1750 case ASYNC_WITH:
1751 ADDOP(c, POP_BLOCK);
1752 if (preserve_tos) {
1753 ADDOP(c, ROT_TWO);
1754 }
Mark Shannonfee55262019-11-21 09:11:43 +00001755 if(!compiler_call_exit_with_nones(c)) {
1756 return 0;
1757 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001758 if (info->fb_type == ASYNC_WITH) {
1759 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001760 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001761 ADDOP(c, YIELD_FROM);
1762 }
Mark Shannonfee55262019-11-21 09:11:43 +00001763 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001764 return 1;
1765
1766 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001767 if (info->fb_datum) {
1768 ADDOP(c, POP_BLOCK);
1769 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001770 if (preserve_tos) {
1771 ADDOP(c, ROT_FOUR);
1772 }
Mark Shannonfee55262019-11-21 09:11:43 +00001773 ADDOP(c, POP_EXCEPT);
1774 if (info->fb_datum) {
1775 ADDOP_LOAD_CONST(c, Py_None);
1776 compiler_nameop(c, info->fb_datum, Store);
1777 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001778 }
Mark Shannonfee55262019-11-21 09:11:43 +00001779 return 1;
1780
1781 case POP_VALUE:
1782 if (preserve_tos) {
1783 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001784 }
Mark Shannonfee55262019-11-21 09:11:43 +00001785 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001786 return 1;
1787 }
1788 Py_UNREACHABLE();
1789}
1790
Mark Shannonfee55262019-11-21 09:11:43 +00001791/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1792static int
1793compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1794 if (c->u->u_nfblocks == 0) {
1795 return 1;
1796 }
1797 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1798 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1799 *loop = top;
1800 return 1;
1801 }
1802 struct fblockinfo copy = *top;
1803 c->u->u_nfblocks--;
1804 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1805 return 0;
1806 }
1807 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1808 return 0;
1809 }
1810 c->u->u_fblock[c->u->u_nfblocks] = copy;
1811 c->u->u_nfblocks++;
1812 return 1;
1813}
1814
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001815/* Compile a sequence of statements, checking for a docstring
1816 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817
1818static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001819compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001821 int i = 0;
1822 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001823 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001824
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001825 /* Set current line number to the line number of first statement.
1826 This way line number for SETUP_ANNOTATIONS will always
1827 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301828 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001829 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001830 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001831 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001832 }
1833 /* Every annotated class and module should have __annotations__. */
1834 if (find_ann(stmts)) {
1835 ADDOP(c, SETUP_ANNOTATIONS);
1836 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001837 if (!asdl_seq_LEN(stmts))
1838 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001839 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001840 if (c->c_optimize < 2) {
1841 docstring = _PyAST_GetDocString(stmts);
1842 if (docstring) {
1843 i = 1;
1844 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1845 assert(st->kind == Expr_kind);
1846 VISIT(c, expr, st->v.Expr.value);
1847 if (!compiler_nameop(c, __doc__, Store))
1848 return 0;
1849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001851 for (; i < asdl_seq_LEN(stmts); i++)
1852 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854}
1855
1856static PyCodeObject *
1857compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 PyCodeObject *co;
1860 int addNone = 1;
1861 static PyObject *module;
1862 if (!module) {
1863 module = PyUnicode_InternFromString("<module>");
1864 if (!module)
1865 return NULL;
1866 }
1867 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001868 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 return NULL;
1870 switch (mod->kind) {
1871 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001872 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 compiler_exit_scope(c);
1874 return 0;
1875 }
1876 break;
1877 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001878 if (find_ann(mod->v.Interactive.body)) {
1879 ADDOP(c, SETUP_ANNOTATIONS);
1880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001882 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 break;
1884 case Expression_kind:
1885 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1886 addNone = 0;
1887 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 default:
1889 PyErr_Format(PyExc_SystemError,
1890 "module kind %d should not be possible",
1891 mod->kind);
1892 return 0;
1893 }
1894 co = assemble(c, addNone);
1895 compiler_exit_scope(c);
1896 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001897}
1898
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899/* The test for LOCAL must come before the test for FREE in order to
1900 handle classes where name is both local and free. The local var is
1901 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001902*/
1903
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904static int
1905get_ref_type(struct compiler *c, PyObject *name)
1906{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001907 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001908 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001909 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001910 return CELL;
Victor Stinner28ad12f2021-03-19 12:41:49 +01001911 scope = _PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 if (scope == 0) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001913 PyErr_Format(PyExc_SystemError,
Victor Stinner28ad12f2021-03-19 12:41:49 +01001914 "_PyST_GetScope(name=%R) failed: "
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001915 "unknown scope in unit %S (%R); "
1916 "symbols: %R; locals: %R; globals: %R",
1917 name,
1918 c->u->u_name, c->u->u_ste->ste_id,
1919 c->u->u_ste->ste_symbols, c->u->u_varnames, c->u->u_names);
1920 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923}
1924
1925static int
1926compiler_lookup_arg(PyObject *dict, PyObject *name)
1927{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001928 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001929 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001930 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001931 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001932 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933}
1934
1935static int
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001936compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags,
1937 PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001939 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001940 if (qualname == NULL)
1941 qualname = co->co_name;
1942
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001943 if (free) {
1944 for (i = 0; i < free; ++i) {
1945 /* Bypass com_addop_varname because it will generate
1946 LOAD_DEREF but LOAD_CLOSURE is needed.
1947 */
1948 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001950 /* Special case: If a class contains a method with a
1951 free variable that has the same name as a method,
1952 the name will be considered free *and* local in the
1953 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001954 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001955 */
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001956 int reftype = get_ref_type(c, name);
1957 if (reftype == -1) {
1958 return 0;
1959 }
1960 int arg;
1961 if (reftype == CELL) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001962 arg = compiler_lookup_arg(c->u->u_cellvars, name);
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001963 }
1964 else {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001965 arg = compiler_lookup_arg(c->u->u_freevars, name);
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001966 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001967 if (arg == -1) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001968 PyErr_Format(PyExc_SystemError,
1969 "compiler_lookup_arg(name=%R) with reftype=%d failed in %S; "
1970 "freevars of code %S: %R",
1971 name,
1972 reftype,
1973 c->u->u_name,
1974 co->co_name,
1975 co->co_freevars);
1976 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001977 }
1978 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001980 flags |= 0x08;
1981 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001983 ADDOP_LOAD_CONST(c, (PyObject*)co);
1984 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001985 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987}
1988
1989static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001990compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 if (!decos)
1995 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1998 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1999 }
2000 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002001}
2002
2003static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002004compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
2005 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00002006{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002007 /* Push a dict of keyword-only default values.
2008
2009 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
2010 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 int i;
2012 PyObject *keys = NULL;
2013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
2015 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
2016 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
2017 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04002018 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002019 if (!mangled) {
2020 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002022 if (keys == NULL) {
2023 keys = PyList_New(1);
2024 if (keys == NULL) {
2025 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002026 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002027 }
2028 PyList_SET_ITEM(keys, 0, mangled);
2029 }
2030 else {
2031 int res = PyList_Append(keys, mangled);
2032 Py_DECREF(mangled);
2033 if (res == -1) {
2034 goto error;
2035 }
2036 }
2037 if (!compiler_visit_expr(c, default_)) {
2038 goto error;
2039 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 }
2041 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002042 if (keys != NULL) {
2043 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2044 PyObject *keys_tuple = PyList_AsTuple(keys);
2045 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002046 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002047 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002048 assert(default_count > 0);
2049 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002050 }
2051 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002052 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002053 }
2054
2055error:
2056 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002057 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002058}
2059
2060static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002061compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2062{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002063 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002064 return 1;
2065}
2066
2067static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002068compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002069 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002072 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002073 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002074 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002075
2076 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002077 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002078 VISIT(c, annexpr, annotation);
2079 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002081 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002082}
2083
2084static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002085compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002086 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002087{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002088 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 for (i = 0; i < asdl_seq_LEN(args); i++) {
2090 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002091 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 c,
2093 arg->arg,
2094 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002095 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002096 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002098 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002099}
2100
2101static int
2102compiler_visit_annotations(struct compiler *c, arguments_ty args,
2103 expr_ty returns)
2104{
Yurii Karabas73019792020-11-25 12:43:18 +02002105 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002106 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002107
Yurii Karabas73019792020-11-25 12:43:18 +02002108 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 */
2110 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002111 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002112
Yurii Karabas73019792020-11-25 12:43:18 +02002113 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2114 return 0;
2115 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2116 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002117 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002118 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002119 args->vararg->annotation, &annotations_len))
2120 return 0;
2121 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2122 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002123 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002124 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002125 args->kwarg->annotation, &annotations_len))
2126 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (!return_str) {
2129 return_str = PyUnicode_InternFromString("return");
2130 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002131 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 }
Yurii Karabas73019792020-11-25 12:43:18 +02002133 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2134 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 }
2136
Yurii Karabas73019792020-11-25 12:43:18 +02002137 if (annotations_len) {
2138 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002139 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002141
Yurii Karabas73019792020-11-25 12:43:18 +02002142 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002143}
2144
2145static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002146compiler_visit_defaults(struct compiler *c, arguments_ty args)
2147{
2148 VISIT_SEQ(c, expr, args->defaults);
2149 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2150 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002151}
2152
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002153static Py_ssize_t
2154compiler_default_arguments(struct compiler *c, arguments_ty args)
2155{
2156 Py_ssize_t funcflags = 0;
2157 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002158 if (!compiler_visit_defaults(c, args))
2159 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002160 funcflags |= 0x01;
2161 }
2162 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002163 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002164 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002165 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002166 return -1;
2167 }
2168 else if (res > 0) {
2169 funcflags |= 0x02;
2170 }
2171 }
2172 return funcflags;
2173}
2174
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002176forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2177{
2178
2179 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2180 compiler_error(c, "cannot assign to __debug__");
2181 return 1;
2182 }
2183 return 0;
2184}
2185
2186static int
2187compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2188{
2189 if (arg != NULL) {
2190 if (forbidden_name(c, arg->arg, Store))
2191 return 0;
2192 }
2193 return 1;
2194}
2195
2196static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002197compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002198{
2199 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002200 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002201 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2202 return 0;
2203 }
2204 }
2205 return 1;
2206}
2207
2208static int
2209compiler_check_debug_args(struct compiler *c, arguments_ty args)
2210{
2211 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2212 return 0;
2213 if (!compiler_check_debug_args_seq(c, args->args))
2214 return 0;
2215 if (!compiler_check_debug_one_arg(c, args->vararg))
2216 return 0;
2217 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2218 return 0;
2219 if (!compiler_check_debug_one_arg(c, args->kwarg))
2220 return 0;
2221 return 1;
2222}
2223
2224static int
Yury Selivanov75445082015-05-11 22:57:16 -04002225compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002228 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002229 arguments_ty args;
2230 expr_ty returns;
2231 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002232 asdl_expr_seq* decos;
2233 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002234 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002235 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002236 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002237 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002238
Yury Selivanov75445082015-05-11 22:57:16 -04002239 if (is_async) {
2240 assert(s->kind == AsyncFunctionDef_kind);
2241
2242 args = s->v.AsyncFunctionDef.args;
2243 returns = s->v.AsyncFunctionDef.returns;
2244 decos = s->v.AsyncFunctionDef.decorator_list;
2245 name = s->v.AsyncFunctionDef.name;
2246 body = s->v.AsyncFunctionDef.body;
2247
2248 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2249 } else {
2250 assert(s->kind == FunctionDef_kind);
2251
2252 args = s->v.FunctionDef.args;
2253 returns = s->v.FunctionDef.returns;
2254 decos = s->v.FunctionDef.decorator_list;
2255 name = s->v.FunctionDef.name;
2256 body = s->v.FunctionDef.body;
2257
2258 scope_type = COMPILER_SCOPE_FUNCTION;
2259 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002261 if (!compiler_check_debug_args(c, args))
2262 return 0;
2263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (!compiler_decorators(c, decos))
2265 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002266
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002267 firstlineno = s->lineno;
2268 if (asdl_seq_LEN(decos)) {
2269 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2270 }
2271
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002272 funcflags = compiler_default_arguments(c, args);
2273 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002275 }
2276
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002277 annotations = compiler_visit_annotations(c, args, returns);
2278 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002279 return 0;
2280 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002281 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002282 funcflags |= 0x04;
2283 }
2284
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002285 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002286 return 0;
2287 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288
INADA Naokicb41b272017-02-23 00:31:59 +09002289 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002290 if (c->c_optimize < 2) {
2291 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002292 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002293 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 compiler_exit_scope(c);
2295 return 0;
2296 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002299 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002301 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002302 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002303 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002305 qualname = c->u->u_qualname;
2306 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002308 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002309 Py_XDECREF(qualname);
2310 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002312 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002313
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002314 if (!compiler_make_closure(c, co, funcflags, qualname)) {
2315 Py_DECREF(qualname);
2316 Py_DECREF(co);
2317 return 0;
2318 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002319 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 /* decorators */
2323 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2324 ADDOP_I(c, CALL_FUNCTION, 1);
2325 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002326
Yury Selivanov75445082015-05-11 22:57:16 -04002327 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002328}
2329
2330static int
2331compiler_class(struct compiler *c, stmt_ty s)
2332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 PyCodeObject *co;
2334 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002335 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002336 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 if (!compiler_decorators(c, decos))
2339 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002340
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002341 firstlineno = s->lineno;
2342 if (asdl_seq_LEN(decos)) {
2343 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2344 }
2345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* ultimately generate code for:
2347 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2348 where:
2349 <func> is a function/closure created from the class body;
2350 it has a single argument (__locals__) where the dict
2351 (or MutableSequence) representing the locals is passed
2352 <name> is the class name
2353 <bases> is the positional arguments and *varargs argument
2354 <keywords> is the keyword arguments and **kwds argument
2355 This borrows from compiler_call.
2356 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002359 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002360 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 return 0;
2362 /* this block represents what we do in the new scope */
2363 {
2364 /* use the class name for name mangling */
2365 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002366 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* load (global) __name__ ... */
2368 str = PyUnicode_InternFromString("__name__");
2369 if (!str || !compiler_nameop(c, str, Load)) {
2370 Py_XDECREF(str);
2371 compiler_exit_scope(c);
2372 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002373 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 Py_DECREF(str);
2375 /* ... and store it as __module__ */
2376 str = PyUnicode_InternFromString("__module__");
2377 if (!str || !compiler_nameop(c, str, Store)) {
2378 Py_XDECREF(str);
2379 compiler_exit_scope(c);
2380 return 0;
2381 }
2382 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002383 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002384 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002385 str = PyUnicode_InternFromString("__qualname__");
2386 if (!str || !compiler_nameop(c, str, Store)) {
2387 Py_XDECREF(str);
2388 compiler_exit_scope(c);
2389 return 0;
2390 }
2391 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002393 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 compiler_exit_scope(c);
2395 return 0;
2396 }
Mark Shannone56d54e2021-01-15 13:52:00 +00002397 /* The following code is artificial */
2398 c->u->u_lineno = -1;
Nick Coghlan19d24672016-12-05 16:47:55 +10002399 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002400 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002401 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002402 str = PyUnicode_InternFromString("__class__");
2403 if (str == NULL) {
2404 compiler_exit_scope(c);
2405 return 0;
2406 }
2407 i = compiler_lookup_arg(c->u->u_cellvars, str);
2408 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002409 if (i < 0) {
2410 compiler_exit_scope(c);
2411 return 0;
2412 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002413 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002416 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002417 str = PyUnicode_InternFromString("__classcell__");
2418 if (!str || !compiler_nameop(c, str, Store)) {
2419 Py_XDECREF(str);
2420 compiler_exit_scope(c);
2421 return 0;
2422 }
2423 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002425 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002426 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002427 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002428 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002429 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002430 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 /* create the code object */
2432 co = assemble(c, 1);
2433 }
2434 /* leave the new scope */
2435 compiler_exit_scope(c);
2436 if (co == NULL)
2437 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 /* 2. load the 'build_class' function */
2440 ADDOP(c, LOAD_BUILD_CLASS);
2441
2442 /* 3. load a function (or closure) made from the code object */
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002443 if (!compiler_make_closure(c, co, 0, NULL)) {
2444 Py_DECREF(co);
2445 return 0;
2446 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 Py_DECREF(co);
2448
2449 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002450 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451
2452 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002453 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 return 0;
2455
2456 /* 6. apply decorators */
2457 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2458 ADDOP_I(c, CALL_FUNCTION, 1);
2459 }
2460
2461 /* 7. store into <name> */
2462 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2463 return 0;
2464 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002465}
2466
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002467/* Return 0 if the expression is a constant value except named singletons.
2468 Return 1 otherwise. */
2469static int
2470check_is_arg(expr_ty e)
2471{
2472 if (e->kind != Constant_kind) {
2473 return 1;
2474 }
2475 PyObject *value = e->v.Constant.value;
2476 return (value == Py_None
2477 || value == Py_False
2478 || value == Py_True
2479 || value == Py_Ellipsis);
2480}
2481
2482/* Check operands of identity chacks ("is" and "is not").
2483 Emit a warning if any operand is a constant except named singletons.
2484 Return 0 on error.
2485 */
2486static int
2487check_compare(struct compiler *c, expr_ty e)
2488{
2489 Py_ssize_t i, n;
2490 int left = check_is_arg(e->v.Compare.left);
2491 n = asdl_seq_LEN(e->v.Compare.ops);
2492 for (i = 0; i < n; i++) {
2493 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2494 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2495 if (op == Is || op == IsNot) {
2496 if (!right || !left) {
2497 const char *msg = (op == Is)
2498 ? "\"is\" with a literal. Did you mean \"==\"?"
2499 : "\"is not\" with a literal. Did you mean \"!=\"?";
2500 return compiler_warn(c, msg);
2501 }
2502 }
2503 left = right;
2504 }
2505 return 1;
2506}
2507
Mark Shannon9af0e472020-01-14 10:12:45 +00002508static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002509{
Mark Shannon9af0e472020-01-14 10:12:45 +00002510 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002511 switch (op) {
2512 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002513 cmp = Py_EQ;
2514 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002515 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002516 cmp = Py_NE;
2517 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002518 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002519 cmp = Py_LT;
2520 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002521 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002522 cmp = Py_LE;
2523 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002524 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002525 cmp = Py_GT;
2526 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002527 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002528 cmp = Py_GE;
2529 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002530 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002531 ADDOP_I(c, IS_OP, 0);
2532 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002533 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002534 ADDOP_I(c, IS_OP, 1);
2535 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002536 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002537 ADDOP_I(c, CONTAINS_OP, 0);
2538 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002539 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002540 ADDOP_I(c, CONTAINS_OP, 1);
2541 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002542 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002543 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002544 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002545 ADDOP_I(c, COMPARE_OP, cmp);
2546 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002547}
2548
Mark Shannon9af0e472020-01-14 10:12:45 +00002549
2550
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002551static int
2552compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2553{
2554 switch (e->kind) {
2555 case UnaryOp_kind:
2556 if (e->v.UnaryOp.op == Not)
2557 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2558 /* fallback to general implementation */
2559 break;
2560 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002561 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002562 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2563 assert(n >= 0);
2564 int cond2 = e->v.BoolOp.op == Or;
2565 basicblock *next2 = next;
2566 if (!cond2 != !cond) {
2567 next2 = compiler_new_block(c);
2568 if (next2 == NULL)
2569 return 0;
2570 }
2571 for (i = 0; i < n; ++i) {
2572 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2573 return 0;
2574 }
2575 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2576 return 0;
2577 if (next2 != next)
2578 compiler_use_next_block(c, next2);
2579 return 1;
2580 }
2581 case IfExp_kind: {
2582 basicblock *end, *next2;
2583 end = compiler_new_block(c);
2584 if (end == NULL)
2585 return 0;
2586 next2 = compiler_new_block(c);
2587 if (next2 == NULL)
2588 return 0;
2589 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2590 return 0;
2591 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2592 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002593 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002594 compiler_use_next_block(c, next2);
2595 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2596 return 0;
2597 compiler_use_next_block(c, end);
2598 return 1;
2599 }
2600 case Compare_kind: {
2601 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2602 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002603 if (!check_compare(c, e)) {
2604 return 0;
2605 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002606 basicblock *cleanup = compiler_new_block(c);
2607 if (cleanup == NULL)
2608 return 0;
2609 VISIT(c, expr, e->v.Compare.left);
2610 for (i = 0; i < n; i++) {
2611 VISIT(c, expr,
2612 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2613 ADDOP(c, DUP_TOP);
2614 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002615 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002616 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002617 NEXT_BLOCK(c);
2618 }
2619 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002620 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002621 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002622 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002623 basicblock *end = compiler_new_block(c);
2624 if (end == NULL)
2625 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002626 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002627 compiler_use_next_block(c, cleanup);
2628 ADDOP(c, POP_TOP);
2629 if (!cond) {
Mark Shannon127dde52021-01-04 18:06:55 +00002630 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002631 }
2632 compiler_use_next_block(c, end);
2633 return 1;
2634 }
2635 /* fallback to general implementation */
2636 break;
2637 }
2638 default:
2639 /* fallback to general implementation */
2640 break;
2641 }
2642
2643 /* general implementation */
2644 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002645 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002646 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002647 return 1;
2648}
2649
2650static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002651compiler_ifexp(struct compiler *c, expr_ty e)
2652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 basicblock *end, *next;
2654
2655 assert(e->kind == IfExp_kind);
2656 end = compiler_new_block(c);
2657 if (end == NULL)
2658 return 0;
2659 next = compiler_new_block(c);
2660 if (next == NULL)
2661 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002662 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2663 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon127dde52021-01-04 18:06:55 +00002665 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 compiler_use_next_block(c, next);
2667 VISIT(c, expr, e->v.IfExp.orelse);
2668 compiler_use_next_block(c, end);
2669 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002670}
2671
2672static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673compiler_lambda(struct compiler *c, expr_ty e)
2674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002676 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002678 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 arguments_ty args = e->v.Lambda.args;
2680 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002681
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002682 if (!compiler_check_debug_args(c, args))
2683 return 0;
2684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 if (!name) {
2686 name = PyUnicode_InternFromString("<lambda>");
2687 if (!name)
2688 return 0;
2689 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002690
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002691 funcflags = compiler_default_arguments(c, args);
2692 if (funcflags == -1) {
2693 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002695
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002696 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002697 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 /* Make None the first constant, so the lambda can't have a
2701 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002702 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002706 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2708 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2709 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002710 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 }
2712 else {
2713 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002714 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002716 qualname = c->u->u_qualname;
2717 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 compiler_exit_scope(c);
Pablo Galindo7fdab832021-01-29 22:40:59 +00002719 if (co == NULL) {
2720 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 return 0;
Pablo Galindo7fdab832021-01-29 22:40:59 +00002722 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002723
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002724 if (!compiler_make_closure(c, co, funcflags, qualname)) {
2725 Py_DECREF(qualname);
2726 Py_DECREF(co);
2727 return 0;
2728 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002729 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 Py_DECREF(co);
2731
2732 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002733}
2734
2735static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736compiler_if(struct compiler *c, stmt_ty s)
2737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 assert(s->kind == If_kind);
2740 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002741 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002743 }
2744 if (asdl_seq_LEN(s->v.If.orelse)) {
2745 next = compiler_new_block(c);
2746 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002747 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002748 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002749 }
2750 else {
2751 next = end;
2752 }
2753 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2754 return 0;
2755 }
2756 VISIT_SEQ(c, stmt, s->v.If.body);
2757 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon127dde52021-01-04 18:06:55 +00002758 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Mark Shannon8473cf82020-12-15 11:07:50 +00002759 compiler_use_next_block(c, next);
2760 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 }
2762 compiler_use_next_block(c, end);
2763 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002764}
2765
2766static int
2767compiler_for(struct compiler *c, stmt_ty s)
2768{
Mark Shannon5977a792020-12-02 13:31:40 +00002769 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002772 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 cleanup = compiler_new_block(c);
2774 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002775 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002777 }
2778 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002780 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 VISIT(c, expr, s->v.For.iter);
2782 ADDOP(c, GET_ITER);
2783 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002784 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002785 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 VISIT(c, expr, s->v.For.target);
2787 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002788 /* Mark jump as artificial */
2789 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002790 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002792
2793 compiler_pop_fblock(c, FOR_LOOP, start);
2794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 VISIT_SEQ(c, stmt, s->v.For.orelse);
2796 compiler_use_next_block(c, end);
2797 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002798}
2799
Yury Selivanov75445082015-05-11 22:57:16 -04002800
2801static int
2802compiler_async_for(struct compiler *c, stmt_ty s)
2803{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002804 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002805 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002806 c->u->u_ste->ste_coroutine = 1;
2807 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002808 return compiler_error(c, "'async for' outside async function");
2809 }
2810
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002811 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002812 except = compiler_new_block(c);
2813 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002814
Mark Shannonfee55262019-11-21 09:11:43 +00002815 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002816 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002817 }
Yury Selivanov75445082015-05-11 22:57:16 -04002818 VISIT(c, expr, s->v.AsyncFor.iter);
2819 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002820
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002821 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002822 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002823 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002824 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002825 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002826 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002827 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002828 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002829 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002830 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002831
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002832 /* Success block for __anext__ */
2833 VISIT(c, expr, s->v.AsyncFor.target);
2834 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002835 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002836
2837 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002838
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002839 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002840 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002841
2842 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002843 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002844
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002845 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002846 VISIT_SEQ(c, stmt, s->v.For.orelse);
2847
2848 compiler_use_next_block(c, end);
2849
2850 return 1;
2851}
2852
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002853static int
2854compiler_while(struct compiler *c, stmt_ty s)
2855{
Mark Shannon266b4622020-11-17 19:30:14 +00002856 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002858 body = compiler_new_block(c);
2859 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002861 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002865 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002868 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2869 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002870 }
2871
2872 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002874 SET_LOC(c, s);
2875 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2876 return 0;
2877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879 compiler_pop_fblock(c, WHILE_LOOP, loop);
2880
Mark Shannon266b4622020-11-17 19:30:14 +00002881 compiler_use_next_block(c, anchor);
2882 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002884 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888}
2889
2890static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002891compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002892{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002893 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002894 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002895 if (c->u->u_ste->ste_type != FunctionBlock)
2896 return compiler_error(c, "'return' outside function");
2897 if (s->v.Return.value != NULL &&
2898 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2899 {
2900 return compiler_error(
2901 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002903 if (preserve_tos) {
2904 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002905 } else {
2906 /* Emit instruction with line number for expression */
2907 if (s->v.Return.value != NULL) {
2908 SET_LOC(c, s->v.Return.value);
2909 ADDOP(c, NOP);
2910 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002911 }
Mark Shannonfee55262019-11-21 09:11:43 +00002912 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2913 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002914 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002915 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002916 }
2917 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00002918 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002919 }
2920 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002921 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924}
2925
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002926static int
2927compiler_break(struct compiler *c)
2928{
Mark Shannonfee55262019-11-21 09:11:43 +00002929 struct fblockinfo *loop = NULL;
2930 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2931 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002932 }
Mark Shannonfee55262019-11-21 09:11:43 +00002933 if (loop == NULL) {
2934 return compiler_error(c, "'break' outside loop");
2935 }
2936 if (!compiler_unwind_fblock(c, loop, 0)) {
2937 return 0;
2938 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002939 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002940 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002941 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002942}
2943
2944static int
2945compiler_continue(struct compiler *c)
2946{
Mark Shannonfee55262019-11-21 09:11:43 +00002947 struct fblockinfo *loop = NULL;
2948 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2949 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002950 }
Mark Shannonfee55262019-11-21 09:11:43 +00002951 if (loop == NULL) {
2952 return compiler_error(c, "'continue' not properly in loop");
2953 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002954 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002955 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002956 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002957}
2958
2959
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002960/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002961
2962 SETUP_FINALLY L
2963 <code for body>
2964 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002965 <code for finalbody>
2966 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002967 L:
2968 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002969 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 The special instructions use the block stack. Each block
2972 stack entry contains the instruction that created it (here
2973 SETUP_FINALLY), the level of the value stack at the time the
2974 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002976 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 Pushes the current value stack level and the label
2978 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002979 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002980 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002983 when a SETUP_FINALLY entry is found, the raised and the caught
2984 exceptions are pushed onto the value stack (and the exception
2985 condition is cleared), and the interpreter jumps to the label
2986 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987*/
2988
2989static int
2990compiler_try_finally(struct compiler *c, stmt_ty s)
2991{
Mark Shannonfee55262019-11-21 09:11:43 +00002992 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 body = compiler_new_block(c);
2995 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002996 exit = compiler_new_block(c);
2997 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003000 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01003001 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003003 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003005 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
3006 if (!compiler_try_except(c, s))
3007 return 0;
3008 }
3009 else {
3010 VISIT_SEQ(c, stmt, s->v.Try.body);
3011 }
Mark Shannon3bd60352021-01-13 12:05:43 +00003012 ADDOP_NOLINE(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00003013 compiler_pop_fblock(c, FINALLY_TRY, body);
3014 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon127dde52021-01-04 18:06:55 +00003015 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00003016 /* `finally` block */
3017 compiler_use_next_block(c, end);
3018 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
3019 return 0;
3020 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3021 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00003022 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00003023 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003024 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025}
3026
3027/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003028 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 (The contents of the value stack is shown in [], with the top
3030 at the right; 'tb' is trace-back info, 'val' the exception's
3031 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032
3033 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003034 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003035 [] <code for S>
3036 [] POP_BLOCK
3037 [] JUMP_FORWARD L0
3038
3039 [tb, val, exc] L1: DUP )
3040 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003041 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 [tb, val, exc] POP
3043 [tb, val] <assign to V1> (or POP if no V1)
3044 [tb] POP
3045 [] <code for S1>
3046 JUMP_FORWARD L0
3047
3048 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003049 .............................etc.......................
3050
Mark Shannonfee55262019-11-21 09:11:43 +00003051 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052
3053 [] L0: <next statement>
3054
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003055 Of course, parts are not generated if Vi or Ei is not present.
3056*/
3057static int
3058compiler_try_except(struct compiler *c, stmt_ty s)
3059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003061 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003063 body = compiler_new_block(c);
3064 except = compiler_new_block(c);
3065 orelse = compiler_new_block(c);
3066 end = compiler_new_block(c);
3067 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3068 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003069 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003071 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003073 VISIT_SEQ(c, stmt, s->v.Try.body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003074 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon3bd60352021-01-13 12:05:43 +00003075 ADDOP_NOLINE(c, POP_BLOCK);
3076 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003077 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003079 /* Runtime will push a block here, so we need to account for that */
3080 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3081 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082 for (i = 0; i < n; i++) {
3083 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003084 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003085 if (!handler->v.ExceptHandler.type && i < n-1)
3086 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003087 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088 except = compiler_new_block(c);
3089 if (except == NULL)
3090 return 0;
3091 if (handler->v.ExceptHandler.type) {
3092 ADDOP(c, DUP_TOP);
3093 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003094 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003095 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 }
3097 ADDOP(c, POP_TOP);
3098 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003099 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003100
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 cleanup_end = compiler_new_block(c);
3102 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003103 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003104 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003105 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003106
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003107 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3108 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003110 /*
3111 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003112 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003113 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003114 try:
3115 # body
3116 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003117 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003118 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003121 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003122 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003123 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003124 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003125 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003127 /* second # body */
3128 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003129 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003130 ADDOP(c, POP_BLOCK);
3131 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003132 /* name = None; del name; # Mark as artificial */
3133 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003134 ADDOP_LOAD_CONST(c, Py_None);
3135 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3136 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003137 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138
Mark Shannonfee55262019-11-21 09:11:43 +00003139 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003140 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141
Mark Shannon877df852020-11-12 09:43:29 +00003142 /* name = None; del name; # Mark as artificial */
3143 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003144 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003145 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003146 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147
Mark Shannonbf353f32020-12-17 13:55:28 +00003148 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003149 }
3150 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003151 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003153 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003154 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003155 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156
Guido van Rossumb940e112007-01-10 16:19:56 +00003157 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003158 ADDOP(c, POP_TOP);
3159 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003160 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003161 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003163 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannon127dde52021-01-04 18:06:55 +00003164 /* name = None; del name; # Mark as artificial */
3165 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003166 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003167 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 compiler_use_next_block(c, except);
3170 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003171 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003172 /* Mark as artificial */
3173 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003174 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003175 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003176 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 compiler_use_next_block(c, end);
3178 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179}
3180
3181static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003182compiler_try(struct compiler *c, stmt_ty s) {
3183 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3184 return compiler_try_finally(c, s);
3185 else
3186 return compiler_try_except(c, s);
3187}
3188
3189
3190static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003191compiler_import_as(struct compiler *c, identifier name, identifier asname)
3192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 /* The IMPORT_NAME opcode was already generated. This function
3194 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003197 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003199 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3200 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003201 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003202 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003203 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003205 while (1) {
3206 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003208 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003209 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003210 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003211 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003213 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003214 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003215 if (dot == -1) {
3216 break;
3217 }
3218 ADDOP(c, ROT_TWO);
3219 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003221 if (!compiler_nameop(c, asname, Store)) {
3222 return 0;
3223 }
3224 ADDOP(c, POP_TOP);
3225 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 }
3227 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003228}
3229
3230static int
3231compiler_import(struct compiler *c, stmt_ty s)
3232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 /* The Import node stores a module name like a.b.c as a single
3234 string. This is convenient for all cases except
3235 import a.b.c as d
3236 where we need to parse that string to extract the individual
3237 module names.
3238 XXX Perhaps change the representation to make this case simpler?
3239 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003240 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003241
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003242 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 for (i = 0; i < n; i++) {
3244 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3245 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003246
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003247 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003248 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 if (alias->asname) {
3252 r = compiler_import_as(c, alias->name, alias->asname);
3253 if (!r)
3254 return r;
3255 }
3256 else {
3257 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003258 Py_ssize_t dot = PyUnicode_FindChar(
3259 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003260 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003261 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003262 if (tmp == NULL)
3263 return 0;
3264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003266 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 Py_DECREF(tmp);
3268 }
3269 if (!r)
3270 return r;
3271 }
3272 }
3273 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274}
3275
3276static int
3277compiler_from_import(struct compiler *c, stmt_ty s)
3278{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003279 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003280 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 if (!empty_string) {
3284 empty_string = PyUnicode_FromString("");
3285 if (!empty_string)
3286 return 0;
3287 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003289 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003290
3291 names = PyTuple_New(n);
3292 if (!names)
3293 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 /* build up the names */
3296 for (i = 0; i < n; i++) {
3297 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3298 Py_INCREF(alias->name);
3299 PyTuple_SET_ITEM(names, i, alias->name);
3300 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003303 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 Py_DECREF(names);
3305 return compiler_error(c, "from __future__ imports must occur "
3306 "at the beginning of the file");
3307 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003308 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 if (s->v.ImportFrom.module) {
3311 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3312 }
3313 else {
3314 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3315 }
3316 for (i = 0; i < n; i++) {
3317 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3318 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003319
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003320 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 assert(n == 1);
3322 ADDOP(c, IMPORT_STAR);
3323 return 1;
3324 }
3325
3326 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3327 store_name = alias->name;
3328 if (alias->asname)
3329 store_name = alias->asname;
3330
3331 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 return 0;
3333 }
3334 }
3335 /* remove imported module */
3336 ADDOP(c, POP_TOP);
3337 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338}
3339
3340static int
3341compiler_assert(struct compiler *c, stmt_ty s)
3342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003344
tsukasa-aua8ef4572021-03-16 22:14:41 +11003345 /* Always emit a warning if the test is a non-zero length tuple */
3346 if ((s->v.Assert.test->kind == Tuple_kind &&
3347 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) ||
3348 (s->v.Assert.test->kind == Constant_kind &&
3349 PyTuple_Check(s->v.Assert.test->v.Constant.value) &&
3350 PyTuple_Size(s->v.Assert.test->v.Constant.value) > 0))
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003351 {
3352 if (!compiler_warn(c, "assertion is always true, "
3353 "perhaps remove parentheses?"))
3354 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003355 return 0;
3356 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003357 }
tsukasa-aua8ef4572021-03-16 22:14:41 +11003358 if (c->c_optimize)
3359 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 end = compiler_new_block(c);
3361 if (end == NULL)
3362 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003363 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3364 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003365 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 if (s->v.Assert.msg) {
3367 VISIT(c, expr, s->v.Assert.msg);
3368 ADDOP_I(c, CALL_FUNCTION, 1);
3369 }
3370 ADDOP_I(c, RAISE_VARARGS, 1);
3371 compiler_use_next_block(c, end);
3372 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003373}
3374
3375static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003376compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3377{
3378 if (c->c_interactive && c->c_nestlevel <= 1) {
3379 VISIT(c, expr, value);
3380 ADDOP(c, PRINT_EXPR);
3381 return 1;
3382 }
3383
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003384 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003385 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003386 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003387 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003388 }
3389
3390 VISIT(c, expr, value);
Mark Shannonc5440932021-03-15 14:24:25 +00003391 /* Mark POP_TOP as artificial */
3392 c->u->u_lineno = -1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003393 ADDOP(c, POP_TOP);
3394 return 1;
3395}
3396
3397static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003398compiler_visit_stmt(struct compiler *c, stmt_ty s)
3399{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003400 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003403 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 switch (s->kind) {
3406 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003407 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 case ClassDef_kind:
3409 return compiler_class(c, s);
3410 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003411 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003412 case Delete_kind:
3413 VISIT_SEQ(c, expr, s->v.Delete.targets)
3414 break;
3415 case Assign_kind:
3416 n = asdl_seq_LEN(s->v.Assign.targets);
3417 VISIT(c, expr, s->v.Assign.value);
3418 for (i = 0; i < n; i++) {
3419 if (i < n - 1)
3420 ADDOP(c, DUP_TOP);
3421 VISIT(c, expr,
3422 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3423 }
3424 break;
3425 case AugAssign_kind:
3426 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003427 case AnnAssign_kind:
3428 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 case For_kind:
3430 return compiler_for(c, s);
3431 case While_kind:
3432 return compiler_while(c, s);
3433 case If_kind:
3434 return compiler_if(c, s);
Brandt Bucher145bf262021-02-26 14:51:55 -08003435 case Match_kind:
3436 return compiler_match(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003437 case Raise_kind:
3438 n = 0;
3439 if (s->v.Raise.exc) {
3440 VISIT(c, expr, s->v.Raise.exc);
3441 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003442 if (s->v.Raise.cause) {
3443 VISIT(c, expr, s->v.Raise.cause);
3444 n++;
3445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003447 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003448 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003450 case Try_kind:
3451 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003452 case Assert_kind:
3453 return compiler_assert(c, s);
3454 case Import_kind:
3455 return compiler_import(c, s);
3456 case ImportFrom_kind:
3457 return compiler_from_import(c, s);
3458 case Global_kind:
3459 case Nonlocal_kind:
3460 break;
3461 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003462 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003464 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003465 break;
3466 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003467 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003468 case Continue_kind:
3469 return compiler_continue(c);
3470 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003471 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003472 case AsyncFunctionDef_kind:
3473 return compiler_function(c, s, 1);
3474 case AsyncWith_kind:
3475 return compiler_async_with(c, s, 0);
3476 case AsyncFor_kind:
3477 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003478 }
Yury Selivanov75445082015-05-11 22:57:16 -04003479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003480 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481}
3482
3483static int
3484unaryop(unaryop_ty op)
3485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 switch (op) {
3487 case Invert:
3488 return UNARY_INVERT;
3489 case Not:
3490 return UNARY_NOT;
3491 case UAdd:
3492 return UNARY_POSITIVE;
3493 case USub:
3494 return UNARY_NEGATIVE;
3495 default:
3496 PyErr_Format(PyExc_SystemError,
3497 "unary op %d should not be possible", op);
3498 return 0;
3499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003500}
3501
3502static int
Andy Lester76d58772020-03-10 21:18:12 -05003503binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003505 switch (op) {
3506 case Add:
3507 return BINARY_ADD;
3508 case Sub:
3509 return BINARY_SUBTRACT;
3510 case Mult:
3511 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003512 case MatMult:
3513 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003514 case Div:
3515 return BINARY_TRUE_DIVIDE;
3516 case Mod:
3517 return BINARY_MODULO;
3518 case Pow:
3519 return BINARY_POWER;
3520 case LShift:
3521 return BINARY_LSHIFT;
3522 case RShift:
3523 return BINARY_RSHIFT;
3524 case BitOr:
3525 return BINARY_OR;
3526 case BitXor:
3527 return BINARY_XOR;
3528 case BitAnd:
3529 return BINARY_AND;
3530 case FloorDiv:
3531 return BINARY_FLOOR_DIVIDE;
3532 default:
3533 PyErr_Format(PyExc_SystemError,
3534 "binary op %d should not be possible", op);
3535 return 0;
3536 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537}
3538
3539static int
Andy Lester76d58772020-03-10 21:18:12 -05003540inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003542 switch (op) {
3543 case Add:
3544 return INPLACE_ADD;
3545 case Sub:
3546 return INPLACE_SUBTRACT;
3547 case Mult:
3548 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003549 case MatMult:
3550 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003551 case Div:
3552 return INPLACE_TRUE_DIVIDE;
3553 case Mod:
3554 return INPLACE_MODULO;
3555 case Pow:
3556 return INPLACE_POWER;
3557 case LShift:
3558 return INPLACE_LSHIFT;
3559 case RShift:
3560 return INPLACE_RSHIFT;
3561 case BitOr:
3562 return INPLACE_OR;
3563 case BitXor:
3564 return INPLACE_XOR;
3565 case BitAnd:
3566 return INPLACE_AND;
3567 case FloorDiv:
3568 return INPLACE_FLOOR_DIVIDE;
3569 default:
3570 PyErr_Format(PyExc_SystemError,
3571 "inplace binary op %d should not be possible", op);
3572 return 0;
3573 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003574}
3575
3576static int
3577compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3578{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003579 int op, scope;
3580 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 PyObject *dict = c->u->u_names;
3584 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003586 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3587 !_PyUnicode_EqualToASCIIString(name, "True") &&
3588 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003589
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003590 if (forbidden_name(c, name, ctx))
3591 return 0;
3592
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003593 mangled = _Py_Mangle(c->u->u_private, name);
3594 if (!mangled)
3595 return 0;
3596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 op = 0;
3598 optype = OP_NAME;
Victor Stinner28ad12f2021-03-19 12:41:49 +01003599 scope = _PyST_GetScope(c->u->u_ste, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 switch (scope) {
3601 case FREE:
3602 dict = c->u->u_freevars;
3603 optype = OP_DEREF;
3604 break;
3605 case CELL:
3606 dict = c->u->u_cellvars;
3607 optype = OP_DEREF;
3608 break;
3609 case LOCAL:
3610 if (c->u->u_ste->ste_type == FunctionBlock)
3611 optype = OP_FAST;
3612 break;
3613 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003614 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 optype = OP_GLOBAL;
3616 break;
3617 case GLOBAL_EXPLICIT:
3618 optype = OP_GLOBAL;
3619 break;
3620 default:
3621 /* scope can be 0 */
3622 break;
3623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003626 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 switch (optype) {
3629 case OP_DEREF:
3630 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003631 case Load:
3632 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3633 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003634 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003635 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 }
3637 break;
3638 case OP_FAST:
3639 switch (ctx) {
3640 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003641 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003644 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 return 1;
3646 case OP_GLOBAL:
3647 switch (ctx) {
3648 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003649 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 }
3652 break;
3653 case OP_NAME:
3654 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003655 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003656 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003657 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 }
3659 break;
3660 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003662 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003663 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 Py_DECREF(mangled);
3665 if (arg < 0)
3666 return 0;
3667 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003668}
3669
3670static int
3671compiler_boolop(struct compiler *c, expr_ty e)
3672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003673 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003674 int jumpi;
3675 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003676 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 assert(e->kind == BoolOp_kind);
3679 if (e->v.BoolOp.op == And)
3680 jumpi = JUMP_IF_FALSE_OR_POP;
3681 else
3682 jumpi = JUMP_IF_TRUE_OR_POP;
3683 end = compiler_new_block(c);
3684 if (end == NULL)
3685 return 0;
3686 s = e->v.BoolOp.values;
3687 n = asdl_seq_LEN(s) - 1;
3688 assert(n >= 0);
3689 for (i = 0; i < n; ++i) {
3690 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003691 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003692 basicblock *next = compiler_new_block(c);
3693 if (next == NULL) {
3694 return 0;
3695 }
3696 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003697 }
3698 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3699 compiler_use_next_block(c, end);
3700 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003701}
3702
3703static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003704starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003705 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003706{
3707 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003708 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003709 if (n > 2 && are_all_items_const(elts, 0, n)) {
3710 PyObject *folded = PyTuple_New(n);
3711 if (folded == NULL) {
3712 return 0;
3713 }
3714 PyObject *val;
3715 for (i = 0; i < n; i++) {
3716 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3717 Py_INCREF(val);
3718 PyTuple_SET_ITEM(folded, i, val);
3719 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003720 if (tuple) {
3721 ADDOP_LOAD_CONST_NEW(c, folded);
3722 } else {
3723 if (add == SET_ADD) {
3724 Py_SETREF(folded, PyFrozenSet_New(folded));
3725 if (folded == NULL) {
3726 return 0;
3727 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003728 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003729 ADDOP_I(c, build, pushed);
3730 ADDOP_LOAD_CONST_NEW(c, folded);
3731 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003732 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003733 return 1;
3734 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003735
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003736 for (i = 0; i < n; i++) {
3737 expr_ty elt = asdl_seq_GET(elts, i);
3738 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003739 seen_star = 1;
3740 }
3741 }
3742 if (seen_star) {
3743 seen_star = 0;
3744 for (i = 0; i < n; i++) {
3745 expr_ty elt = asdl_seq_GET(elts, i);
3746 if (elt->kind == Starred_kind) {
3747 if (seen_star == 0) {
3748 ADDOP_I(c, build, i+pushed);
3749 seen_star = 1;
3750 }
3751 VISIT(c, expr, elt->v.Starred.value);
3752 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003754 else {
3755 VISIT(c, expr, elt);
3756 if (seen_star) {
3757 ADDOP_I(c, add, 1);
3758 }
3759 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003760 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003761 assert(seen_star);
3762 if (tuple) {
3763 ADDOP(c, LIST_TO_TUPLE);
3764 }
3765 }
3766 else {
3767 for (i = 0; i < n; i++) {
3768 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003769 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003770 }
3771 if (tuple) {
3772 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3773 } else {
3774 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003775 }
3776 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003777 return 1;
3778}
3779
3780static int
Brandt Bucher145bf262021-02-26 14:51:55 -08003781unpack_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003782{
3783 Py_ssize_t n = asdl_seq_LEN(elts);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003784 int seen_star = 0;
Brandt Bucher145bf262021-02-26 14:51:55 -08003785 for (Py_ssize_t i = 0; i < n; i++) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003786 expr_ty elt = asdl_seq_GET(elts, i);
3787 if (elt->kind == Starred_kind && !seen_star) {
3788 if ((i >= (1 << 8)) ||
3789 (n-i-1 >= (INT_MAX >> 8)))
3790 return compiler_error(c,
3791 "too many expressions in "
3792 "star-unpacking assignment");
3793 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3794 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 }
3796 else if (elt->kind == Starred_kind) {
3797 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003798 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003799 }
3800 }
3801 if (!seen_star) {
3802 ADDOP_I(c, UNPACK_SEQUENCE, n);
3803 }
Brandt Bucher145bf262021-02-26 14:51:55 -08003804 return 1;
3805}
3806
3807static int
3808assignment_helper(struct compiler *c, asdl_expr_seq *elts)
3809{
3810 Py_ssize_t n = asdl_seq_LEN(elts);
3811 RETURN_IF_FALSE(unpack_helper(c, elts));
3812 for (Py_ssize_t i = 0; i < n; i++) {
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003813 expr_ty elt = asdl_seq_GET(elts, i);
3814 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3815 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003816 return 1;
3817}
3818
3819static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003820compiler_list(struct compiler *c, expr_ty e)
3821{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003822 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003823 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003824 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003825 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003826 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003827 return starunpack_helper(c, elts, 0, BUILD_LIST,
3828 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003829 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003830 else
3831 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003832 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003833}
3834
3835static int
3836compiler_tuple(struct compiler *c, expr_ty e)
3837{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003838 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003839 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003840 return assignment_helper(c, elts);
3841 }
3842 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003843 return starunpack_helper(c, elts, 0, BUILD_LIST,
3844 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003845 }
3846 else
3847 VISIT_SEQ(c, expr, elts);
3848 return 1;
3849}
3850
3851static int
3852compiler_set(struct compiler *c, expr_ty e)
3853{
Mark Shannon13bc1392020-01-23 09:25:17 +00003854 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3855 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003856}
3857
3858static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003859are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003860{
3861 Py_ssize_t i;
3862 for (i = begin; i < end; i++) {
3863 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003864 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003865 return 0;
3866 }
3867 return 1;
3868}
3869
3870static int
3871compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3872{
3873 Py_ssize_t i, n = end - begin;
3874 PyObject *keys, *key;
3875 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3876 for (i = begin; i < end; i++) {
3877 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3878 }
3879 keys = PyTuple_New(n);
3880 if (keys == NULL) {
3881 return 0;
3882 }
3883 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003884 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003885 Py_INCREF(key);
3886 PyTuple_SET_ITEM(keys, i - begin, key);
3887 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003888 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003889 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3890 }
3891 else {
3892 for (i = begin; i < end; i++) {
3893 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3894 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3895 }
3896 ADDOP_I(c, BUILD_MAP, n);
3897 }
3898 return 1;
3899}
3900
3901static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003902compiler_dict(struct compiler *c, expr_ty e)
3903{
Victor Stinner976bb402016-03-23 11:36:19 +01003904 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003905 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003906 int is_unpacking = 0;
3907 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003908 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003909 elements = 0;
3910 for (i = 0; i < n; i++) {
3911 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003912 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003913 if (elements) {
3914 if (!compiler_subdict(c, e, i - elements, i)) {
3915 return 0;
3916 }
3917 if (have_dict) {
3918 ADDOP_I(c, DICT_UPDATE, 1);
3919 }
3920 have_dict = 1;
3921 elements = 0;
3922 }
3923 if (have_dict == 0) {
3924 ADDOP_I(c, BUILD_MAP, 0);
3925 have_dict = 1;
3926 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003927 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003928 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003929 }
3930 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003931 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003932 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003933 return 0;
3934 }
3935 if (have_dict) {
3936 ADDOP_I(c, DICT_UPDATE, 1);
3937 }
3938 have_dict = 1;
3939 elements = 0;
3940 }
3941 else {
3942 elements++;
3943 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 }
3945 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003946 if (elements) {
3947 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003948 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003949 }
3950 if (have_dict) {
3951 ADDOP_I(c, DICT_UPDATE, 1);
3952 }
3953 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003954 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003955 if (!have_dict) {
3956 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 }
3958 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003959}
3960
3961static int
3962compiler_compare(struct compiler *c, expr_ty e)
3963{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003964 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003965
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003966 if (!check_compare(c, e)) {
3967 return 0;
3968 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003970 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3971 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3972 if (n == 0) {
3973 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003974 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003975 }
3976 else {
3977 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003978 if (cleanup == NULL)
3979 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003980 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003981 VISIT(c, expr,
3982 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003983 ADDOP(c, DUP_TOP);
3984 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003985 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003986 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003987 NEXT_BLOCK(c);
3988 }
3989 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003990 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003991 basicblock *end = compiler_new_block(c);
3992 if (end == NULL)
3993 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00003994 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003995 compiler_use_next_block(c, cleanup);
3996 ADDOP(c, ROT_TWO);
3997 ADDOP(c, POP_TOP);
3998 compiler_use_next_block(c, end);
3999 }
4000 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004001}
4002
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004003static PyTypeObject *
4004infer_type(expr_ty e)
4005{
4006 switch (e->kind) {
4007 case Tuple_kind:
4008 return &PyTuple_Type;
4009 case List_kind:
4010 case ListComp_kind:
4011 return &PyList_Type;
4012 case Dict_kind:
4013 case DictComp_kind:
4014 return &PyDict_Type;
4015 case Set_kind:
4016 case SetComp_kind:
4017 return &PySet_Type;
4018 case GeneratorExp_kind:
4019 return &PyGen_Type;
4020 case Lambda_kind:
4021 return &PyFunction_Type;
4022 case JoinedStr_kind:
4023 case FormattedValue_kind:
4024 return &PyUnicode_Type;
4025 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01004026 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004027 default:
4028 return NULL;
4029 }
4030}
4031
4032static int
4033check_caller(struct compiler *c, expr_ty e)
4034{
4035 switch (e->kind) {
4036 case Constant_kind:
4037 case Tuple_kind:
4038 case List_kind:
4039 case ListComp_kind:
4040 case Dict_kind:
4041 case DictComp_kind:
4042 case Set_kind:
4043 case SetComp_kind:
4044 case GeneratorExp_kind:
4045 case JoinedStr_kind:
4046 case FormattedValue_kind:
4047 return compiler_warn(c, "'%.200s' object is not callable; "
4048 "perhaps you missed a comma?",
4049 infer_type(e)->tp_name);
4050 default:
4051 return 1;
4052 }
4053}
4054
4055static int
4056check_subscripter(struct compiler *c, expr_ty e)
4057{
4058 PyObject *v;
4059
4060 switch (e->kind) {
4061 case Constant_kind:
4062 v = e->v.Constant.value;
4063 if (!(v == Py_None || v == Py_Ellipsis ||
4064 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4065 PyAnySet_Check(v)))
4066 {
4067 return 1;
4068 }
4069 /* fall through */
4070 case Set_kind:
4071 case SetComp_kind:
4072 case GeneratorExp_kind:
4073 case Lambda_kind:
4074 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4075 "perhaps you missed a comma?",
4076 infer_type(e)->tp_name);
4077 default:
4078 return 1;
4079 }
4080}
4081
4082static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004083check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004084{
4085 PyObject *v;
4086
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004087 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004088 if (index_type == NULL
4089 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4090 || index_type == &PySlice_Type) {
4091 return 1;
4092 }
4093
4094 switch (e->kind) {
4095 case Constant_kind:
4096 v = e->v.Constant.value;
4097 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4098 return 1;
4099 }
4100 /* fall through */
4101 case Tuple_kind:
4102 case List_kind:
4103 case ListComp_kind:
4104 case JoinedStr_kind:
4105 case FormattedValue_kind:
4106 return compiler_warn(c, "%.200s indices must be integers or slices, "
4107 "not %.200s; "
4108 "perhaps you missed a comma?",
4109 infer_type(e)->tp_name,
4110 index_type->tp_name);
4111 default:
4112 return 1;
4113 }
4114}
4115
Zackery Spytz97f5de02019-03-22 01:30:32 -06004116// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004117static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004118maybe_optimize_method_call(struct compiler *c, expr_ty e)
4119{
4120 Py_ssize_t argsl, i;
4121 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004122 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004123
4124 /* Check that the call node is an attribute access, and that
4125 the call doesn't have keyword parameters. */
4126 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4127 asdl_seq_LEN(e->v.Call.keywords))
4128 return -1;
4129
4130 /* Check that there are no *varargs types of arguments. */
4131 argsl = asdl_seq_LEN(args);
4132 for (i = 0; i < argsl; i++) {
4133 expr_ty elt = asdl_seq_GET(args, i);
4134 if (elt->kind == Starred_kind) {
4135 return -1;
4136 }
4137 }
4138
4139 /* Alright, we can optimize the code. */
4140 VISIT(c, expr, meth->v.Attribute.value);
Mark Shannond48848c2021-03-14 18:01:30 +00004141 int old_lineno = c->u->u_lineno;
4142 c->u->u_lineno = meth->end_lineno;
Yury Selivanovf2392132016-12-13 19:03:51 -05004143 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4144 VISIT_SEQ(c, expr, e->v.Call.args);
4145 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
Mark Shannond48848c2021-03-14 18:01:30 +00004146 c->u->u_lineno = old_lineno;
Yury Selivanovf2392132016-12-13 19:03:51 -05004147 return 1;
4148}
4149
4150static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004151validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004152{
4153 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4154 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004155 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4156 if (key->arg == NULL) {
4157 continue;
4158 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004159 if (forbidden_name(c, key->arg, Store)) {
4160 return -1;
4161 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004162 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004163 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4164 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004165 c->u->u_col_offset = other->col_offset;
Brandt Bucher145bf262021-02-26 14:51:55 -08004166 compiler_error(c, "keyword argument repeated: %U", key->arg);
Pablo Galindo254ec782020-04-03 20:37:13 +01004167 return -1;
4168 }
4169 }
4170 }
4171 return 0;
4172}
4173
4174static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004175compiler_call(struct compiler *c, expr_ty e)
4176{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004177 int ret = maybe_optimize_method_call(c, e);
4178 if (ret >= 0) {
4179 return ret;
4180 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004181 if (!check_caller(c, e->v.Call.func)) {
4182 return 0;
4183 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004184 VISIT(c, expr, e->v.Call.func);
4185 return compiler_call_helper(c, 0,
4186 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004187 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004188}
4189
Eric V. Smith235a6f02015-09-19 14:51:32 -04004190static int
4191compiler_joined_str(struct compiler *c, expr_ty e)
4192{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004193 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004194 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4195 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004196 return 1;
4197}
4198
Eric V. Smitha78c7952015-11-03 12:45:05 -05004199/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004200static int
4201compiler_formatted_value(struct compiler *c, expr_ty e)
4202{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004203 /* Our oparg encodes 2 pieces of information: the conversion
4204 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004205
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004206 Convert the conversion char to 3 bits:
4207 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004208 !s : 001 0x1 FVC_STR
4209 !r : 010 0x2 FVC_REPR
4210 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004211
Eric V. Smitha78c7952015-11-03 12:45:05 -05004212 next bit is whether or not we have a format spec:
4213 yes : 100 0x4
4214 no : 000 0x0
4215 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004216
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004217 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004218 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004219
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004220 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004221 VISIT(c, expr, e->v.FormattedValue.value);
4222
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004223 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004224 case 's': oparg = FVC_STR; break;
4225 case 'r': oparg = FVC_REPR; break;
4226 case 'a': oparg = FVC_ASCII; break;
4227 case -1: oparg = FVC_NONE; break;
4228 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004229 PyErr_Format(PyExc_SystemError,
4230 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004231 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004232 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004233 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004234 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004235 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004236 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004237 }
4238
Eric V. Smitha78c7952015-11-03 12:45:05 -05004239 /* And push our opcode and oparg */
4240 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004241
Eric V. Smith235a6f02015-09-19 14:51:32 -04004242 return 1;
4243}
4244
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004245static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004246compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004247{
4248 Py_ssize_t i, n = end - begin;
4249 keyword_ty kw;
4250 PyObject *keys, *key;
4251 assert(n > 0);
4252 if (n > 1) {
4253 for (i = begin; i < end; i++) {
4254 kw = asdl_seq_GET(keywords, i);
4255 VISIT(c, expr, kw->value);
4256 }
4257 keys = PyTuple_New(n);
4258 if (keys == NULL) {
4259 return 0;
4260 }
4261 for (i = begin; i < end; i++) {
4262 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4263 Py_INCREF(key);
4264 PyTuple_SET_ITEM(keys, i - begin, key);
4265 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004266 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004267 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4268 }
4269 else {
4270 /* a for loop only executes once */
4271 for (i = begin; i < end; i++) {
4272 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004273 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004274 VISIT(c, expr, kw->value);
4275 }
4276 ADDOP_I(c, BUILD_MAP, n);
4277 }
4278 return 1;
4279}
4280
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004281/* shared code between compiler_call and compiler_class */
4282static int
4283compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004284 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004285 asdl_expr_seq *args,
4286 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004287{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004288 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004289
Pablo Galindo254ec782020-04-03 20:37:13 +01004290 if (validate_keywords(c, keywords) == -1) {
4291 return 0;
4292 }
4293
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004294 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004295 nkwelts = asdl_seq_LEN(keywords);
4296
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004297 for (i = 0; i < nelts; i++) {
4298 expr_ty elt = asdl_seq_GET(args, i);
4299 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004300 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004301 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004302 }
4303 for (i = 0; i < nkwelts; i++) {
4304 keyword_ty kw = asdl_seq_GET(keywords, i);
4305 if (kw->arg == NULL) {
4306 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004307 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004308 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004309
Mark Shannon13bc1392020-01-23 09:25:17 +00004310 /* No * or ** args, so can use faster calling sequence */
4311 for (i = 0; i < nelts; i++) {
4312 expr_ty elt = asdl_seq_GET(args, i);
4313 assert(elt->kind != Starred_kind);
4314 VISIT(c, expr, elt);
4315 }
4316 if (nkwelts) {
4317 PyObject *names;
4318 VISIT_SEQ(c, keyword, keywords);
4319 names = PyTuple_New(nkwelts);
4320 if (names == NULL) {
4321 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004322 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004323 for (i = 0; i < nkwelts; i++) {
4324 keyword_ty kw = asdl_seq_GET(keywords, i);
4325 Py_INCREF(kw->arg);
4326 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004327 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004328 ADDOP_LOAD_CONST_NEW(c, names);
4329 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4330 return 1;
4331 }
4332 else {
4333 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4334 return 1;
4335 }
4336
4337ex_call:
4338
4339 /* Do positional arguments. */
4340 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4341 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4342 }
4343 else if (starunpack_helper(c, args, n, BUILD_LIST,
4344 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4345 return 0;
4346 }
4347 /* Then keyword arguments */
4348 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004349 /* Has a new dict been pushed */
4350 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004351
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004352 nseen = 0; /* the number of keyword arguments on the stack following */
4353 for (i = 0; i < nkwelts; i++) {
4354 keyword_ty kw = asdl_seq_GET(keywords, i);
4355 if (kw->arg == NULL) {
4356 /* A keyword argument unpacking. */
4357 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004358 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004359 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004360 }
Mark Shannondb64f122020-06-01 10:42:42 +01004361 if (have_dict) {
4362 ADDOP_I(c, DICT_MERGE, 1);
4363 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004364 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004365 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004366 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004367 if (!have_dict) {
4368 ADDOP_I(c, BUILD_MAP, 0);
4369 have_dict = 1;
4370 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004371 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004372 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004373 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004374 else {
4375 nseen++;
4376 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004377 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004378 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004379 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004380 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004381 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004382 }
4383 if (have_dict) {
4384 ADDOP_I(c, DICT_MERGE, 1);
4385 }
4386 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004387 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004388 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004390 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4391 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004392}
4393
Nick Coghlan650f0d02007-04-15 12:05:43 +00004394
4395/* List and set comprehensions and generator expressions work by creating a
4396 nested function to perform the actual iteration. This means that the
4397 iteration variables don't leak into the current scope.
4398 The defined function is called immediately following its definition, with the
4399 result of that call being the result of the expression.
4400 The LC/SC version returns the populated container, while the GE version is
4401 flagged in symtable.c as a generator, so it returns the generator object
4402 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004403
4404 Possible cleanups:
4405 - iterate over the generator sequence instead of using recursion
4406*/
4407
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004408
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004409static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004411 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004412 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004414{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004415 comprehension_ty gen;
4416 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4417 if (gen->is_async) {
4418 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004419 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004420 } else {
4421 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004422 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004423 }
4424}
4425
4426static int
4427compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004428 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004429 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004430 expr_ty elt, expr_ty val, int type)
4431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 /* generate code for the iterator, then each of the ifs,
4433 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 comprehension_ty gen;
4436 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004437 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 start = compiler_new_block(c);
4440 skip = compiler_new_block(c);
4441 if_cleanup = compiler_new_block(c);
4442 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4445 anchor == NULL)
4446 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 if (gen_index == 0) {
4451 /* Receive outermost iter as an implicit argument */
4452 c->u->u_argcount = 1;
4453 ADDOP_I(c, LOAD_FAST, 0);
4454 }
4455 else {
4456 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004457 /* Fast path for the temporary variable assignment idiom:
4458 for y in [f(x)]
4459 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004460 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004461 switch (gen->iter->kind) {
4462 case List_kind:
4463 elts = gen->iter->v.List.elts;
4464 break;
4465 case Tuple_kind:
4466 elts = gen->iter->v.Tuple.elts;
4467 break;
4468 default:
4469 elts = NULL;
4470 }
4471 if (asdl_seq_LEN(elts) == 1) {
4472 expr_ty elt = asdl_seq_GET(elts, 0);
4473 if (elt->kind != Starred_kind) {
4474 VISIT(c, expr, elt);
4475 start = NULL;
4476 }
4477 }
4478 if (start) {
4479 VISIT(c, expr, gen->iter);
4480 ADDOP(c, GET_ITER);
4481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004483 if (start) {
4484 depth++;
4485 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004486 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004487 NEXT_BLOCK(c);
4488 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004489 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 /* XXX this needs to be cleaned up...a lot! */
4492 n = asdl_seq_LEN(gen->ifs);
4493 for (i = 0; i < n; i++) {
4494 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004495 if (!compiler_jump_if(c, e, if_cleanup, 0))
4496 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 NEXT_BLOCK(c);
4498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 if (++gen_index < asdl_seq_LEN(generators))
4501 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004502 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 elt, val, type))
4504 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 /* only append after the last for generator */
4507 if (gen_index >= asdl_seq_LEN(generators)) {
4508 /* comprehension specific code */
4509 switch (type) {
4510 case COMP_GENEXP:
4511 VISIT(c, expr, elt);
4512 ADDOP(c, YIELD_VALUE);
4513 ADDOP(c, POP_TOP);
4514 break;
4515 case COMP_LISTCOMP:
4516 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004517 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004518 break;
4519 case COMP_SETCOMP:
4520 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004521 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522 break;
4523 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004524 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004525 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004526 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004527 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004528 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004529 break;
4530 default:
4531 return 0;
4532 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004534 compiler_use_next_block(c, skip);
4535 }
4536 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004537 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004538 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004539 compiler_use_next_block(c, anchor);
4540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004541
4542 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004543}
4544
4545static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004547 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004548 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004549 expr_ty elt, expr_ty val, int type)
4550{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004551 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004552 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004554 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004555 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004556 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004558 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004559 return 0;
4560 }
4561
4562 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4563
4564 if (gen_index == 0) {
4565 /* Receive outermost iter as an implicit argument */
4566 c->u->u_argcount = 1;
4567 ADDOP_I(c, LOAD_FAST, 0);
4568 }
4569 else {
4570 /* Sub-iter - calculate on the fly */
4571 VISIT(c, expr, gen->iter);
4572 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004573 }
4574
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004575 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004576
Mark Shannon582aaf12020-08-04 17:30:11 +01004577 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004578 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004579 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004580 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004581 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004582 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004583
4584 n = asdl_seq_LEN(gen->ifs);
4585 for (i = 0; i < n; i++) {
4586 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004587 if (!compiler_jump_if(c, e, if_cleanup, 0))
4588 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004589 NEXT_BLOCK(c);
4590 }
4591
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004592 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004593 if (++gen_index < asdl_seq_LEN(generators))
4594 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004595 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004596 elt, val, type))
4597 return 0;
4598
4599 /* only append after the last for generator */
4600 if (gen_index >= asdl_seq_LEN(generators)) {
4601 /* comprehension specific code */
4602 switch (type) {
4603 case COMP_GENEXP:
4604 VISIT(c, expr, elt);
4605 ADDOP(c, YIELD_VALUE);
4606 ADDOP(c, POP_TOP);
4607 break;
4608 case COMP_LISTCOMP:
4609 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004610 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004611 break;
4612 case COMP_SETCOMP:
4613 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004614 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004615 break;
4616 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004617 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004618 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004619 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004620 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004621 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004622 break;
4623 default:
4624 return 0;
4625 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004626 }
4627 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004628 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004629
4630 compiler_use_next_block(c, except);
4631 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004632
4633 return 1;
4634}
4635
4636static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004637compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004638 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004639 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004642 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004643 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004644 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004645 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004646
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004647
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004648 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004649
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004650 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004651 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4652 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004653 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004655 }
4656
4657 is_async_generator = c->u->u_ste->ste_coroutine;
4658
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004659 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004660 compiler_error(c, "asynchronous comprehension outside of "
4661 "an asynchronous function");
4662 goto error_in_scope;
4663 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 if (type != COMP_GENEXP) {
4666 int op;
4667 switch (type) {
4668 case COMP_LISTCOMP:
4669 op = BUILD_LIST;
4670 break;
4671 case COMP_SETCOMP:
4672 op = BUILD_SET;
4673 break;
4674 case COMP_DICTCOMP:
4675 op = BUILD_MAP;
4676 break;
4677 default:
4678 PyErr_Format(PyExc_SystemError,
4679 "unknown comprehension type %d", type);
4680 goto error_in_scope;
4681 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 ADDOP_I(c, op, 0);
4684 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004685
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004686 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 val, type))
4688 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 if (type != COMP_GENEXP) {
4691 ADDOP(c, RETURN_VALUE);
4692 }
4693
4694 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004695 qualname = c->u->u_qualname;
4696 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004698 if (top_level_await && is_async_generator){
4699 c->u->u_ste->ste_coroutine = 1;
4700 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004701 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 goto error;
4703
Victor Stinnerba7a99d2021-01-30 01:46:44 +01004704 if (!compiler_make_closure(c, co, 0, qualname)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 goto error;
Victor Stinnerba7a99d2021-01-30 01:46:44 +01004706 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004707 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 Py_DECREF(co);
4709
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004710 VISIT(c, expr, outermost->iter);
4711
4712 if (outermost->is_async) {
4713 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004714 } else {
4715 ADDOP(c, GET_ITER);
4716 }
4717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004719
4720 if (is_async_generator && type != COMP_GENEXP) {
4721 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004722 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004723 ADDOP(c, YIELD_FROM);
4724 }
4725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004726 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004727error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004729error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004730 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 Py_XDECREF(co);
4732 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004733}
4734
4735static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004736compiler_genexp(struct compiler *c, expr_ty e)
4737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738 static identifier name;
4739 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004740 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004741 if (!name)
4742 return 0;
4743 }
4744 assert(e->kind == GeneratorExp_kind);
4745 return compiler_comprehension(c, e, COMP_GENEXP, name,
4746 e->v.GeneratorExp.generators,
4747 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004748}
4749
4750static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004751compiler_listcomp(struct compiler *c, expr_ty e)
4752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004753 static identifier name;
4754 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004755 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 if (!name)
4757 return 0;
4758 }
4759 assert(e->kind == ListComp_kind);
4760 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4761 e->v.ListComp.generators,
4762 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004763}
4764
4765static int
4766compiler_setcomp(struct compiler *c, expr_ty e)
4767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004768 static identifier name;
4769 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004770 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004771 if (!name)
4772 return 0;
4773 }
4774 assert(e->kind == SetComp_kind);
4775 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4776 e->v.SetComp.generators,
4777 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004778}
4779
4780
4781static int
4782compiler_dictcomp(struct compiler *c, expr_ty e)
4783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784 static identifier name;
4785 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004786 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004787 if (!name)
4788 return 0;
4789 }
4790 assert(e->kind == DictComp_kind);
4791 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4792 e->v.DictComp.generators,
4793 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004794}
4795
4796
4797static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004798compiler_visit_keyword(struct compiler *c, keyword_ty k)
4799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004800 VISIT(c, expr, k->value);
4801 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004802}
4803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004804/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004805 whether they are true or false.
4806
4807 Return values: 1 for true, 0 for false, -1 for non-constant.
4808 */
4809
4810static int
Mark Shannonfee55262019-11-21 09:11:43 +00004811compiler_with_except_finish(struct compiler *c) {
4812 basicblock *exit;
4813 exit = compiler_new_block(c);
4814 if (exit == NULL)
4815 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004816 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004817 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004818 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004819 compiler_use_next_block(c, exit);
4820 ADDOP(c, POP_TOP);
4821 ADDOP(c, POP_TOP);
4822 ADDOP(c, POP_TOP);
4823 ADDOP(c, POP_EXCEPT);
4824 ADDOP(c, POP_TOP);
4825 return 1;
4826}
Yury Selivanov75445082015-05-11 22:57:16 -04004827
4828/*
4829 Implements the async with statement.
4830
4831 The semantics outlined in that PEP are as follows:
4832
4833 async with EXPR as VAR:
4834 BLOCK
4835
4836 It is implemented roughly as:
4837
4838 context = EXPR
4839 exit = context.__aexit__ # not calling it
4840 value = await context.__aenter__()
4841 try:
4842 VAR = value # if VAR present in the syntax
4843 BLOCK
4844 finally:
4845 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004846 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004847 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004848 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004849 if not (await exit(*exc)):
4850 raise
4851 */
4852static int
4853compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4854{
Mark Shannonfee55262019-11-21 09:11:43 +00004855 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004856 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4857
4858 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004859 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004860 c->u->u_ste->ste_coroutine = 1;
4861 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004862 return compiler_error(c, "'async with' outside async function");
4863 }
Yury Selivanov75445082015-05-11 22:57:16 -04004864
4865 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004866 final = compiler_new_block(c);
4867 exit = compiler_new_block(c);
4868 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004869 return 0;
4870
4871 /* Evaluate EXPR */
4872 VISIT(c, expr, item->context_expr);
4873
4874 ADDOP(c, BEFORE_ASYNC_WITH);
4875 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004876 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004877 ADDOP(c, YIELD_FROM);
4878
Mark Shannon582aaf12020-08-04 17:30:11 +01004879 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004880
4881 /* SETUP_ASYNC_WITH pushes a finally block. */
4882 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004883 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004884 return 0;
4885 }
4886
4887 if (item->optional_vars) {
4888 VISIT(c, expr, item->optional_vars);
4889 }
4890 else {
4891 /* Discard result from context.__aenter__() */
4892 ADDOP(c, POP_TOP);
4893 }
4894
4895 pos++;
4896 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4897 /* BLOCK code */
4898 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4899 else if (!compiler_async_with(c, s, pos))
4900 return 0;
4901
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004902 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004903 ADDOP(c, POP_BLOCK);
4904 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004905
Mark Shannonfee55262019-11-21 09:11:43 +00004906 /* For successful outcome:
4907 * call __exit__(None, None, None)
4908 */
4909 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004910 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004911 ADDOP(c, GET_AWAITABLE);
4912 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4913 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004914
Mark Shannonfee55262019-11-21 09:11:43 +00004915 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004916
Mark Shannon582aaf12020-08-04 17:30:11 +01004917 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004918
4919 /* For exceptional outcome: */
4920 compiler_use_next_block(c, final);
4921
4922 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004923 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004924 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004925 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004926 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004927
Mark Shannonfee55262019-11-21 09:11:43 +00004928compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004929 return 1;
4930}
4931
4932
Guido van Rossumc2e20742006-02-27 22:32:47 +00004933/*
4934 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004935 with EXPR as VAR:
4936 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004937 is implemented as:
4938 <code for EXPR>
4939 SETUP_WITH E
4940 <code to store to VAR> or POP_TOP
4941 <code for BLOCK>
4942 LOAD_CONST (None, None, None)
4943 CALL_FUNCTION_EX 0
4944 JUMP_FORWARD EXIT
4945 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4946 POP_JUMP_IF_TRUE T:
4947 RERAISE
4948 T: POP_TOP * 3 (remove exception from stack)
4949 POP_EXCEPT
4950 POP_TOP
4951 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004952 */
Mark Shannonfee55262019-11-21 09:11:43 +00004953
Guido van Rossumc2e20742006-02-27 22:32:47 +00004954static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004955compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004956{
Mark Shannonfee55262019-11-21 09:11:43 +00004957 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004958 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004959
4960 assert(s->kind == With_kind);
4961
Guido van Rossumc2e20742006-02-27 22:32:47 +00004962 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004963 final = compiler_new_block(c);
4964 exit = compiler_new_block(c);
4965 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004966 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004967
Thomas Wouters477c8d52006-05-27 19:21:47 +00004968 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004969 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004970 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004971 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004972
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004973 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004974 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004975 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004976 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004977 }
4978
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004979 if (item->optional_vars) {
4980 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004981 }
4982 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004983 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004984 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004985 }
4986
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004987 pos++;
4988 if (pos == asdl_seq_LEN(s->v.With.items))
4989 /* BLOCK code */
4990 VISIT_SEQ(c, stmt, s->v.With.body)
4991 else if (!compiler_with(c, s, pos))
4992 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004993
Mark Shannon3bd60352021-01-13 12:05:43 +00004994
4995 /* Mark all following code as artificial */
4996 c->u->u_lineno = -1;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004997 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004998 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004999
Mark Shannonfee55262019-11-21 09:11:43 +00005000 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00005001
Mark Shannonfee55262019-11-21 09:11:43 +00005002 /* For successful outcome:
5003 * call __exit__(None, None, None)
5004 */
5005 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00005006 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00005007 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01005008 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005009
Mark Shannonfee55262019-11-21 09:11:43 +00005010 /* For exceptional outcome: */
5011 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005012
Mark Shannonfee55262019-11-21 09:11:43 +00005013 ADDOP(c, WITH_EXCEPT_START);
5014 compiler_with_except_finish(c);
5015
5016 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005017 return 1;
5018}
5019
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005020static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005021compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07005024 case NamedExpr_kind:
5025 VISIT(c, expr, e->v.NamedExpr.value);
5026 ADDOP(c, DUP_TOP);
5027 VISIT(c, expr, e->v.NamedExpr.target);
5028 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005029 case BoolOp_kind:
5030 return compiler_boolop(c, e);
5031 case BinOp_kind:
5032 VISIT(c, expr, e->v.BinOp.left);
5033 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05005034 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005035 break;
5036 case UnaryOp_kind:
5037 VISIT(c, expr, e->v.UnaryOp.operand);
5038 ADDOP(c, unaryop(e->v.UnaryOp.op));
5039 break;
5040 case Lambda_kind:
5041 return compiler_lambda(c, e);
5042 case IfExp_kind:
5043 return compiler_ifexp(c, e);
5044 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005045 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005047 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 case GeneratorExp_kind:
5049 return compiler_genexp(c, e);
5050 case ListComp_kind:
5051 return compiler_listcomp(c, e);
5052 case SetComp_kind:
5053 return compiler_setcomp(c, e);
5054 case DictComp_kind:
5055 return compiler_dictcomp(c, e);
5056 case Yield_kind:
5057 if (c->u->u_ste->ste_type != FunctionBlock)
5058 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005059 if (e->v.Yield.value) {
5060 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 }
5062 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005063 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005065 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005067 case YieldFrom_kind:
5068 if (c->u->u_ste->ste_type != FunctionBlock)
5069 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005070
5071 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5072 return compiler_error(c, "'yield from' inside async function");
5073
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005074 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005075 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005076 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005077 ADDOP(c, YIELD_FROM);
5078 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005079 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005080 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005081 if (c->u->u_ste->ste_type != FunctionBlock){
5082 return compiler_error(c, "'await' outside function");
5083 }
Yury Selivanov75445082015-05-11 22:57:16 -04005084
Victor Stinner331a6a52019-05-27 16:39:22 +02005085 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005086 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5087 return compiler_error(c, "'await' outside async function");
5088 }
5089 }
Yury Selivanov75445082015-05-11 22:57:16 -04005090
5091 VISIT(c, expr, e->v.Await.value);
5092 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005093 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005094 ADDOP(c, YIELD_FROM);
5095 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 case Compare_kind:
5097 return compiler_compare(c, e);
5098 case Call_kind:
5099 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005100 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005101 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005102 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005103 case JoinedStr_kind:
5104 return compiler_joined_str(c, e);
5105 case FormattedValue_kind:
5106 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005107 /* The following exprs can be assignment targets. */
5108 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005109 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005110 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 case Load:
Mark Shannond48848c2021-03-14 18:01:30 +00005112 {
5113 int old_lineno = c->u->u_lineno;
5114 c->u->u_lineno = e->end_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005116 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005117 break;
Mark Shannond48848c2021-03-14 18:01:30 +00005118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005119 case Store:
Mark Shannond48848c2021-03-14 18:01:30 +00005120 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx)) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005121 return 0;
Mark Shannond48848c2021-03-14 18:01:30 +00005122 }
5123 int old_lineno = c->u->u_lineno;
5124 c->u->u_lineno = e->end_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005126 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 break;
5128 case Del:
5129 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5130 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005131 }
5132 break;
5133 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005134 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 case Starred_kind:
5136 switch (e->v.Starred.ctx) {
5137 case Store:
5138 /* In all legitimate cases, the Starred node was already replaced
5139 * by compiler_list/compiler_tuple. XXX: is that okay? */
5140 return compiler_error(c,
5141 "starred assignment target must be in a list or tuple");
5142 default:
5143 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005144 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005146 break;
5147 case Slice_kind:
5148 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 case Name_kind:
5150 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5151 /* child nodes of List and Tuple will have expr_context set */
5152 case List_kind:
5153 return compiler_list(c, e);
5154 case Tuple_kind:
5155 return compiler_tuple(c, e);
Brandt Bucher145bf262021-02-26 14:51:55 -08005156 case MatchAs_kind:
5157 case MatchOr_kind:
5158 // Can only occur in patterns, which are handled elsewhere.
5159 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005160 }
5161 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005162}
5163
5164static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005165compiler_visit_expr(struct compiler *c, expr_ty e)
5166{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005167 int old_lineno = c->u->u_lineno;
5168 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005169 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005170 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005171 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005172 c->u->u_col_offset = old_col_offset;
5173 return res;
5174}
5175
5176static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005177compiler_augassign(struct compiler *c, stmt_ty s)
5178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005179 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005180 expr_ty e = s->v.AugAssign.target;
5181
5182 int old_lineno = c->u->u_lineno;
5183 int old_col_offset = c->u->u_col_offset;
5184 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005186 switch (e->kind) {
5187 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005188 VISIT(c, expr, e->v.Attribute.value);
5189 ADDOP(c, DUP_TOP);
Mark Shannond48848c2021-03-14 18:01:30 +00005190 int old_lineno = c->u->u_lineno;
5191 c->u->u_lineno = e->end_lineno;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005192 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Mark Shannond48848c2021-03-14 18:01:30 +00005193 c->u->u_lineno = old_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005194 break;
5195 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005196 VISIT(c, expr, e->v.Subscript.value);
5197 VISIT(c, expr, e->v.Subscript.slice);
5198 ADDOP(c, DUP_TOP_TWO);
5199 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005200 break;
5201 case Name_kind:
5202 if (!compiler_nameop(c, e->v.Name.id, Load))
5203 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005204 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005205 default:
5206 PyErr_Format(PyExc_SystemError,
5207 "invalid node type (%d) for augmented assignment",
5208 e->kind);
5209 return 0;
5210 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005211
5212 c->u->u_lineno = old_lineno;
5213 c->u->u_col_offset = old_col_offset;
5214
5215 VISIT(c, expr, s->v.AugAssign.value);
5216 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5217
5218 SET_LOC(c, e);
5219
5220 switch (e->kind) {
5221 case Attribute_kind:
Mark Shannond48848c2021-03-14 18:01:30 +00005222 c->u->u_lineno = e->end_lineno;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005223 ADDOP(c, ROT_TWO);
5224 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5225 break;
5226 case Subscript_kind:
5227 ADDOP(c, ROT_THREE);
5228 ADDOP(c, STORE_SUBSCR);
5229 break;
5230 case Name_kind:
5231 return compiler_nameop(c, e->v.Name.id, Store);
5232 default:
5233 Py_UNREACHABLE();
5234 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005235 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005236}
5237
5238static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005239check_ann_expr(struct compiler *c, expr_ty e)
5240{
5241 VISIT(c, expr, e);
5242 ADDOP(c, POP_TOP);
5243 return 1;
5244}
5245
5246static int
5247check_annotation(struct compiler *c, stmt_ty s)
5248{
5249 /* Annotations are only evaluated in a module or class. */
5250 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5251 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5252 return check_ann_expr(c, s->v.AnnAssign.annotation);
5253 }
5254 return 1;
5255}
5256
5257static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005258check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005259{
5260 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005261 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005262 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005263 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005264 return 0;
5265 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005266 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5267 return 0;
5268 }
5269 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5270 return 0;
5271 }
5272 return 1;
5273 case Tuple_kind: {
5274 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005275 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005276 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005277 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005278 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005279 return 0;
5280 }
5281 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005282 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005283 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005284 default:
5285 return check_ann_expr(c, e);
5286 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005287}
5288
5289static int
5290compiler_annassign(struct compiler *c, stmt_ty s)
5291{
5292 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005293 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005294
5295 assert(s->kind == AnnAssign_kind);
5296
5297 /* We perform the actual assignment first. */
5298 if (s->v.AnnAssign.value) {
5299 VISIT(c, expr, s->v.AnnAssign.value);
5300 VISIT(c, expr, targ);
5301 }
5302 switch (targ->kind) {
5303 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005304 if (forbidden_name(c, targ->v.Name.id, Store))
5305 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005306 /* If we have a simple name in a module or class, store annotation. */
5307 if (s->v.AnnAssign.simple &&
5308 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5309 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005310 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005311 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005312 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005313 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005314 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005315 }
5316 break;
5317 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005318 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5319 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005320 if (!s->v.AnnAssign.value &&
5321 !check_ann_expr(c, targ->v.Attribute.value)) {
5322 return 0;
5323 }
5324 break;
5325 case Subscript_kind:
5326 if (!s->v.AnnAssign.value &&
5327 (!check_ann_expr(c, targ->v.Subscript.value) ||
5328 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5329 return 0;
5330 }
5331 break;
5332 default:
5333 PyErr_Format(PyExc_SystemError,
5334 "invalid node type (%d) for annotated assignment",
5335 targ->kind);
5336 return 0;
5337 }
5338 /* Annotation is evaluated last. */
5339 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5340 return 0;
5341 }
5342 return 1;
5343}
5344
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005345/* Raises a SyntaxError and returns 0.
5346 If something goes wrong, a different exception may be raised.
5347*/
5348
5349static int
Brandt Bucher145bf262021-02-26 14:51:55 -08005350compiler_error(struct compiler *c, const char *format, ...)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005351{
Brandt Bucher145bf262021-02-26 14:51:55 -08005352 va_list vargs;
5353#ifdef HAVE_STDARG_PROTOTYPES
5354 va_start(vargs, format);
5355#else
5356 va_start(vargs);
5357#endif
5358 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5359 va_end(vargs);
5360 if (msg == NULL) {
5361 return 0;
5362 }
5363 PyObject *loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
5364 if (loc == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 Py_INCREF(Py_None);
5366 loc = Py_None;
5367 }
Brandt Bucher145bf262021-02-26 14:51:55 -08005368 PyObject *args = Py_BuildValue("O(OiiO)", msg, c->c_filename,
5369 c->u->u_lineno, c->u->u_col_offset + 1, loc);
5370 Py_DECREF(msg);
5371 if (args == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 goto exit;
Brandt Bucher145bf262021-02-26 14:51:55 -08005373 }
5374 PyErr_SetObject(PyExc_SyntaxError, args);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005375 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005376 Py_DECREF(loc);
Brandt Bucher145bf262021-02-26 14:51:55 -08005377 Py_XDECREF(args);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005379}
5380
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005381/* Emits a SyntaxWarning and returns 1 on success.
5382 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5383 and returns 0.
5384*/
5385static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005386compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005387{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005388 va_list vargs;
5389#ifdef HAVE_STDARG_PROTOTYPES
5390 va_start(vargs, format);
5391#else
5392 va_start(vargs);
5393#endif
5394 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5395 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005396 if (msg == NULL) {
5397 return 0;
5398 }
5399 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5400 c->u->u_lineno, NULL, NULL) < 0)
5401 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005402 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005403 /* Replace the SyntaxWarning exception with a SyntaxError
5404 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005405 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005406 assert(PyUnicode_AsUTF8(msg) != NULL);
5407 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005408 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005409 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005410 return 0;
5411 }
5412 Py_DECREF(msg);
5413 return 1;
5414}
5415
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005416static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005417compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005418{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005419 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005421
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005422 if (ctx == Load) {
5423 if (!check_subscripter(c, e->v.Subscript.value)) {
5424 return 0;
5425 }
5426 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5427 return 0;
5428 }
5429 }
5430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005431 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 case Store: op = STORE_SUBSCR; break;
5434 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005435 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005436 assert(op);
5437 VISIT(c, expr, e->v.Subscript.value);
5438 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 ADDOP(c, op);
5440 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005441}
5442
5443static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005444compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 int n = 2;
5447 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 /* only handles the cases where BUILD_SLICE is emitted */
5450 if (s->v.Slice.lower) {
5451 VISIT(c, expr, s->v.Slice.lower);
5452 }
5453 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005454 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005457 if (s->v.Slice.upper) {
5458 VISIT(c, expr, s->v.Slice.upper);
5459 }
5460 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005461 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005462 }
5463
5464 if (s->v.Slice.step) {
5465 n++;
5466 VISIT(c, expr, s->v.Slice.step);
5467 }
5468 ADDOP_I(c, BUILD_SLICE, n);
5469 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005470}
5471
Brandt Bucher145bf262021-02-26 14:51:55 -08005472
5473// PEP 634: Structural Pattern Matching
5474
5475// To keep things simple, all compiler_pattern_* routines follow the convention
5476// of replacing TOS (the subject for the given pattern) with either True (match)
5477// or False (no match). We do this even for irrefutable patterns; the idea is
5478// that it's much easier to smooth out any redundant pushing, popping, and
5479// jumping in the peephole optimizer than to detect or predict it here.
5480
5481
5482#define WILDCARD_CHECK(N) \
5483 ((N)->kind == Name_kind && \
5484 _PyUnicode_EqualToASCIIString((N)->v.Name.id, "_"))
5485
5486
5487static int
5488pattern_helper_store_name(struct compiler *c, identifier n, pattern_context *pc)
5489{
5490 assert(!_PyUnicode_EqualToASCIIString(n, "_"));
5491 // Can't assign to the same name twice:
5492 if (pc->stores == NULL) {
5493 RETURN_IF_FALSE(pc->stores = PySet_New(NULL));
5494 }
5495 else {
5496 int duplicate = PySet_Contains(pc->stores, n);
5497 if (duplicate < 0) {
5498 return 0;
5499 }
5500 if (duplicate) {
5501 const char *e = "multiple assignments to name %R in pattern";
5502 return compiler_error(c, e, n);
5503 }
5504 }
5505 RETURN_IF_FALSE(!PySet_Add(pc->stores, n));
5506 RETURN_IF_FALSE(compiler_nameop(c, n, Store));
5507 return 1;
5508}
5509
5510
5511static int
5512pattern_helper_sequence_unpack(struct compiler *c, asdl_expr_seq *values,
5513 Py_ssize_t star, pattern_context *pc)
5514{
5515 RETURN_IF_FALSE(unpack_helper(c, values));
5516 // We've now got a bunch of new subjects on the stack. If any of them fail
5517 // to match, we need to pop everything else off, then finally push False.
5518 // fails is an array of blocks that correspond to the necessary amount of
5519 // popping for each element:
5520 basicblock **fails;
5521 Py_ssize_t size = asdl_seq_LEN(values);
5522 fails = (basicblock **)PyObject_Malloc(sizeof(basicblock*) * size);
5523 if (fails == NULL) {
5524 PyErr_NoMemory();
5525 return 0;
5526 }
5527 // NOTE: Can't use our nice returning macros anymore: they'll leak memory!
5528 // goto error on error.
5529 for (Py_ssize_t i = 0; i < size; i++) {
5530 fails[i] = compiler_new_block(c);
5531 if (fails[i] == NULL) {
5532 goto error;
5533 }
5534 }
5535 for (Py_ssize_t i = 0; i < size; i++) {
5536 expr_ty value = asdl_seq_GET(values, i);
5537 if (i == star) {
5538 assert(value->kind == Starred_kind);
5539 value = value->v.Starred.value;
5540 }
5541 if (!compiler_pattern_subpattern(c, value, pc) ||
5542 !compiler_addop_j(c, POP_JUMP_IF_FALSE, fails[i]) ||
5543 compiler_next_block(c) == NULL)
5544 {
5545 goto error;
5546 }
5547 }
5548 // Success!
5549 basicblock *end = compiler_new_block(c);
5550 if (end == NULL ||
5551 !compiler_addop_load_const(c, Py_True) ||
5552 !compiler_addop_j(c, JUMP_FORWARD, end))
5553 {
5554 goto error;
5555 }
5556 // This is where we handle failed sub-patterns. For a sequence pattern like
5557 // [a, b, c, d], this will look like:
5558 // fails[0]: POP_TOP
5559 // fails[1]: POP_TOP
5560 // fails[2]: POP_TOP
5561 // fails[3]: LOAD_CONST False
5562 for (Py_ssize_t i = 0; i < size - 1; i++) {
5563 compiler_use_next_block(c, fails[i]);
5564 if (!compiler_addop(c, POP_TOP)) {
5565 goto error;
5566 }
5567 }
5568 compiler_use_next_block(c, fails[size - 1]);
5569 if (!compiler_addop_load_const(c, Py_False)) {
5570 goto error;
5571 }
5572 compiler_use_next_block(c, end);
5573 PyObject_Free(fails);
5574 return 1;
5575error:
5576 PyObject_Free(fails);
5577 return 0;
5578}
5579
5580// Like pattern_helper_sequence_unpack, but uses BINARY_SUBSCR instead of
5581// UNPACK_SEQUENCE / UNPACK_EX. This is more efficient for patterns with a
5582// starred wildcard like [first, *_] / [first, *_, last] / [*_, last] / etc.
5583static int
5584pattern_helper_sequence_subscr(struct compiler *c, asdl_expr_seq *values,
5585 Py_ssize_t star, pattern_context *pc)
5586{
5587 basicblock *end, *fail_pop_1;
5588 RETURN_IF_FALSE(end = compiler_new_block(c));
5589 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5590 Py_ssize_t size = asdl_seq_LEN(values);
5591 for (Py_ssize_t i = 0; i < size; i++) {
5592 expr_ty value = asdl_seq_GET(values, i);
5593 if (WILDCARD_CHECK(value)) {
5594 continue;
5595 }
5596 if (i == star) {
5597 assert(value->kind == Starred_kind);
5598 assert(WILDCARD_CHECK(value->v.Starred.value));
5599 continue;
5600 }
5601 ADDOP(c, DUP_TOP);
5602 if (i < star) {
5603 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
5604 }
5605 else {
5606 // The subject may not support negative indexing! Compute a
5607 // nonnegative index:
5608 ADDOP(c, GET_LEN);
5609 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size - i));
5610 ADDOP(c, BINARY_SUBTRACT);
5611 }
5612 ADDOP(c, BINARY_SUBSCR);
5613 RETURN_IF_FALSE(compiler_pattern_subpattern(c, value, pc));
5614 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5615 NEXT_BLOCK(c);
5616 }
5617 ADDOP(c, POP_TOP);
5618 ADDOP_LOAD_CONST(c, Py_True);
5619 ADDOP_JUMP(c, JUMP_FORWARD, end);
5620 compiler_use_next_block(c, fail_pop_1);
5621 ADDOP(c, POP_TOP);
5622 ADDOP_LOAD_CONST(c, Py_False);
5623 compiler_use_next_block(c, end);
5624 return 1;
5625}
5626
5627
5628// Like compiler_pattern, but turn off checks for irrefutability.
5629static int
5630compiler_pattern_subpattern(struct compiler *c, expr_ty p, pattern_context *pc)
5631{
5632 int allow_irrefutable = pc->allow_irrefutable;
5633 pc->allow_irrefutable = 1;
5634 RETURN_IF_FALSE(compiler_pattern(c, p, pc));
5635 pc->allow_irrefutable = allow_irrefutable;
5636 return 1;
5637}
5638
5639
5640static int
5641compiler_pattern_as(struct compiler *c, expr_ty p, pattern_context *pc)
5642{
5643 assert(p->kind == MatchAs_kind);
5644 basicblock *end, *fail_pop_1;
5645 RETURN_IF_FALSE(end = compiler_new_block(c));
5646 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5647 // Need to make a copy for (possibly) storing later:
5648 ADDOP(c, DUP_TOP);
5649 RETURN_IF_FALSE(compiler_pattern(c, p->v.MatchAs.pattern, pc));
5650 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5651 NEXT_BLOCK(c);
5652 RETURN_IF_FALSE(pattern_helper_store_name(c, p->v.MatchAs.name, pc));
5653 ADDOP_LOAD_CONST(c, Py_True);
5654 ADDOP_JUMP(c, JUMP_FORWARD, end);
5655 compiler_use_next_block(c, fail_pop_1);
5656 // Need to pop that unused copy from before:
5657 ADDOP(c, POP_TOP);
5658 ADDOP_LOAD_CONST(c, Py_False);
5659 compiler_use_next_block(c, end);
5660 return 1;
5661}
5662
5663
5664static int
5665compiler_pattern_capture(struct compiler *c, expr_ty p, pattern_context *pc)
5666{
5667 assert(p->kind == Name_kind);
5668 assert(p->v.Name.ctx == Store);
5669 assert(!WILDCARD_CHECK(p));
5670 if (!pc->allow_irrefutable) {
5671 // Whoops, can't have a name capture here!
5672 const char *e = "name capture %R makes remaining patterns unreachable";
5673 return compiler_error(c, e, p->v.Name.id);
5674 }
5675 RETURN_IF_FALSE(pattern_helper_store_name(c, p->v.Name.id, pc));
5676 ADDOP_LOAD_CONST(c, Py_True);
5677 return 1;
5678}
5679
5680
5681static int
5682compiler_pattern_class(struct compiler *c, expr_ty p, pattern_context *pc)
5683{
5684 asdl_expr_seq *args = p->v.Call.args;
5685 asdl_keyword_seq *kwargs = p->v.Call.keywords;
5686 Py_ssize_t nargs = asdl_seq_LEN(args);
5687 Py_ssize_t nkwargs = asdl_seq_LEN(kwargs);
5688 if (INT_MAX < nargs || INT_MAX < nargs + nkwargs - 1) {
5689 const char *e = "too many sub-patterns in class pattern %R";
5690 return compiler_error(c, e, p->v.Call.func);
5691 }
5692 RETURN_IF_FALSE(!validate_keywords(c, kwargs));
5693 basicblock *end, *fail_pop_1;
5694 RETURN_IF_FALSE(end = compiler_new_block(c));
5695 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5696 VISIT(c, expr, p->v.Call.func);
5697 PyObject *kwnames;
5698 RETURN_IF_FALSE(kwnames = PyTuple_New(nkwargs));
5699 Py_ssize_t i;
5700 for (i = 0; i < nkwargs; i++) {
5701 PyObject *name = ((keyword_ty) asdl_seq_GET(kwargs, i))->arg;
5702 Py_INCREF(name);
5703 PyTuple_SET_ITEM(kwnames, i, name);
5704 }
5705 ADDOP_LOAD_CONST_NEW(c, kwnames);
5706 ADDOP_I(c, MATCH_CLASS, nargs);
5707 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5708 NEXT_BLOCK(c);
5709 // TOS is now a tuple of (nargs + nkwargs) attributes.
5710 for (i = 0; i < nargs + nkwargs; i++) {
5711 expr_ty arg;
5712 if (i < nargs) {
5713 // Positional:
5714 arg = asdl_seq_GET(args, i);
5715 }
5716 else {
5717 // Keyword:
5718 arg = ((keyword_ty) asdl_seq_GET(kwargs, i - nargs))->value;
5719 }
5720 if (WILDCARD_CHECK(arg)) {
5721 continue;
5722 }
5723 // Get the i-th attribute, and match it against the i-th pattern:
5724 ADDOP(c, DUP_TOP);
5725 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
5726 ADDOP(c, BINARY_SUBSCR);
5727 RETURN_IF_FALSE(compiler_pattern_subpattern(c, arg, pc));
5728 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5729 NEXT_BLOCK(c);
5730 }
5731 // Success! Pop the tuple of attributes:
5732 ADDOP(c, POP_TOP);
5733 ADDOP_LOAD_CONST(c, Py_True);
5734 ADDOP_JUMP(c, JUMP_FORWARD, end);
5735 compiler_use_next_block(c, fail_pop_1);
5736 ADDOP(c, POP_TOP);
5737 ADDOP_LOAD_CONST(c, Py_False);
5738 compiler_use_next_block(c, end);
5739 return 1;
5740}
5741
5742
5743static int
5744compiler_pattern_literal(struct compiler *c, expr_ty p, pattern_context *pc)
5745{
5746 assert(p->kind == Constant_kind);
5747 PyObject *v = p->v.Constant.value;
5748 ADDOP_LOAD_CONST(c, v);
5749 // Literal True, False, and None are compared by identity. All others use
5750 // equality:
5751 ADDOP_COMPARE(c, (v == Py_None || PyBool_Check(v)) ? Is : Eq);
5752 return 1;
5753}
5754
5755
5756static int
5757compiler_pattern_mapping(struct compiler *c, expr_ty p, pattern_context *pc)
5758{
5759 basicblock *end, *fail_pop_1, *fail_pop_3;
5760 RETURN_IF_FALSE(end = compiler_new_block(c));
5761 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5762 RETURN_IF_FALSE(fail_pop_3 = compiler_new_block(c));
5763 asdl_expr_seq *keys = p->v.Dict.keys;
5764 asdl_expr_seq *values = p->v.Dict.values;
5765 Py_ssize_t size = asdl_seq_LEN(values);
Ikko Ashimine57827f82021-03-10 19:39:51 +09005766 // A starred pattern will be a keyless value. It is guaranteed to be last:
Brandt Bucher145bf262021-02-26 14:51:55 -08005767 int star = size ? !asdl_seq_GET(keys, size - 1) : 0;
5768 ADDOP(c, MATCH_MAPPING);
5769 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5770 NEXT_BLOCK(c);
5771 if (!size) {
5772 // If the pattern is just "{}", we're done!
5773 ADDOP(c, POP_TOP);
5774 ADDOP_LOAD_CONST(c, Py_True);
5775 ADDOP_JUMP(c, JUMP_FORWARD, end);
5776 compiler_use_next_block(c, fail_pop_1);
5777 ADDOP(c, POP_TOP);
5778 ADDOP_LOAD_CONST(c, Py_False);
5779 compiler_use_next_block(c, end);
5780 return 1;
5781 }
5782 if (size - star) {
5783 // If the pattern has any keys in it, perform a length check:
5784 ADDOP(c, GET_LEN);
5785 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size - star));
5786 ADDOP_COMPARE(c, GtE);
5787 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5788 NEXT_BLOCK(c);
5789 }
5790 if (INT_MAX < size - star - 1) {
5791 return compiler_error(c, "too many sub-patterns in mapping pattern");
5792 }
5793 // Collect all of the keys into a tuple for MATCH_KEYS and
5794 // COPY_DICT_WITHOUT_KEYS. They can either be dotted names or literals:
5795 for (Py_ssize_t i = 0; i < size - star; i++) {
5796 expr_ty key = asdl_seq_GET(keys, i);
5797 if (key == NULL) {
5798 const char *e = "can't use starred name here "
5799 "(consider moving to end)";
5800 return compiler_error(c, e);
5801 }
5802 VISIT(c, expr, key);
5803 }
5804 ADDOP_I(c, BUILD_TUPLE, size - star);
5805 ADDOP(c, MATCH_KEYS);
5806 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_3);
5807 NEXT_BLOCK(c);
5808 // So far so good. There's now a tuple of values on the stack to match
5809 // sub-patterns against:
5810 for (Py_ssize_t i = 0; i < size - star; i++) {
5811 expr_ty value = asdl_seq_GET(values, i);
5812 if (WILDCARD_CHECK(value)) {
5813 continue;
5814 }
5815 ADDOP(c, DUP_TOP);
5816 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(i));
5817 ADDOP(c, BINARY_SUBSCR);
5818 RETURN_IF_FALSE(compiler_pattern_subpattern(c, value, pc));
5819 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_3);
5820 NEXT_BLOCK(c);
5821 }
5822 // If we get this far, it's a match! We're done with that tuple of values.
5823 ADDOP(c, POP_TOP);
5824 if (star) {
5825 // If we had a starred name, bind a dict of remaining items to it:
5826 ADDOP(c, COPY_DICT_WITHOUT_KEYS);
5827 PyObject *id = asdl_seq_GET(values, size - 1)->v.Name.id;
5828 RETURN_IF_FALSE(pattern_helper_store_name(c, id, pc));
5829 }
5830 else {
5831 // Otherwise, we don't care about this tuple of keys anymore:
5832 ADDOP(c, POP_TOP);
5833 }
5834 // Pop the subject:
5835 ADDOP(c, POP_TOP);
5836 ADDOP_LOAD_CONST(c, Py_True);
5837 ADDOP_JUMP(c, JUMP_FORWARD, end);
5838 // The top two items are a tuple of values or None, followed by a tuple of
5839 // keys. Pop them both:
5840 compiler_use_next_block(c, fail_pop_3);
5841 ADDOP(c, POP_TOP);
5842 ADDOP(c, POP_TOP);
5843 compiler_use_next_block(c, fail_pop_1);
5844 // Pop the subject:
5845 ADDOP(c, POP_TOP);
5846 ADDOP_LOAD_CONST(c, Py_False);
5847 compiler_use_next_block(c, end);
5848 return 1;
5849}
5850
5851
5852static int
5853compiler_pattern_or(struct compiler *c, expr_ty p, pattern_context *pc)
5854{
5855 assert(p->kind == MatchOr_kind);
5856 // control is the set of names bound by the first alternative. If all of the
5857 // others bind the same names (they should), then this becomes pc->stores.
5858 PyObject *control = NULL;
5859 basicblock *end, *pass_pop_1;
5860 RETURN_IF_FALSE(end = compiler_new_block(c));
5861 RETURN_IF_FALSE(pass_pop_1 = compiler_new_block(c));
5862 Py_ssize_t size = asdl_seq_LEN(p->v.MatchOr.patterns);
5863 assert(size > 1);
5864 // We're going to be messing with pc. Keep the original info handy:
5865 PyObject *stores_init = pc->stores;
5866 int allow_irrefutable = pc->allow_irrefutable;
5867 for (Py_ssize_t i = 0; i < size; i++) {
5868 // NOTE: Can't use our nice returning macros in here: they'll leak sets!
5869 expr_ty alt = asdl_seq_GET(p->v.MatchOr.patterns, i);
5870 pc->stores = PySet_New(stores_init);
5871 // An irrefutable sub-pattern must be last, if it is allowed at all:
5872 int is_last = i == size - 1;
5873 pc->allow_irrefutable = allow_irrefutable && is_last;
5874 SET_LOC(c, alt);
5875 if (pc->stores == NULL ||
5876 // Only copy the subject if we're *not* on the last alternative:
5877 (!is_last && !compiler_addop(c, DUP_TOP)) ||
5878 !compiler_pattern(c, alt, pc) ||
5879 // Only jump if we're *not* on the last alternative:
5880 (!is_last && !compiler_addop_j(c, POP_JUMP_IF_TRUE, pass_pop_1)) ||
5881 !compiler_next_block(c))
5882 {
5883 goto fail;
5884 }
5885 if (!i) {
5886 // If this is the first alternative, save its stores as a "control"
5887 // for the others (they can't bind a different set of names):
5888 control = pc->stores;
5889 continue;
5890 }
5891 if (PySet_GET_SIZE(pc->stores) || PySet_GET_SIZE(control)) {
5892 // Otherwise, check to see if we differ from the control set:
5893 PyObject *diff = PyNumber_InPlaceXor(pc->stores, control);
5894 if (diff == NULL) {
5895 goto fail;
5896 }
5897 if (PySet_GET_SIZE(diff)) {
5898 // The names differ! Raise.
5899 Py_DECREF(diff);
5900 compiler_error(c, "alternative patterns bind different names");
5901 goto fail;
5902 }
5903 Py_DECREF(diff);
5904 }
5905 Py_DECREF(pc->stores);
5906 }
5907 Py_XDECREF(stores_init);
5908 // Update pc->stores and restore pc->allow_irrefutable:
5909 pc->stores = control;
5910 pc->allow_irrefutable = allow_irrefutable;
5911 ADDOP_JUMP(c, JUMP_FORWARD, end);
5912 compiler_use_next_block(c, pass_pop_1);
5913 ADDOP(c, POP_TOP);
5914 ADDOP_LOAD_CONST(c, Py_True);
5915 compiler_use_next_block(c, end);
5916 return 1;
5917fail:
5918 Py_XDECREF(stores_init);
5919 Py_XDECREF(control);
5920 return 0;
5921}
5922
5923
5924static int
5925compiler_pattern_sequence(struct compiler *c, expr_ty p, pattern_context *pc)
5926{
5927 assert(p->kind == List_kind || p->kind == Tuple_kind);
5928 asdl_expr_seq *values = (p->kind == Tuple_kind) ? p->v.Tuple.elts
5929 : p->v.List.elts;
5930 Py_ssize_t size = asdl_seq_LEN(values);
5931 Py_ssize_t star = -1;
5932 int only_wildcard = 1;
5933 int star_wildcard = 0;
5934 // Find a starred name, if it exists. There may be at most one:
5935 for (Py_ssize_t i = 0; i < size; i++) {
5936 expr_ty value = asdl_seq_GET(values, i);
5937 if (value->kind == Starred_kind) {
5938 value = value->v.Starred.value;
5939 if (star >= 0) {
5940 const char *e = "multiple starred names in sequence pattern";
5941 return compiler_error(c, e);
5942 }
5943 star_wildcard = WILDCARD_CHECK(value);
5944 star = i;
5945 }
5946 only_wildcard &= WILDCARD_CHECK(value);
5947 }
5948 basicblock *end, *fail_pop_1;
5949 RETURN_IF_FALSE(end = compiler_new_block(c));
5950 RETURN_IF_FALSE(fail_pop_1 = compiler_new_block(c));
5951 ADDOP(c, MATCH_SEQUENCE);
5952 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5953 NEXT_BLOCK(c);
5954 if (star < 0) {
5955 // No star: len(subject) == size
5956 ADDOP(c, GET_LEN);
5957 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size));
5958 ADDOP_COMPARE(c, Eq);
5959 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5960 NEXT_BLOCK(c);
5961 }
5962 else if (size > 1) {
5963 // Star: len(subject) >= size - 1
5964 ADDOP(c, GET_LEN);
5965 ADDOP_LOAD_CONST_NEW(c, PyLong_FromSsize_t(size - 1));
5966 ADDOP_COMPARE(c, GtE);
5967 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, fail_pop_1);
5968 NEXT_BLOCK(c);
5969 }
5970 if (only_wildcard) {
5971 // Patterns like: [] / [_] / [_, _] / [*_] / [_, *_] / [_, _, *_] / etc.
5972 ADDOP(c, POP_TOP);
5973 ADDOP_LOAD_CONST(c, Py_True);
5974 }
5975 else if (star_wildcard) {
5976 RETURN_IF_FALSE(pattern_helper_sequence_subscr(c, values, star, pc));
5977 }
5978 else {
5979 RETURN_IF_FALSE(pattern_helper_sequence_unpack(c, values, star, pc));
5980 }
5981 ADDOP_JUMP(c, JUMP_FORWARD, end);
5982 compiler_use_next_block(c, fail_pop_1);
5983 ADDOP(c, POP_TOP)
5984 ADDOP_LOAD_CONST(c, Py_False);
5985 compiler_use_next_block(c, end);
5986 return 1;
5987}
5988
5989
5990static int
5991compiler_pattern_value(struct compiler *c, expr_ty p, pattern_context *pc)
5992{
5993 assert(p->kind == Attribute_kind);
5994 assert(p->v.Attribute.ctx == Load);
5995 VISIT(c, expr, p);
5996 ADDOP_COMPARE(c, Eq);
5997 return 1;
5998}
5999
6000
6001static int
6002compiler_pattern_wildcard(struct compiler *c, expr_ty p, pattern_context *pc)
6003{
6004 assert(p->kind == Name_kind);
6005 assert(p->v.Name.ctx == Store);
6006 assert(WILDCARD_CHECK(p));
6007 if (!pc->allow_irrefutable) {
6008 // Whoops, can't have a wildcard here!
6009 const char *e = "wildcard makes remaining patterns unreachable";
6010 return compiler_error(c, e);
6011 }
6012 ADDOP(c, POP_TOP);
6013 ADDOP_LOAD_CONST(c, Py_True);
6014 return 1;
6015}
6016
6017
6018static int
6019compiler_pattern(struct compiler *c, expr_ty p, pattern_context *pc)
6020{
6021 SET_LOC(c, p);
6022 switch (p->kind) {
6023 case Attribute_kind:
6024 return compiler_pattern_value(c, p, pc);
6025 case BinOp_kind:
6026 // Because we allow "2+2j", things like "2+2" make it this far:
6027 return compiler_error(c, "patterns cannot include operators");
6028 case Call_kind:
6029 return compiler_pattern_class(c, p, pc);
6030 case Constant_kind:
6031 return compiler_pattern_literal(c, p, pc);
6032 case Dict_kind:
6033 return compiler_pattern_mapping(c, p, pc);
6034 case JoinedStr_kind:
6035 // Because we allow strings, f-strings make it this far:
6036 return compiler_error(c, "patterns cannot include f-strings");
6037 case List_kind:
6038 case Tuple_kind:
6039 return compiler_pattern_sequence(c, p, pc);
6040 case MatchAs_kind:
6041 return compiler_pattern_as(c, p, pc);
6042 case MatchOr_kind:
6043 return compiler_pattern_or(c, p, pc);
6044 case Name_kind:
6045 if (WILDCARD_CHECK(p)) {
6046 return compiler_pattern_wildcard(c, p, pc);
6047 }
6048 return compiler_pattern_capture(c, p, pc);
6049 default:
6050 Py_UNREACHABLE();
6051 }
6052}
6053
6054
6055static int
6056compiler_match(struct compiler *c, stmt_ty s)
6057{
6058 VISIT(c, expr, s->v.Match.subject);
6059 basicblock *next, *end;
6060 RETURN_IF_FALSE(end = compiler_new_block(c));
6061 Py_ssize_t cases = asdl_seq_LEN(s->v.Match.cases);
6062 assert(cases);
6063 pattern_context pc;
6064 // We use pc.stores to track:
6065 // - Repeated name assignments in the same pattern.
6066 // - Different name assignments in alternatives.
6067 // It's a set of names, but we don't create it until it's needed:
6068 pc.stores = NULL;
6069 match_case_ty m = asdl_seq_GET(s->v.Match.cases, cases - 1);
6070 int has_default = WILDCARD_CHECK(m->pattern) && 1 < cases;
6071 for (Py_ssize_t i = 0; i < cases - has_default; i++) {
6072 m = asdl_seq_GET(s->v.Match.cases, i);
6073 SET_LOC(c, m->pattern);
6074 RETURN_IF_FALSE(next = compiler_new_block(c));
6075 // If pc.allow_irrefutable is 0, any name captures against our subject
6076 // will raise. Irrefutable cases must be either guarded, last, or both:
6077 pc.allow_irrefutable = m->guard != NULL || i == cases - 1;
6078 // Only copy the subject if we're *not* on the last case:
6079 if (i != cases - has_default - 1) {
6080 ADDOP(c, DUP_TOP);
6081 }
6082 int result = compiler_pattern(c, m->pattern, &pc);
6083 Py_CLEAR(pc.stores);
6084 RETURN_IF_FALSE(result);
6085 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, next);
6086 NEXT_BLOCK(c);
6087 if (m->guard) {
6088 RETURN_IF_FALSE(compiler_jump_if(c, m->guard, next, 0));
6089 }
6090 // Success! Pop the subject off, we're done with it:
6091 if (i != cases - has_default - 1) {
6092 ADDOP(c, POP_TOP);
6093 }
6094 VISIT_SEQ(c, stmt, m->body);
6095 ADDOP_JUMP(c, JUMP_FORWARD, end);
6096 compiler_use_next_block(c, next);
6097 }
6098 if (has_default) {
6099 if (cases == 1) {
6100 // No matches. Done with the subject:
6101 ADDOP(c, POP_TOP);
6102 }
6103 // A trailing "case _" is common, and lets us save a bit of redundant
6104 // pushing and popping in the loop above:
6105 m = asdl_seq_GET(s->v.Match.cases, cases - 1);
6106 SET_LOC(c, m->pattern);
6107 if (m->guard) {
6108 RETURN_IF_FALSE(compiler_jump_if(c, m->guard, end, 0));
6109 }
6110 VISIT_SEQ(c, stmt, m->body);
6111 }
6112 compiler_use_next_block(c, end);
6113 return 1;
6114}
6115
6116
6117#undef WILDCARD_CHECK
6118
6119
Thomas Wouters89f507f2006-12-13 04:49:30 +00006120/* End of the compiler section, beginning of the assembler section */
6121
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006122/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07006123 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006124
6125 XXX must handle implicit jumps from one block to next
6126*/
6127
Thomas Wouters89f507f2006-12-13 04:49:30 +00006128struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006129 PyObject *a_bytecode; /* string containing bytecode */
6130 int a_offset; /* offset into bytecode */
6131 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006132 PyObject *a_lnotab; /* string containing lnotab */
6133 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00006134 int a_prevlineno; /* lineno of last emitted line in line table */
6135 int a_lineno; /* lineno of last emitted instruction */
6136 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006137 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00006138};
6139
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006140Py_LOCAL_INLINE(void)
6141stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006142{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02006143 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00006144 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006145 assert(b->b_startdepth < 0);
6146 b->b_startdepth = depth;
6147 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02006148 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006149}
6150
6151/* Find the flow path that needs the largest stack. We assume that
6152 * cycles in the flow graph have no net effect on the stack depth.
6153 */
6154static int
6155stackdepth(struct compiler *c)
6156{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006157 basicblock *b, *entryblock = NULL;
6158 basicblock **stack, **sp;
6159 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006160 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006161 b->b_startdepth = INT_MIN;
6162 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006163 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006164 }
Mark Shannon67969f52021-04-07 10:52:07 +01006165 assert(entryblock!= NULL);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006166 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
6167 if (!stack) {
6168 PyErr_NoMemory();
6169 return -1;
6170 }
6171
6172 sp = stack;
Mark Shannonb37181e2021-04-06 11:48:59 +01006173 if (c->u->u_ste->ste_generator || c->u->u_ste->ste_coroutine) {
6174 stackdepth_push(&sp, entryblock, 1);
6175 } else {
6176 stackdepth_push(&sp, entryblock, 0);
6177 }
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006178 while (sp != stack) {
6179 b = *--sp;
6180 int depth = b->b_startdepth;
6181 assert(depth >= 0);
6182 basicblock *next = b->b_next;
6183 for (int i = 0; i < b->b_iused; i++) {
6184 struct instr *instr = &b->b_instr[i];
6185 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
6186 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01006187 PyErr_Format(PyExc_SystemError,
6188 "compiler stack_effect(opcode=%d, arg=%i) failed",
6189 instr->i_opcode, instr->i_oparg);
6190 return -1;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006191 }
6192 int new_depth = depth + effect;
6193 if (new_depth > maxdepth) {
6194 maxdepth = new_depth;
6195 }
6196 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01006197 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006198 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
6199 assert(effect != PY_INVALID_STACK_EFFECT);
6200 int target_depth = depth + effect;
6201 if (target_depth > maxdepth) {
6202 maxdepth = target_depth;
6203 }
6204 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006205 stackdepth_push(&sp, instr->i_target, target_depth);
6206 }
6207 depth = new_depth;
6208 if (instr->i_opcode == JUMP_ABSOLUTE ||
6209 instr->i_opcode == JUMP_FORWARD ||
6210 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00006211 instr->i_opcode == RAISE_VARARGS ||
6212 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006213 {
6214 /* remaining code is dead */
6215 next = NULL;
6216 break;
6217 }
6218 }
6219 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00006220 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006221 stackdepth_push(&sp, next, depth);
6222 }
6223 }
6224 PyObject_Free(stack);
6225 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006226}
6227
6228static int
6229assemble_init(struct assembler *a, int nblocks, int firstlineno)
6230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006231 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00006232 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00006233 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006234 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00006235 if (a->a_bytecode == NULL) {
6236 goto error;
6237 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006238 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00006239 if (a->a_lnotab == NULL) {
6240 goto error;
6241 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07006242 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006243 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00006244 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006245 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006246 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00006247error:
6248 Py_XDECREF(a->a_bytecode);
6249 Py_XDECREF(a->a_lnotab);
6250 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006251}
6252
6253static void
6254assemble_free(struct assembler *a)
6255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006256 Py_XDECREF(a->a_bytecode);
6257 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006258}
6259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006260static int
6261blocksize(basicblock *b)
6262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006263 int i;
6264 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006266 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006267 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006268 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006269}
6270
Guido van Rossumf68d8e52001-04-14 17:55:09 +00006271static int
Mark Shannon877df852020-11-12 09:43:29 +00006272assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006273{
Mark Shannon877df852020-11-12 09:43:29 +00006274 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006275 if (a->a_lnotab_off + 2 >= len) {
6276 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
6277 return 0;
6278 }
Pablo Galindo86e322f2021-01-30 13:54:22 +00006279 unsigned char *lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab);
6280 lnotab += a->a_lnotab_off;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006281 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00006282 *lnotab++ = bdelta;
6283 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006284 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006285}
6286
Mark Shannon877df852020-11-12 09:43:29 +00006287/* Appends a range to the end of the line number table. See
6288 * Objects/lnotab_notes.txt for the description of the line number table. */
6289
6290static int
6291assemble_line_range(struct assembler *a)
6292{
6293 int ldelta, bdelta;
6294 bdelta = (a->a_offset - a->a_lineno_start) * 2;
6295 if (bdelta == 0) {
6296 return 1;
6297 }
6298 if (a->a_lineno < 0) {
6299 ldelta = -128;
6300 }
6301 else {
6302 ldelta = a->a_lineno - a->a_prevlineno;
6303 a->a_prevlineno = a->a_lineno;
6304 while (ldelta > 127) {
6305 if (!assemble_emit_linetable_pair(a, 0, 127)) {
6306 return 0;
6307 }
6308 ldelta -= 127;
6309 }
6310 while (ldelta < -127) {
6311 if (!assemble_emit_linetable_pair(a, 0, -127)) {
6312 return 0;
6313 }
6314 ldelta += 127;
6315 }
6316 }
6317 assert(-128 <= ldelta && ldelta < 128);
6318 while (bdelta > 254) {
6319 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
6320 return 0;
6321 }
6322 ldelta = a->a_lineno < 0 ? -128 : 0;
6323 bdelta -= 254;
6324 }
6325 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
6326 return 0;
6327 }
6328 a->a_lineno_start = a->a_offset;
6329 return 1;
6330}
6331
6332static int
6333assemble_lnotab(struct assembler *a, struct instr *i)
6334{
6335 if (i->i_lineno == a->a_lineno) {
6336 return 1;
6337 }
6338 if (!assemble_line_range(a)) {
6339 return 0;
6340 }
6341 a->a_lineno = i->i_lineno;
6342 return 1;
6343}
6344
6345
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006346/* assemble_emit()
6347 Extend the bytecode with a new instruction.
6348 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00006349*/
6350
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00006351static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006352assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00006353{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006354 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006355 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03006356 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006357
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006358 arg = i->i_oparg;
6359 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006360 if (i->i_lineno && !assemble_lnotab(a, i))
6361 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006362 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006363 if (len > PY_SSIZE_T_MAX / 2)
6364 return 0;
6365 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
6366 return 0;
6367 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03006368 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006369 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006370 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006371 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00006372}
6373
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00006374static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006375assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00006376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006377 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006378 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006379 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00006380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006381 /* Compute the size of each block and fixup jump args.
6382 Replace block pointer with position in bytecode. */
6383 do {
6384 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006385 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006386 bsize = blocksize(b);
6387 b->b_offset = totsize;
6388 totsize += bsize;
6389 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006390 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006391 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6392 bsize = b->b_offset;
6393 for (i = 0; i < b->b_iused; i++) {
6394 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006395 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006396 /* Relative jumps are computed relative to
6397 the instruction pointer after fetching
6398 the jump instruction.
6399 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006400 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01006401 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006402 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01006403 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006404 instr->i_oparg -= bsize;
6405 }
6406 if (instrsize(instr->i_oparg) != isize) {
6407 extended_arg_recompile = 1;
6408 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006410 }
6411 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00006412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006413 /* XXX: This is an awful hack that could hurt performance, but
6414 on the bright side it should work until we come up
6415 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00006416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006417 The issue is that in the first loop blocksize() is called
6418 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006419 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006420 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00006421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006422 So we loop until we stop seeing new EXTENDED_ARGs.
6423 The only EXTENDED_ARGs that could be popping up are
6424 ones in jump instructions. So this should converge
6425 fairly quickly.
6426 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006427 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00006428}
6429
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006430static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01006431dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006433 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006434 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006436 tuple = PyTuple_New(size);
6437 if (tuple == NULL)
6438 return NULL;
6439 while (PyDict_Next(dict, &pos, &k, &v)) {
6440 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006441 Py_INCREF(k);
6442 assert((i - offset) < size);
6443 assert((i - offset) >= 0);
6444 PyTuple_SET_ITEM(tuple, i - offset, k);
6445 }
6446 return tuple;
6447}
6448
6449static PyObject *
6450consts_dict_keys_inorder(PyObject *dict)
6451{
6452 PyObject *consts, *k, *v;
6453 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
6454
6455 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
6456 if (consts == NULL)
6457 return NULL;
6458 while (PyDict_Next(dict, &pos, &k, &v)) {
6459 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03006460 /* The keys of the dictionary can be tuples wrapping a contant.
6461 * (see compiler_add_o and _PyCode_ConstantKey). In that case
6462 * the object we want is always second. */
6463 if (PyTuple_CheckExact(k)) {
6464 k = PyTuple_GET_ITEM(k, 1);
6465 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006466 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006467 assert(i < size);
6468 assert(i >= 0);
6469 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006470 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006471 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006472}
6473
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006474static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006475compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006477 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006478 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006479 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04006480 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006481 if (ste->ste_nested)
6482 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07006483 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006484 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07006485 if (!ste->ste_generator && ste->ste_coroutine)
6486 flags |= CO_COROUTINE;
6487 if (ste->ste_generator && ste->ste_coroutine)
6488 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006489 if (ste->ste_varargs)
6490 flags |= CO_VARARGS;
6491 if (ste->ste_varkeywords)
6492 flags |= CO_VARKEYWORDS;
6493 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00006494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006495 /* (Only) inherit compilerflags in PyCF_MASK */
6496 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00006497
Pablo Galindo90235812020-03-15 04:29:22 +00006498 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07006499 ste->ste_coroutine &&
6500 !ste->ste_generator) {
6501 flags |= CO_COROUTINE;
6502 }
6503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006504 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00006505}
6506
Inada Naokibdb941b2021-02-10 09:20:42 +09006507// Merge *obj* with constant cache.
INADA Naokic2e16072018-11-26 21:23:22 +09006508// Unlike merge_consts_recursive(), this function doesn't work recursively.
6509static int
Inada Naokibdb941b2021-02-10 09:20:42 +09006510merge_const_one(struct compiler *c, PyObject **obj)
INADA Naokic2e16072018-11-26 21:23:22 +09006511{
Inada Naokibdb941b2021-02-10 09:20:42 +09006512 PyObject *key = _PyCode_ConstantKey(*obj);
INADA Naokic2e16072018-11-26 21:23:22 +09006513 if (key == NULL) {
6514 return 0;
6515 }
6516
6517 // t is borrowed reference
6518 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
6519 Py_DECREF(key);
6520 if (t == NULL) {
6521 return 0;
6522 }
Inada Naokibdb941b2021-02-10 09:20:42 +09006523 if (t == key) { // obj is new constant.
INADA Naokic2e16072018-11-26 21:23:22 +09006524 return 1;
6525 }
6526
Inada Naokibdb941b2021-02-10 09:20:42 +09006527 if (PyTuple_CheckExact(t)) {
6528 // t is still borrowed reference
6529 t = PyTuple_GET_ITEM(t, 1);
6530 }
6531
6532 Py_INCREF(t);
6533 Py_DECREF(*obj);
6534 *obj = t;
INADA Naokic2e16072018-11-26 21:23:22 +09006535 return 1;
6536}
6537
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006538static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01006539makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006541 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006542 PyObject *names = NULL;
6543 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006544 PyObject *name = NULL;
6545 PyObject *freevars = NULL;
6546 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006547 Py_ssize_t nlocals;
6548 int nlocals_int;
6549 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01006550 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006552 names = dict_keys_inorder(c->u->u_names, 0);
6553 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006554 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006555 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006556 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006557 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
6558 if (!cellvars)
6559 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006560 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006561 if (!freevars)
6562 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01006563
Inada Naokibdb941b2021-02-10 09:20:42 +09006564 if (!merge_const_one(c, &names) ||
6565 !merge_const_one(c, &varnames) ||
6566 !merge_const_one(c, &cellvars) ||
6567 !merge_const_one(c, &freevars))
INADA Naokic2e16072018-11-26 21:23:22 +09006568 {
6569 goto error;
6570 }
6571
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02006572 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01006573 assert(nlocals < INT_MAX);
6574 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
6575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006576 flags = compute_code_flags(c);
6577 if (flags < 0)
6578 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006579
Mark Shannon6e8128f2020-07-30 10:03:00 +01006580 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
6581 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006582 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006583 }
Inada Naokibdb941b2021-02-10 09:20:42 +09006584 if (!merge_const_one(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006585 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09006586 goto error;
6587 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006588
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01006589 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01006590 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01006591 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006592 maxdepth = stackdepth(c);
6593 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006594 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02006595 goto error;
6596 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006597 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00006598 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01006599 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01006600 varnames, freevars, cellvars, c->c_filename,
6601 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006602 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006603 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006604 Py_XDECREF(names);
6605 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006606 Py_XDECREF(name);
6607 Py_XDECREF(freevars);
6608 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006609 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006610}
6611
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006612
6613/* For debugging purposes only */
6614#if 0
6615static void
6616dump_instr(const struct instr *i)
6617{
Mark Shannon582aaf12020-08-04 17:30:11 +01006618 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
6619 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006620 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006622 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006623 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006624 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03006625 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006626 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
6627 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006628}
6629
6630static void
6631dump_basicblock(const basicblock *b)
6632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006633 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01006634 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
6635 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006636 if (b->b_instr) {
6637 int i;
6638 for (i = 0; i < b->b_iused; i++) {
6639 fprintf(stderr, " [%02d] ", i);
6640 dump_instr(b->b_instr + i);
6641 }
6642 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006643}
6644#endif
6645
Mark Shannon5977a792020-12-02 13:31:40 +00006646
6647static int
6648normalize_basic_block(basicblock *bb);
6649
Mark Shannon6e8128f2020-07-30 10:03:00 +01006650static int
6651optimize_cfg(struct assembler *a, PyObject *consts);
6652
Mark Shannon5977a792020-12-02 13:31:40 +00006653static int
6654ensure_exits_have_lineno(struct compiler *c);
6655
Mark Shannonb37181e2021-04-06 11:48:59 +01006656static int
6657insert_generator_prefix(struct compiler *c, basicblock *entryblock) {
6658
6659 int flags = compute_code_flags(c);
6660 if (flags < 0) {
6661 return -1;
6662 }
6663 int kind;
6664 if (flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
6665 if (flags & CO_COROUTINE) {
6666 kind = 1;
6667 }
6668 else if (flags & CO_ASYNC_GENERATOR) {
6669 kind = 2;
6670 }
6671 else {
6672 kind = 0;
6673 }
6674 }
6675 else {
6676 return 0;
6677 }
6678 if (compiler_next_instr(entryblock) < 0) {
6679 return -1;
6680 }
6681 for (int i = entryblock->b_iused-1; i > 0; i--) {
6682 entryblock->b_instr[i] = entryblock->b_instr[i-1];
6683 }
6684 entryblock->b_instr[0].i_opcode = GEN_START;
6685 entryblock->b_instr[0].i_oparg = kind;
6686 entryblock->b_instr[0].i_lineno = -1;
6687 entryblock->b_instr[0].i_target = NULL;
6688 return 0;
6689}
6690
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006691static PyCodeObject *
6692assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006694 basicblock *b, *entryblock;
6695 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006696 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006697 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006698 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00006699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006700 /* Make sure every block that falls off the end returns None.
6701 XXX NEXT_BLOCK() isn't quite right, because if the last
6702 block ends with a jump or return b_next shouldn't set.
6703 */
6704 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00006705 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006706 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03006707 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006708 ADDOP(c, RETURN_VALUE);
6709 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006710
Mark Shannon5977a792020-12-02 13:31:40 +00006711 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6712 if (normalize_basic_block(b)) {
Alex Henrie503627f2021-03-02 03:20:25 -07006713 return NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006714 }
6715 }
6716
6717 if (ensure_exits_have_lineno(c)) {
Alex Henrie503627f2021-03-02 03:20:25 -07006718 return NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006719 }
6720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006721 nblocks = 0;
6722 entryblock = NULL;
6723 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
6724 nblocks++;
6725 entryblock = b;
6726 }
Mark Shannon67969f52021-04-07 10:52:07 +01006727 assert(entryblock != NULL);
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006728
Mark Shannonb37181e2021-04-06 11:48:59 +01006729 if (insert_generator_prefix(c, entryblock)) {
6730 goto error;
6731 }
6732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006733 /* Set firstlineno if it wasn't explicitly set. */
6734 if (!c->u->u_firstlineno) {
Mark Shannon67969f52021-04-07 10:52:07 +01006735 if (entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006736 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00006737 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006738 c->u->u_firstlineno = 1;
6739 }
Mark Shannon5977a792020-12-02 13:31:40 +00006740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006741 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6742 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006743 a.a_entry = entryblock;
6744 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006745
Mark Shannon6e8128f2020-07-30 10:03:00 +01006746 consts = consts_dict_keys_inorder(c->u->u_consts);
6747 if (consts == NULL) {
6748 goto error;
6749 }
6750 if (optimize_cfg(&a, consts)) {
6751 goto error;
6752 }
6753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006754 /* Can't modify the bytecode after computing jump offsets. */
6755 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006756
Mark Shannoncc75ab72020-11-12 19:49:33 +00006757 /* Emit code. */
6758 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006759 for (j = 0; j < b->b_iused; j++)
6760 if (!assemble_emit(&a, &b->b_instr[j]))
6761 goto error;
6762 }
Mark Shannon877df852020-11-12 09:43:29 +00006763 if (!assemble_line_range(&a)) {
6764 return 0;
6765 }
6766 /* Emit sentinel at end of line number table */
6767 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
6768 goto error;
6769 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006770
Inada Naokibdb941b2021-02-10 09:20:42 +09006771 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006772 goto error;
Inada Naokibdb941b2021-02-10 09:20:42 +09006773 }
6774 if (!merge_const_one(c, &a.a_lnotab)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006775 goto error;
Inada Naokibdb941b2021-02-10 09:20:42 +09006776 }
6777 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0) {
6778 goto error;
6779 }
6780 if (!merge_const_one(c, &a.a_bytecode)) {
6781 goto error;
6782 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006783
Mark Shannon6e8128f2020-07-30 10:03:00 +01006784 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006785 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006786 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006787 assemble_free(&a);
6788 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006789}
Georg Brandl8334fd92010-12-04 10:26:46 +00006790
Mark Shannon6e8128f2020-07-30 10:03:00 +01006791/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6792 with LOAD_CONST (c1, c2, ... cn).
6793 The consts table must still be in list form so that the
6794 new constant (c1, c2, ... cn) can be appended.
6795 Called with codestr pointing to the first LOAD_CONST.
6796*/
6797static int
6798fold_tuple_on_constants(struct instr *inst,
6799 int n, PyObject *consts)
6800{
6801 /* Pre-conditions */
6802 assert(PyList_CheckExact(consts));
6803 assert(inst[n].i_opcode == BUILD_TUPLE);
6804 assert(inst[n].i_oparg == n);
6805
6806 for (int i = 0; i < n; i++) {
6807 if (inst[i].i_opcode != LOAD_CONST) {
6808 return 0;
6809 }
6810 }
6811
6812 /* Buildup new tuple of constants */
6813 PyObject *newconst = PyTuple_New(n);
6814 if (newconst == NULL) {
6815 return -1;
6816 }
6817 for (int i = 0; i < n; i++) {
6818 int arg = inst[i].i_oparg;
6819 PyObject *constant = PyList_GET_ITEM(consts, arg);
6820 Py_INCREF(constant);
6821 PyTuple_SET_ITEM(newconst, i, constant);
6822 }
6823 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006824 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006825 Py_DECREF(newconst);
6826 PyErr_SetString(PyExc_OverflowError, "too many constants");
6827 return -1;
6828 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006829 if (PyList_Append(consts, newconst)) {
6830 Py_DECREF(newconst);
6831 return -1;
6832 }
6833 Py_DECREF(newconst);
6834 for (int i = 0; i < n; i++) {
6835 inst[i].i_opcode = NOP;
6836 }
6837 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006838 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006839 return 0;
6840}
6841
Mark Shannon28b75c82020-12-23 11:43:10 +00006842
6843static int
6844eliminate_jump_to_jump(basicblock *bb, int opcode) {
6845 assert (bb->b_iused > 0);
6846 struct instr *inst = &bb->b_instr[bb->b_iused-1];
6847 assert (is_jump(inst));
6848 assert (inst->i_target->b_iused > 0);
6849 struct instr *target = &inst->i_target->b_instr[0];
6850 if (inst->i_target == target->i_target) {
6851 /* Nothing to do */
6852 return 0;
6853 }
6854 int lineno = target->i_lineno;
6855 if (add_jump_to_block(bb, opcode, lineno, target->i_target) == 0) {
6856 return -1;
6857 }
6858 assert (bb->b_iused >= 2);
6859 bb->b_instr[bb->b_iused-2].i_opcode = NOP;
6860 return 0;
6861}
6862
Mark Shannoncc75ab72020-11-12 19:49:33 +00006863/* Maximum size of basic block that should be copied in optimizer */
6864#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006865
6866/* Optimization */
6867static int
6868optimize_basic_block(basicblock *bb, PyObject *consts)
6869{
6870 assert(PyList_CheckExact(consts));
6871 struct instr nop;
6872 nop.i_opcode = NOP;
6873 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006874 for (int i = 0; i < bb->b_iused; i++) {
6875 struct instr *inst = &bb->b_instr[i];
6876 int oparg = inst->i_oparg;
6877 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006878 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006879 /* Skip over empty basic blocks. */
6880 while (inst->i_target->b_iused == 0) {
6881 inst->i_target = inst->i_target->b_next;
6882 }
6883 target = &inst->i_target->b_instr[0];
6884 }
6885 else {
6886 target = &nop;
6887 }
6888 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006889 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006890 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006891 {
6892 PyObject* cnt;
6893 int is_true;
6894 int jump_if_true;
6895 switch(nextop) {
6896 case POP_JUMP_IF_FALSE:
6897 case POP_JUMP_IF_TRUE:
6898 cnt = PyList_GET_ITEM(consts, oparg);
6899 is_true = PyObject_IsTrue(cnt);
6900 if (is_true == -1) {
6901 goto error;
6902 }
6903 inst->i_opcode = NOP;
6904 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6905 if (is_true == jump_if_true) {
6906 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6907 bb->b_nofallthrough = 1;
6908 }
6909 else {
6910 bb->b_instr[i+1].i_opcode = NOP;
6911 }
6912 break;
6913 case JUMP_IF_FALSE_OR_POP:
6914 case JUMP_IF_TRUE_OR_POP:
6915 cnt = PyList_GET_ITEM(consts, oparg);
6916 is_true = PyObject_IsTrue(cnt);
6917 if (is_true == -1) {
6918 goto error;
6919 }
6920 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6921 if (is_true == jump_if_true) {
6922 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6923 bb->b_nofallthrough = 1;
6924 }
6925 else {
6926 inst->i_opcode = NOP;
6927 bb->b_instr[i+1].i_opcode = NOP;
6928 }
6929 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006930 }
6931 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006932 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006933
6934 /* Try to fold tuples of constants.
6935 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6936 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6937 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6938 case BUILD_TUPLE:
6939 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6940 switch(oparg) {
6941 case 1:
6942 inst->i_opcode = NOP;
6943 bb->b_instr[i+1].i_opcode = NOP;
6944 break;
6945 case 2:
6946 inst->i_opcode = ROT_TWO;
6947 bb->b_instr[i+1].i_opcode = NOP;
6948 break;
6949 case 3:
6950 inst->i_opcode = ROT_THREE;
6951 bb->b_instr[i+1].i_opcode = ROT_TWO;
6952 }
6953 break;
6954 }
6955 if (i >= oparg) {
6956 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6957 goto error;
6958 }
6959 }
6960 break;
6961
6962 /* Simplify conditional jump to conditional jump where the
6963 result of the first test implies the success of a similar
6964 test or the failure of the opposite test.
6965 Arises in code like:
6966 "a and b or c"
6967 "(a and b) and c"
6968 "(a or b) or c"
6969 "(a or b) and c"
6970 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6971 --> x:JUMP_IF_FALSE_OR_POP z
6972 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6973 --> x:POP_JUMP_IF_FALSE y+1
6974 where y+1 is the instruction following the second test.
6975 */
6976 case JUMP_IF_FALSE_OR_POP:
6977 switch(target->i_opcode) {
6978 case POP_JUMP_IF_FALSE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006979 if (inst->i_lineno == target->i_lineno) {
6980 *inst = *target;
6981 i--;
6982 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006983 break;
6984 case JUMP_ABSOLUTE:
6985 case JUMP_FORWARD:
6986 case JUMP_IF_FALSE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006987 if (inst->i_lineno == target->i_lineno &&
6988 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006989 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006990 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006991 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006992 break;
6993 case JUMP_IF_TRUE_OR_POP:
6994 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006995 if (inst->i_lineno == target->i_lineno) {
6996 inst->i_opcode = POP_JUMP_IF_FALSE;
6997 inst->i_target = inst->i_target->b_next;
6998 --i;
6999 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007000 break;
7001 }
7002 break;
7003
7004 case JUMP_IF_TRUE_OR_POP:
7005 switch(target->i_opcode) {
7006 case POP_JUMP_IF_TRUE:
Mark Shannon28b75c82020-12-23 11:43:10 +00007007 if (inst->i_lineno == target->i_lineno) {
7008 *inst = *target;
7009 i--;
7010 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007011 break;
7012 case JUMP_ABSOLUTE:
7013 case JUMP_FORWARD:
7014 case JUMP_IF_TRUE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00007015 if (inst->i_lineno == target->i_lineno &&
7016 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00007017 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007018 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007019 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007020 break;
7021 case JUMP_IF_FALSE_OR_POP:
7022 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00007023 if (inst->i_lineno == target->i_lineno) {
7024 inst->i_opcode = POP_JUMP_IF_TRUE;
7025 inst->i_target = inst->i_target->b_next;
7026 --i;
7027 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007028 break;
7029 }
7030 break;
7031
7032 case POP_JUMP_IF_FALSE:
7033 switch(target->i_opcode) {
7034 case JUMP_ABSOLUTE:
7035 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007036 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00007037 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007038 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007039 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007040 break;
7041 }
7042 break;
7043
7044 case POP_JUMP_IF_TRUE:
7045 switch(target->i_opcode) {
7046 case JUMP_ABSOLUTE:
7047 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007048 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00007049 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00007050 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00007051 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007052 break;
7053 }
7054 break;
7055
7056 case JUMP_ABSOLUTE:
7057 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007058 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007059 switch(target->i_opcode) {
7060 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00007061 if (eliminate_jump_to_jump(bb, inst->i_opcode)) {
7062 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00007063 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007064 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00007065
Mark Shannon6e8128f2020-07-30 10:03:00 +01007066 case JUMP_ABSOLUTE:
Mark Shannon28b75c82020-12-23 11:43:10 +00007067 if (eliminate_jump_to_jump(bb, JUMP_ABSOLUTE)) {
7068 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00007069 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007070 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00007071 default:
7072 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
7073 basicblock *to_copy = inst->i_target;
7074 inst->i_opcode = NOP;
7075 for (i = 0; i < to_copy->b_iused; i++) {
7076 int index = compiler_next_instr(bb);
7077 if (index < 0) {
7078 return -1;
7079 }
7080 bb->b_instr[index] = to_copy->b_instr[i];
7081 }
7082 bb->b_exit = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007083 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00007084 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007085 }
7086 }
7087 return 0;
7088error:
7089 return -1;
7090}
7091
7092
7093static void
Mark Shannon1659ad12021-01-13 15:05:04 +00007094clean_basic_block(basicblock *bb, int prev_lineno) {
7095 /* Remove NOPs when legal to do so. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01007096 int dest = 0;
7097 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00007098 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007099 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00007100 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007101 if (lineno < 0) {
7102 continue;
7103 }
Mark Shannon266b4622020-11-17 19:30:14 +00007104 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007105 if (prev_lineno == lineno) {
7106 continue;
7107 }
Mark Shannon266b4622020-11-17 19:30:14 +00007108 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007109 if (src < bb->b_iused - 1) {
7110 int next_lineno = bb->b_instr[src+1].i_lineno;
7111 if (next_lineno < 0 || next_lineno == lineno) {
7112 bb->b_instr[src+1].i_lineno = lineno;
7113 continue;
Mark Shannon877df852020-11-12 09:43:29 +00007114 }
7115 }
Mark Shannon266b4622020-11-17 19:30:14 +00007116 else {
7117 basicblock* next = bb->b_next;
7118 while (next && next->b_iused == 0) {
7119 next = next->b_next;
7120 }
7121 /* or if last instruction in BB and next BB has same line number */
7122 if (next) {
7123 if (lineno == next->b_instr[0].i_lineno) {
7124 continue;
7125 }
7126 }
7127 }
7128
Mark Shannon6e8128f2020-07-30 10:03:00 +01007129 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00007130 if (dest != src) {
7131 bb->b_instr[dest] = bb->b_instr[src];
7132 }
7133 dest++;
7134 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007135 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01007136 assert(dest <= bb->b_iused);
7137 bb->b_iused = dest;
7138}
7139
Mark Shannon266b4622020-11-17 19:30:14 +00007140static int
7141normalize_basic_block(basicblock *bb) {
7142 /* Mark blocks as exit and/or nofallthrough.
7143 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007144 for (int i = 0; i < bb->b_iused; i++) {
7145 switch(bb->b_instr[i].i_opcode) {
7146 case RETURN_VALUE:
7147 case RAISE_VARARGS:
7148 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007149 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00007150 bb->b_nofallthrough = 1;
7151 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007152 case JUMP_ABSOLUTE:
7153 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00007154 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00007155 /* fall through */
7156 case POP_JUMP_IF_FALSE:
7157 case POP_JUMP_IF_TRUE:
7158 case JUMP_IF_FALSE_OR_POP:
7159 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00007160 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00007161 if (i != bb->b_iused-1) {
7162 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
7163 return -1;
7164 }
Mark Shannon5977a792020-12-02 13:31:40 +00007165 /* Skip over empty basic blocks. */
7166 while (bb->b_instr[i].i_target->b_iused == 0) {
7167 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
7168 }
7169
Mark Shannoncc75ab72020-11-12 19:49:33 +00007170 }
7171 }
Mark Shannon266b4622020-11-17 19:30:14 +00007172 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007173}
7174
Mark Shannon6e8128f2020-07-30 10:03:00 +01007175static int
7176mark_reachable(struct assembler *a) {
7177 basicblock **stack, **sp;
7178 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
7179 if (stack == NULL) {
7180 return -1;
7181 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007182 a->a_entry->b_predecessors = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00007183 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007184 while (sp > stack) {
7185 basicblock *b = *(--sp);
Mark Shannon3bd60352021-01-13 12:05:43 +00007186 if (b->b_next && !b->b_nofallthrough) {
7187 if (b->b_next->b_predecessors == 0) {
7188 *sp++ = b->b_next;
7189 }
7190 b->b_next->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007191 }
7192 for (int i = 0; i < b->b_iused; i++) {
7193 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01007194 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007195 target = b->b_instr[i].i_target;
Mark Shannon3bd60352021-01-13 12:05:43 +00007196 if (target->b_predecessors == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007197 *sp++ = target;
7198 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007199 target->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007200 }
7201 }
7202 }
7203 PyObject_Free(stack);
7204 return 0;
7205}
7206
Mark Shannon3bd60352021-01-13 12:05:43 +00007207static void
7208eliminate_empty_basic_blocks(basicblock *entry) {
7209 /* Eliminate empty blocks */
7210 for (basicblock *b = entry; b != NULL; b = b->b_next) {
7211 basicblock *next = b->b_next;
7212 if (next) {
7213 while (next->b_iused == 0 && next->b_next) {
7214 next = next->b_next;
7215 }
7216 b->b_next = next;
7217 }
7218 }
7219 for (basicblock *b = entry; b != NULL; b = b->b_next) {
7220 if (b->b_iused == 0) {
7221 continue;
7222 }
7223 if (is_jump(&b->b_instr[b->b_iused-1])) {
7224 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7225 while (target->b_iused == 0) {
7226 target = target->b_next;
7227 }
7228 b->b_instr[b->b_iused-1].i_target = target;
7229 }
7230 }
7231}
7232
7233
Mark Shannon5977a792020-12-02 13:31:40 +00007234/* If an instruction has no line number, but it's predecessor in the BB does,
Mark Shannon3bd60352021-01-13 12:05:43 +00007235 * then copy the line number. If a successor block has no line number, and only
7236 * one predecessor, then inherit the line number.
7237 * This ensures that all exit blocks (with one predecessor) receive a line number.
7238 * Also reduces the size of the line number table,
Mark Shannon5977a792020-12-02 13:31:40 +00007239 * but has no impact on the generated line number events.
7240 */
7241static void
Mark Shannon3bd60352021-01-13 12:05:43 +00007242propogate_line_numbers(struct assembler *a) {
Mark Shannon5977a792020-12-02 13:31:40 +00007243 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007244 if (b->b_iused == 0) {
7245 continue;
7246 }
Mark Shannon5977a792020-12-02 13:31:40 +00007247 int prev_lineno = -1;
7248 for (int i = 0; i < b->b_iused; i++) {
7249 if (b->b_instr[i].i_lineno < 0) {
7250 b->b_instr[i].i_lineno = prev_lineno;
7251 }
7252 else {
7253 prev_lineno = b->b_instr[i].i_lineno;
7254 }
7255 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007256 if (!b->b_nofallthrough && b->b_next->b_predecessors == 1) {
7257 assert(b->b_next->b_iused);
7258 if (b->b_next->b_instr[0].i_lineno < 0) {
7259 b->b_next->b_instr[0].i_lineno = prev_lineno;
7260 }
7261 }
7262 if (is_jump(&b->b_instr[b->b_iused-1])) {
7263 switch (b->b_instr[b->b_iused-1].i_opcode) {
7264 /* Note: Only actual jumps, not exception handlers */
7265 case SETUP_ASYNC_WITH:
7266 case SETUP_WITH:
7267 case SETUP_FINALLY:
7268 continue;
7269 }
7270 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7271 if (target->b_predecessors == 1) {
7272 if (target->b_instr[0].i_lineno < 0) {
7273 target->b_instr[0].i_lineno = prev_lineno;
7274 }
7275 }
7276 }
Mark Shannon5977a792020-12-02 13:31:40 +00007277 }
7278}
7279
7280/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01007281 The consts object should still be in list form to allow new constants
7282 to be appended.
7283
7284 All transformations keep the code size the same or smaller.
7285 For those that reduce size, the gaps are initially filled with
7286 NOPs. Later those NOPs are removed.
7287*/
7288
7289static int
7290optimize_cfg(struct assembler *a, PyObject *consts)
7291{
Mark Shannoncc75ab72020-11-12 19:49:33 +00007292 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00007293 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01007294 return -1;
7295 }
Mark Shannon1659ad12021-01-13 15:05:04 +00007296 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00007297 assert(b->b_predecessors == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007298 }
7299 if (mark_reachable(a)) {
7300 return -1;
7301 }
7302 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00007303 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007304 if (b->b_predecessors == 0) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00007305 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05307306 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01007307 }
7308 }
Mark Shannon1659ad12021-01-13 15:05:04 +00007309 basicblock *pred = NULL;
7310 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
7311 int prev_lineno = -1;
7312 if (pred && pred->b_iused) {
7313 prev_lineno = pred->b_instr[pred->b_iused-1].i_lineno;
7314 }
7315 clean_basic_block(b, prev_lineno);
7316 pred = b->b_nofallthrough ? NULL : b;
7317 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007318 eliminate_empty_basic_blocks(a->a_entry);
Om Gc71581c2020-12-16 17:48:05 +05307319 /* Delete jump instructions made redundant by previous step. If a non-empty
7320 block ends with a jump instruction, check if the next non-empty block
7321 reached through normal flow control is the target of that jump. If it
7322 is, then the jump instruction is redundant and can be deleted.
7323 */
Mark Shannon3bd60352021-01-13 12:05:43 +00007324 int maybe_empty_blocks = 0;
Om Gc71581c2020-12-16 17:48:05 +05307325 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
7326 if (b->b_iused > 0) {
7327 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
Mark Shannon802b6452021-02-02 14:59:15 +00007328 if (b_last_instr->i_opcode == JUMP_ABSOLUTE ||
Om Gc71581c2020-12-16 17:48:05 +05307329 b_last_instr->i_opcode == JUMP_FORWARD) {
Mark Shannon3bd60352021-01-13 12:05:43 +00007330 if (b_last_instr->i_target == b->b_next) {
7331 assert(b->b_next->b_iused);
Om Gc71581c2020-12-16 17:48:05 +05307332 b->b_nofallthrough = 0;
Mark Shannon802b6452021-02-02 14:59:15 +00007333 b_last_instr->i_opcode = NOP;
7334 clean_basic_block(b, -1);
7335 maybe_empty_blocks = 1;
Om Gc71581c2020-12-16 17:48:05 +05307336 }
7337 }
7338 }
7339 }
Mark Shannon3bd60352021-01-13 12:05:43 +00007340 if (maybe_empty_blocks) {
7341 eliminate_empty_basic_blocks(a->a_entry);
7342 }
7343 propogate_line_numbers(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01007344 return 0;
7345}
7346
Mark Shannon5977a792020-12-02 13:31:40 +00007347static inline int
7348is_exit_without_lineno(basicblock *b) {
7349 return b->b_exit && b->b_instr[0].i_lineno < 0;
7350}
7351
7352/* PEP 626 mandates that the f_lineno of a frame is correct
7353 * after a frame terminates. It would be prohibitively expensive
7354 * to continuously update the f_lineno field at runtime,
7355 * so we make sure that all exiting instruction (raises and returns)
7356 * have a valid line number, allowing us to compute f_lineno lazily.
7357 * We can do this by duplicating the exit blocks without line number
7358 * so that none have more than one predecessor. We can then safely
7359 * copy the line number from the sole predecessor block.
7360 */
7361static int
7362ensure_exits_have_lineno(struct compiler *c)
7363{
Mark Shannoneaccc122020-12-04 15:22:12 +00007364 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00007365 /* Copy all exit blocks without line number that are targets of a jump.
7366 */
7367 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7368 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
7369 switch (b->b_instr[b->b_iused-1].i_opcode) {
7370 /* Note: Only actual jumps, not exception handlers */
7371 case SETUP_ASYNC_WITH:
7372 case SETUP_WITH:
7373 case SETUP_FINALLY:
7374 continue;
7375 }
7376 basicblock *target = b->b_instr[b->b_iused-1].i_target;
7377 if (is_exit_without_lineno(target)) {
7378 basicblock *new_target = compiler_copy_block(c, target);
7379 if (new_target == NULL) {
7380 return -1;
7381 }
7382 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
7383 b->b_instr[b->b_iused-1].i_target = new_target;
7384 }
7385 }
Mark Shannoneaccc122020-12-04 15:22:12 +00007386 entry = b;
7387 }
7388 assert(entry != NULL);
7389 if (is_exit_without_lineno(entry)) {
7390 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00007391 }
Mark Shannonee9f98d2021-01-05 12:04:10 +00007392 /* Eliminate empty blocks */
7393 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7394 while (b->b_next && b->b_next->b_iused == 0) {
7395 b->b_next = b->b_next->b_next;
7396 }
7397 }
Mark Shannon5977a792020-12-02 13:31:40 +00007398 /* Any remaining reachable exit blocks without line number can only be reached by
7399 * fall through, and thus can only have a single predecessor */
7400 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
7401 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
7402 if (is_exit_without_lineno(b->b_next)) {
7403 assert(b->b_next->b_iused > 0);
7404 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
7405 }
7406 }
7407 }
7408 return 0;
7409}
7410
7411
Mark Shannon6e8128f2020-07-30 10:03:00 +01007412/* Retained for API compatibility.
7413 * Optimization is now done in optimize_cfg */
7414
7415PyObject *
7416PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
7417 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
7418{
7419 Py_INCREF(code);
7420 return code;
7421}