blob: 9927f5abfb964c1910304b01da8e540edb348902 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
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 Stinnerba7a99d2021-01-30 01:46:44 +010025#include "pycore_pymem.h" // _PyMem_IsPtrFreed()
Victor Stinnerc9bc2902020-10-27 02:24:34 +010026#include "pycore_long.h" // _PyLong_GetZero()
Guido van Rossum3f5da241990-12-20 15:06:42 +000027
Ammar Askare92d3932020-01-15 11:48:40 -050028#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000029#include "ast.h"
30#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000031#include "symtable.h"
Mark Shannon582aaf12020-08-04 17:30:11 +010032#define NEED_OPCODE_JUMP_TABLES
Guido van Rossum10dc2e81990-11-18 17:27:39 +000033#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030034#include "wordcode_helpers.h"
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
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100205static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000206static void compiler_free(struct compiler *);
207static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500208static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100210static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100211static int compiler_addop_j(struct compiler *, int, basicblock *);
Mark Shannon127dde52021-01-04 18:06:55 +0000212static int compiler_addop_j_noline(struct compiler *, int, basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200214static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000215static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
216
217static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
218static int compiler_visit_stmt(struct compiler *, stmt_ty);
219static int compiler_visit_keyword(struct compiler *, keyword_ty);
220static int compiler_visit_expr(struct compiler *, expr_ty);
221static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700222static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200223static int compiler_subscript(struct compiler *, expr_ty);
224static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000225
Andy Lester76d58772020-03-10 21:18:12 -0500226static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100227static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Mark Shannon8473cf82020-12-15 11:07:50 +0000228
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000229
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500230static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400231static int compiler_async_with(struct compiler *, stmt_ty, int);
232static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100233static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100234 asdl_expr_seq *args,
235 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500236static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400237static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000238
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700239static int compiler_sync_comprehension_generator(
240 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100241 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200242 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700243 expr_ty elt, expr_ty val, int type);
244
245static int compiler_async_comprehension_generator(
246 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100247 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200248 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700249 expr_ty elt, expr_ty val, int type);
250
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000251static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000252static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000253
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400254#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000255
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000257_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 /* Name mangling: __private becomes _classname__private.
260 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200261 PyObject *result;
262 size_t nlen, plen, ipriv;
263 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200265 PyUnicode_READ_CHAR(ident, 0) != '_' ||
266 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 Py_INCREF(ident);
268 return ident;
269 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200270 nlen = PyUnicode_GET_LENGTH(ident);
271 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 The only time a name with a dot can occur is when
275 we are compiling an import statement that has a
276 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 TODO(jhylton): Decide whether we want to support
279 mangling of the module name, e.g. __M.X.
280 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200281 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
282 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
283 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 Py_INCREF(ident);
285 return ident; /* Don't mangle __whatever__ */
286 }
287 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200288 ipriv = 0;
289 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
290 ipriv++;
291 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 Py_INCREF(ident);
293 return ident; /* Don't mangle if class is just underscores */
294 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200295 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000296
Antoine Pitrou55bff892013-04-06 21:21:04 +0200297 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
298 PyErr_SetString(PyExc_OverflowError,
299 "private identifier too large to be mangled");
300 return NULL;
301 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200303 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
304 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
305 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
306
307 result = PyUnicode_New(1 + nlen + plen, maxchar);
308 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200310 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
311 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200312 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
313 Py_DECREF(result);
314 return NULL;
315 }
316 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
317 Py_DECREF(result);
318 return NULL;
319 }
Victor Stinner8f825062012-04-27 13:55:39 +0200320 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200321 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000322}
323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000324static int
325compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000328
INADA Naokic2e16072018-11-26 21:23:22 +0900329 c->c_const_cache = PyDict_New();
330 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900332 }
333
334 c->c_stack = PyList_New(0);
335 if (!c->c_stack) {
336 Py_CLEAR(c->c_const_cache);
337 return 0;
338 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000341}
342
343PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200344PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
345 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 struct compiler c;
348 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200349 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (!__doc__) {
353 __doc__ = PyUnicode_InternFromString("__doc__");
354 if (!__doc__)
355 return NULL;
356 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000357 if (!__annotations__) {
358 __annotations__ = PyUnicode_InternFromString("__annotations__");
359 if (!__annotations__)
360 return NULL;
361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (!compiler_init(&c))
363 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200364 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 c.c_filename = filename;
366 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200367 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (c.c_future == NULL)
369 goto finally;
370 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 flags = &local_flags;
372 }
373 merged = c.c_future->ff_features | flags->cf_flags;
374 c.c_future->ff_features = merged;
375 flags->cf_flags = merged;
376 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200377 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000379
Pablo Galindod112c602020-03-18 23:02:09 +0000380 _PyASTOptimizeState state;
381 state.optimize = c.c_optimize;
382 state.ff_features = merged;
383
384 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900385 goto finally;
386 }
387
Victor Stinner14e461d2013-08-26 22:28:21 +0200388 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (c.c_st == NULL) {
390 if (!PyErr_Occurred())
391 PyErr_SetString(PyExc_SystemError, "no symtable");
392 goto finally;
393 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396
Thomas Wouters1175c432006-02-27 22:49:54 +0000397 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 compiler_free(&c);
399 assert(co || PyErr_Occurred());
400 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000401}
402
403PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200404PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
405 int optimize, PyArena *arena)
406{
407 PyObject *filename;
408 PyCodeObject *co;
409 filename = PyUnicode_DecodeFSDefault(filename_str);
410 if (filename == NULL)
411 return NULL;
412 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
413 Py_DECREF(filename);
414 return co;
415
416}
417
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000418static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000419compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 if (c->c_st)
422 PySymtable_Free(c->c_st);
423 if (c->c_future)
424 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200425 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900426 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000428}
429
Guido van Rossum79f25d91997-04-29 20:08:16 +0000430static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000431list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 Py_ssize_t i, n;
434 PyObject *v, *k;
435 PyObject *dict = PyDict_New();
436 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 n = PyList_Size(list);
439 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100440 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (!v) {
442 Py_DECREF(dict);
443 return NULL;
444 }
445 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300446 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 Py_DECREF(v);
448 Py_DECREF(dict);
449 return NULL;
450 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 Py_DECREF(v);
452 }
453 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000454}
455
456/* Return new dict containing names from src that match scope(s).
457
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000458src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000460values are integers, starting at offset and increasing by one for
461each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000462*/
463
464static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100465dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700467 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500469 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 assert(offset >= 0);
472 if (dest == NULL)
473 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474
Meador Inge2ca63152012-07-18 14:20:11 -0500475 /* Sort the keys so that we have a deterministic order on the indexes
476 saved in the returned dictionary. These indexes are used as indexes
477 into the free and cell var storage. Therefore if they aren't
478 deterministic, then the generated bytecode is not deterministic.
479 */
480 sorted_keys = PyDict_Keys(src);
481 if (sorted_keys == NULL)
482 return NULL;
483 if (PyList_Sort(sorted_keys) != 0) {
484 Py_DECREF(sorted_keys);
485 return NULL;
486 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500487 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500488
489 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* XXX this should probably be a macro in symtable.h */
491 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500492 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200493 v = PyDict_GetItemWithError(src, k);
494 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 vi = PyLong_AS_LONG(v);
496 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300499 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500501 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 Py_DECREF(dest);
503 return NULL;
504 }
505 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300506 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500507 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 Py_DECREF(item);
509 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return NULL;
511 }
512 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 }
514 }
Meador Inge2ca63152012-07-18 14:20:11 -0500515 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000517}
518
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000519static void
520compiler_unit_check(struct compiler_unit *u)
521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 basicblock *block;
523 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +0100524 assert(!_PyMem_IsPtrFreed(block));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (block->b_instr != NULL) {
526 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100527 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 assert(block->b_ialloc >= block->b_iused);
529 }
530 else {
531 assert (block->b_iused == 0);
532 assert (block->b_ialloc == 0);
533 }
534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535}
536
537static void
538compiler_unit_free(struct compiler_unit *u)
539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 compiler_unit_check(u);
543 b = u->u_blocks;
544 while (b != NULL) {
545 if (b->b_instr)
546 PyObject_Free((void *)b->b_instr);
547 next = b->b_list;
548 PyObject_Free((void *)b);
549 b = next;
550 }
551 Py_CLEAR(u->u_ste);
552 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400553 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 Py_CLEAR(u->u_consts);
555 Py_CLEAR(u->u_names);
556 Py_CLEAR(u->u_varnames);
557 Py_CLEAR(u->u_freevars);
558 Py_CLEAR(u->u_cellvars);
559 Py_CLEAR(u->u_private);
560 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561}
562
563static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100564compiler_enter_scope(struct compiler *c, identifier name,
565 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100568 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000569
Andy Lester7668a8b2020-03-24 23:26:44 -0500570 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 struct compiler_unit));
572 if (!u) {
573 PyErr_NoMemory();
574 return 0;
575 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100576 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100578 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 u->u_kwonlyargcount = 0;
580 u->u_ste = PySymtable_Lookup(c->c_st, key);
581 if (!u->u_ste) {
582 compiler_unit_free(u);
583 return 0;
584 }
585 Py_INCREF(name);
586 u->u_name = name;
587 u->u_varnames = list2dict(u->u_ste->ste_varnames);
588 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
589 if (!u->u_varnames || !u->u_cellvars) {
590 compiler_unit_free(u);
591 return 0;
592 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500593 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000594 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500595 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300596 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500597 int res;
598 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200599 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500600 name = _PyUnicode_FromId(&PyId___class__);
601 if (!name) {
602 compiler_unit_free(u);
603 return 0;
604 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100605 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500606 if (res < 0) {
607 compiler_unit_free(u);
608 return 0;
609 }
610 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200613 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (!u->u_freevars) {
615 compiler_unit_free(u);
616 return 0;
617 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 u->u_blocks = NULL;
620 u->u_nfblocks = 0;
621 u->u_firstlineno = lineno;
622 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000623 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 u->u_consts = PyDict_New();
625 if (!u->u_consts) {
626 compiler_unit_free(u);
627 return 0;
628 }
629 u->u_names = PyDict_New();
630 if (!u->u_names) {
631 compiler_unit_free(u);
632 return 0;
633 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 /* Push the old compiler_unit on the stack. */
638 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400639 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
641 Py_XDECREF(capsule);
642 compiler_unit_free(u);
643 return 0;
644 }
645 Py_DECREF(capsule);
646 u->u_private = c->u->u_private;
647 Py_XINCREF(u->u_private);
648 }
649 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100652
653 block = compiler_new_block(c);
654 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100656 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400658 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
659 if (!compiler_set_qualname(c))
660 return 0;
661 }
662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664}
665
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000666static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667compiler_exit_scope(struct compiler *c)
668{
Victor Stinnera6192632021-01-29 16:53:03 +0100669 // Don't call PySequence_DelItem() with an exception raised
670 PyObject *exc_type, *exc_val, *exc_tb;
671 PyErr_Fetch(&exc_type, &exc_val, &exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 c->c_nestlevel--;
674 compiler_unit_free(c->u);
675 /* Restore c->u to the parent unit. */
Victor Stinnera6192632021-01-29 16:53:03 +0100676 Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (n >= 0) {
Victor Stinnera6192632021-01-29 16:53:03 +0100678 PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400679 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 assert(c->u);
681 /* we are deleting from a list so this really shouldn't fail */
Victor Stinnera6192632021-01-29 16:53:03 +0100682 if (PySequence_DelItem(c->c_stack, n) < 0) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +0100683 _PyErr_WriteUnraisableMsg("on removing the last compiler "
684 "stack item", NULL);
Victor Stinnera6192632021-01-29 16:53:03 +0100685 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 compiler_unit_check(c->u);
687 }
Victor Stinnera6192632021-01-29 16:53:03 +0100688 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 c->u = NULL;
Victor Stinnera6192632021-01-29 16:53:03 +0100690 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000691
Victor Stinnera6192632021-01-29 16:53:03 +0100692 PyErr_Restore(exc_type, exc_val, exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000693}
694
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400695static int
696compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100697{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 _Py_static_string(dot_locals, ".<locals>");
700 Py_ssize_t stack_size;
701 struct compiler_unit *u = c->u;
702 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100703
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400704 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100705 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400706 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400707 if (stack_size > 1) {
708 int scope, force_global = 0;
709 struct compiler_unit *parent;
710 PyObject *mangled, *capsule;
711
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400712 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400713 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400714 assert(parent);
715
Yury Selivanov75445082015-05-11 22:57:16 -0400716 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
717 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
718 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400719 assert(u->u_name);
720 mangled = _Py_Mangle(parent->u_private, u->u_name);
721 if (!mangled)
722 return 0;
723 scope = PyST_GetScope(parent->u_ste, mangled);
724 Py_DECREF(mangled);
725 assert(scope != GLOBAL_IMPLICIT);
726 if (scope == GLOBAL_EXPLICIT)
727 force_global = 1;
728 }
729
730 if (!force_global) {
731 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400732 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400733 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
734 dot_locals_str = _PyUnicode_FromId(&dot_locals);
735 if (dot_locals_str == NULL)
736 return 0;
737 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
738 if (base == NULL)
739 return 0;
740 }
741 else {
742 Py_INCREF(parent->u_qualname);
743 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400744 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100745 }
746 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400747
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400748 if (base != NULL) {
749 dot_str = _PyUnicode_FromId(&dot);
750 if (dot_str == NULL) {
751 Py_DECREF(base);
752 return 0;
753 }
754 name = PyUnicode_Concat(base, dot_str);
755 Py_DECREF(base);
756 if (name == NULL)
757 return 0;
758 PyUnicode_Append(&name, u->u_name);
759 if (name == NULL)
760 return 0;
761 }
762 else {
763 Py_INCREF(u->u_name);
764 name = u->u_name;
765 }
766 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100767
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400768 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100769}
770
Eric V. Smith235a6f02015-09-19 14:51:32 -0400771
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000772/* Allocate a new block and return a pointer to it.
773 Returns NULL on error.
774*/
775
776static basicblock *
777compiler_new_block(struct compiler *c)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 basicblock *b;
780 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500783 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (b == NULL) {
785 PyErr_NoMemory();
786 return NULL;
787 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 /* Extend the singly linked list of blocks with new block. */
789 b->b_list = u->u_blocks;
790 u->u_blocks = b;
791 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000792}
793
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000794static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795compiler_next_block(struct compiler *c)
796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 basicblock *block = compiler_new_block(c);
798 if (block == NULL)
799 return NULL;
800 c->u->u_curblock->b_next = block;
801 c->u->u_curblock = block;
802 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000803}
804
805static basicblock *
806compiler_use_next_block(struct compiler *c, basicblock *block)
807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 assert(block != NULL);
809 c->u->u_curblock->b_next = block;
810 c->u->u_curblock = block;
811 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000812}
813
Mark Shannon5977a792020-12-02 13:31:40 +0000814static basicblock *
815compiler_copy_block(struct compiler *c, basicblock *block)
816{
817 /* Cannot copy a block if it has a fallthrough, since
818 * a block can only have one fallthrough predecessor.
819 */
820 assert(block->b_nofallthrough);
821 basicblock *result = compiler_next_block(c);
822 if (result == NULL) {
823 return NULL;
824 }
825 for (int i = 0; i < block->b_iused; i++) {
826 int n = compiler_next_instr(result);
827 if (n < 0) {
828 return NULL;
829 }
830 result->b_instr[n] = block->b_instr[i];
831 }
832 result->b_exit = block->b_exit;
Mark Shannon3bd60352021-01-13 12:05:43 +0000833 result->b_nofallthrough = 1;
Mark Shannon5977a792020-12-02 13:31:40 +0000834 return result;
835}
836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837/* Returns the offset of the next instruction in the current block's
838 b_instr array. Resizes the b_instr as necessary.
839 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000840*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841
842static int
Andy Lester76d58772020-03-10 21:18:12 -0500843compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 assert(b != NULL);
846 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500847 b->b_instr = (struct instr *)PyObject_Calloc(
848 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (b->b_instr == NULL) {
850 PyErr_NoMemory();
851 return -1;
852 }
853 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 }
855 else if (b->b_iused == b->b_ialloc) {
856 struct instr *tmp;
857 size_t oldsize, newsize;
858 oldsize = b->b_ialloc * sizeof(struct instr);
859 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000860
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700861 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyErr_NoMemory();
863 return -1;
864 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (newsize == 0) {
867 PyErr_NoMemory();
868 return -1;
869 }
870 b->b_ialloc <<= 1;
871 tmp = (struct instr *)PyObject_Realloc(
872 (void *)b->b_instr, newsize);
873 if (tmp == NULL) {
874 PyErr_NoMemory();
875 return -1;
876 }
877 b->b_instr = tmp;
878 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
879 }
880 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000881}
882
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200883/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000884
Christian Heimes2202f872008-02-06 14:31:34 +0000885 The line number is reset in the following cases:
886 - when entering a new scope
887 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200888 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200889 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200892#define SET_LOC(c, x) \
893 (c)->u->u_lineno = (x)->lineno; \
894 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200896/* Return the stack effect of opcode with argument oparg.
897
898 Some opcodes have different stack effect when jump to the target and
899 when not jump. The 'jump' parameter specifies the case:
900
901 * 0 -- when not jump
902 * 1 -- when jump
903 * -1 -- maximal
904 */
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200905static int
906stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300909 case NOP:
910 case EXTENDED_ARG:
911 return 0;
912
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200913 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 case POP_TOP:
915 return -1;
916 case ROT_TWO:
917 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200918 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 return 0;
920 case DUP_TOP:
921 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000922 case DUP_TOP_TWO:
923 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200925 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 case UNARY_POSITIVE:
927 case UNARY_NEGATIVE:
928 case UNARY_NOT:
929 case UNARY_INVERT:
930 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 case SET_ADD:
933 case LIST_APPEND:
934 return -1;
935 case MAP_ADD:
936 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000937
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200938 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 case BINARY_POWER:
940 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400941 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 case BINARY_MODULO:
943 case BINARY_ADD:
944 case BINARY_SUBTRACT:
945 case BINARY_SUBSCR:
946 case BINARY_FLOOR_DIVIDE:
947 case BINARY_TRUE_DIVIDE:
948 return -1;
949 case INPLACE_FLOOR_DIVIDE:
950 case INPLACE_TRUE_DIVIDE:
951 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case INPLACE_ADD:
954 case INPLACE_SUBTRACT:
955 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400956 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case INPLACE_MODULO:
958 return -1;
959 case STORE_SUBSCR:
960 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 case DELETE_SUBSCR:
962 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 case BINARY_LSHIFT:
965 case BINARY_RSHIFT:
966 case BINARY_AND:
967 case BINARY_XOR:
968 case BINARY_OR:
969 return -1;
970 case INPLACE_POWER:
971 return -1;
972 case GET_ITER:
973 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 case PRINT_EXPR:
976 return -1;
977 case LOAD_BUILD_CLASS:
978 return 1;
979 case INPLACE_LSHIFT:
980 case INPLACE_RSHIFT:
981 case INPLACE_AND:
982 case INPLACE_XOR:
983 case INPLACE_OR:
984 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200987 /* 1 in the normal flow.
988 * Restore the stack position and push 6 values before jumping to
989 * the handler if an exception be raised. */
990 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 case RETURN_VALUE:
992 return -1;
993 case IMPORT_STAR:
994 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700995 case SETUP_ANNOTATIONS:
996 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case YIELD_VALUE:
998 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500999 case YIELD_FROM:
1000 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 case POP_BLOCK:
1002 return 0;
1003 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001004 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 case STORE_NAME:
1007 return -1;
1008 case DELETE_NAME:
1009 return 0;
1010 case UNPACK_SEQUENCE:
1011 return oparg-1;
1012 case UNPACK_EX:
1013 return (oparg&0xFF) + (oparg>>8);
1014 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001015 /* -1 at end of iterator, 1 if continue iterating. */
1016 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 case STORE_ATTR:
1019 return -2;
1020 case DELETE_ATTR:
1021 return -1;
1022 case STORE_GLOBAL:
1023 return -1;
1024 case DELETE_GLOBAL:
1025 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 case LOAD_CONST:
1027 return 1;
1028 case LOAD_NAME:
1029 return 1;
1030 case BUILD_TUPLE:
1031 case BUILD_LIST:
1032 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001033 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 return 1-oparg;
1035 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001036 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001037 case BUILD_CONST_KEY_MAP:
1038 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 case LOAD_ATTR:
1040 return 0;
1041 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001042 case IS_OP:
1043 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001045 case JUMP_IF_NOT_EXC_MATCH:
1046 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 case IMPORT_NAME:
1048 return -1;
1049 case IMPORT_FROM:
1050 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001051
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001052 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 case JUMP_ABSOLUTE:
1055 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001057 case JUMP_IF_TRUE_OR_POP:
1058 case JUMP_IF_FALSE_OR_POP:
1059 return jump ? 0 : -1;
1060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 case POP_JUMP_IF_FALSE:
1062 case POP_JUMP_IF_TRUE:
1063 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case LOAD_GLOBAL:
1066 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001067
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001068 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001070 /* 0 in the normal flow.
1071 * Restore the stack position and push 6 values before jumping to
1072 * the handler if an exception be raised. */
1073 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001074 case RERAISE:
1075 return -3;
1076
1077 case WITH_EXCEPT_START:
1078 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 case LOAD_FAST:
1081 return 1;
1082 case STORE_FAST:
1083 return -1;
1084 case DELETE_FAST:
1085 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case RAISE_VARARGS:
1088 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001089
1090 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001092 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001093 case CALL_METHOD:
1094 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001096 return -oparg-1;
1097 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001098 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001099 case MAKE_FUNCTION:
1100 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1101 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 case BUILD_SLICE:
1103 if (oparg == 3)
1104 return -2;
1105 else
1106 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001107
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001108 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 case LOAD_CLOSURE:
1110 return 1;
1111 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001112 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 return 1;
1114 case STORE_DEREF:
1115 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001116 case DELETE_DEREF:
1117 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001118
1119 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001120 case GET_AWAITABLE:
1121 return 0;
1122 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001123 /* 0 in the normal flow.
1124 * Restore the stack position to the position before the result
1125 * of __aenter__ and push 6 values before jumping to the handler
1126 * if an exception be raised. */
1127 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001128 case BEFORE_ASYNC_WITH:
1129 return 1;
1130 case GET_AITER:
1131 return 0;
1132 case GET_ANEXT:
1133 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001134 case GET_YIELD_FROM_ITER:
1135 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001136 case END_ASYNC_FOR:
1137 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001138 case FORMAT_VALUE:
1139 /* If there's a fmt_spec on the stack, we go from 2->1,
1140 else 1->1. */
1141 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001142 case LOAD_METHOD:
1143 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001144 case LOAD_ASSERTION_ERROR:
1145 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001146 case LIST_TO_TUPLE:
1147 return 0;
1148 case LIST_EXTEND:
1149 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001150 case DICT_MERGE:
1151 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001152 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001154 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 }
Larry Hastings3a907972013-11-23 14:49:22 -08001156 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001157}
1158
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001159int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001160PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1161{
1162 return stack_effect(opcode, oparg, jump);
1163}
1164
1165int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001166PyCompile_OpcodeStackEffect(int opcode, int oparg)
1167{
1168 return stack_effect(opcode, oparg, -1);
1169}
1170
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001171/* Add an opcode with no argument.
1172 Returns 0 on failure, 1 on success.
1173*/
1174
1175static int
Mark Shannon3bd60352021-01-13 12:05:43 +00001176compiler_addop_line(struct compiler *c, int opcode, int line)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 basicblock *b;
1179 struct instr *i;
1180 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001181 assert(!HAS_ARG(opcode));
Andy Lester76d58772020-03-10 21:18:12 -05001182 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (off < 0)
1184 return 0;
1185 b = c->u->u_curblock;
1186 i = &b->b_instr[off];
1187 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001188 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (opcode == RETURN_VALUE)
1190 b->b_return = 1;
Mark Shannon3bd60352021-01-13 12:05:43 +00001191 i->i_lineno = line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193}
1194
Mark Shannon3bd60352021-01-13 12:05:43 +00001195static int
1196compiler_addop(struct compiler *c, int opcode)
1197{
1198 return compiler_addop_line(c, opcode, c->u->u_lineno);
1199}
1200
1201static int
1202compiler_addop_noline(struct compiler *c, int opcode)
1203{
1204 return compiler_addop_line(c, opcode, -1);
1205}
1206
1207
Victor Stinnerf8e32212013-11-19 23:56:34 +01001208static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001209compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001210{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001211 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001213
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001214 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001216 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001218 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001219 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001220 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 return -1;
1223 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001224 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 Py_DECREF(v);
1226 return -1;
1227 }
1228 Py_DECREF(v);
1229 }
1230 else
1231 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001232 return arg;
1233}
1234
INADA Naokic2e16072018-11-26 21:23:22 +09001235// Merge const *o* recursively and return constant key object.
1236static PyObject*
1237merge_consts_recursive(struct compiler *c, PyObject *o)
1238{
1239 // None and Ellipsis are singleton, and key is the singleton.
1240 // No need to merge object and key.
1241 if (o == Py_None || o == Py_Ellipsis) {
1242 Py_INCREF(o);
1243 return o;
1244 }
1245
1246 PyObject *key = _PyCode_ConstantKey(o);
1247 if (key == NULL) {
1248 return NULL;
1249 }
1250
1251 // t is borrowed reference
1252 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1253 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001254 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001255 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001256 Py_DECREF(key);
1257 return t;
1258 }
1259
INADA Naokif7e4d362018-11-29 00:58:46 +09001260 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001261 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001262 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001263 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001264 Py_ssize_t len = PyTuple_GET_SIZE(o);
1265 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001266 PyObject *item = PyTuple_GET_ITEM(o, i);
1267 PyObject *u = merge_consts_recursive(c, item);
1268 if (u == NULL) {
1269 Py_DECREF(key);
1270 return NULL;
1271 }
1272
1273 // See _PyCode_ConstantKey()
1274 PyObject *v; // borrowed
1275 if (PyTuple_CheckExact(u)) {
1276 v = PyTuple_GET_ITEM(u, 1);
1277 }
1278 else {
1279 v = u;
1280 }
1281 if (v != item) {
1282 Py_INCREF(v);
1283 PyTuple_SET_ITEM(o, i, v);
1284 Py_DECREF(item);
1285 }
1286
1287 Py_DECREF(u);
1288 }
1289 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001290 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001291 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001292 // constant keys.
1293 // See _PyCode_ConstantKey() for detail.
1294 assert(PyTuple_CheckExact(key));
1295 assert(PyTuple_GET_SIZE(key) == 2);
1296
1297 Py_ssize_t len = PySet_GET_SIZE(o);
1298 if (len == 0) { // empty frozenset should not be re-created.
1299 return key;
1300 }
1301 PyObject *tuple = PyTuple_New(len);
1302 if (tuple == NULL) {
1303 Py_DECREF(key);
1304 return NULL;
1305 }
1306 Py_ssize_t i = 0, pos = 0;
1307 PyObject *item;
1308 Py_hash_t hash;
1309 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1310 PyObject *k = merge_consts_recursive(c, item);
1311 if (k == NULL) {
1312 Py_DECREF(tuple);
1313 Py_DECREF(key);
1314 return NULL;
1315 }
1316 PyObject *u;
1317 if (PyTuple_CheckExact(k)) {
1318 u = PyTuple_GET_ITEM(k, 1);
1319 Py_INCREF(u);
1320 Py_DECREF(k);
1321 }
1322 else {
1323 u = k;
1324 }
1325 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1326 i++;
1327 }
1328
1329 // Instead of rewriting o, we create new frozenset and embed in the
1330 // key tuple. Caller should get merged frozenset from the key tuple.
1331 PyObject *new = PyFrozenSet_New(tuple);
1332 Py_DECREF(tuple);
1333 if (new == NULL) {
1334 Py_DECREF(key);
1335 return NULL;
1336 }
1337 assert(PyTuple_GET_ITEM(key, 1) == o);
1338 Py_DECREF(o);
1339 PyTuple_SET_ITEM(key, 1, new);
1340 }
INADA Naokic2e16072018-11-26 21:23:22 +09001341
1342 return key;
1343}
1344
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001345static Py_ssize_t
1346compiler_add_const(struct compiler *c, PyObject *o)
1347{
INADA Naokic2e16072018-11-26 21:23:22 +09001348 PyObject *key = merge_consts_recursive(c, o);
1349 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001350 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001351 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001352
Andy Lester76d58772020-03-10 21:18:12 -05001353 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001354 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356}
1357
1358static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001359compiler_addop_load_const(struct compiler *c, PyObject *o)
1360{
1361 Py_ssize_t arg = compiler_add_const(c, o);
1362 if (arg < 0)
1363 return 0;
1364 return compiler_addop_i(c, LOAD_CONST, arg);
1365}
1366
1367static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370{
Andy Lester76d58772020-03-10 21:18:12 -05001371 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001372 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001373 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001374 return compiler_addop_i(c, opcode, arg);
1375}
1376
1377static int
1378compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001381 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001382
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1384 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001385 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001386 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001387 Py_DECREF(mangled);
1388 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001389 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001390 return compiler_addop_i(c, opcode, arg);
1391}
1392
1393/* Add an opcode with an integer argument.
1394 Returns 0 on failure, 1 on success.
1395*/
1396
1397static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001398compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 struct instr *i;
1401 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001402
Victor Stinner2ad474b2016-03-01 23:34:47 +01001403 /* oparg value is unsigned, but a signed C int is usually used to store
1404 it in the C code (like Python/ceval.c).
1405
1406 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1407
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001408 The argument of a concrete bytecode instruction is limited to 8-bit.
1409 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1410 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001411 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001412
Andy Lester76d58772020-03-10 21:18:12 -05001413 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (off < 0)
1415 return 0;
1416 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001417 i->i_opcode = opcode;
1418 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001419 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001421}
1422
Mark Shannon28b75c82020-12-23 11:43:10 +00001423static int add_jump_to_block(basicblock *b, int opcode, int lineno, basicblock *target)
1424{
1425 assert(HAS_ARG(opcode));
1426 assert(b != NULL);
1427 assert(target != NULL);
1428
1429 int off = compiler_next_instr(b);
1430 struct instr *i = &b->b_instr[off];
1431 if (off < 0) {
1432 return 0;
1433 }
1434 i->i_opcode = opcode;
1435 i->i_target = target;
1436 i->i_lineno = lineno;
1437 return 1;
1438}
1439
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001441compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442{
Mark Shannon28b75c82020-12-23 11:43:10 +00001443 return add_jump_to_block(c->u->u_curblock, opcode, c->u->u_lineno, b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444}
1445
Mark Shannon127dde52021-01-04 18:06:55 +00001446static int
1447compiler_addop_j_noline(struct compiler *c, int opcode, basicblock *b)
1448{
1449 return add_jump_to_block(c->u->u_curblock, opcode, -1, b);
1450}
1451
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001452/* NEXT_BLOCK() creates an implicit jump from the current block
1453 to the new block.
1454
1455 The returns inside this macro make it impossible to decref objects
1456 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001458#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (compiler_next_block((C)) == NULL) \
1460 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001461}
1462
1463#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 if (!compiler_addop((C), (OP))) \
1465 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466}
1467
Mark Shannon3bd60352021-01-13 12:05:43 +00001468#define ADDOP_NOLINE(C, OP) { \
1469 if (!compiler_addop_noline((C), (OP))) \
1470 return 0; \
1471}
1472
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001473#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (!compiler_addop((C), (OP))) { \
1475 compiler_exit_scope(c); \
1476 return 0; \
1477 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001478}
1479
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001480#define ADDOP_LOAD_CONST(C, O) { \
1481 if (!compiler_addop_load_const((C), (O))) \
1482 return 0; \
1483}
1484
1485/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1486#define ADDOP_LOAD_CONST_NEW(C, O) { \
1487 PyObject *__new_const = (O); \
1488 if (__new_const == NULL) { \
1489 return 0; \
1490 } \
1491 if (!compiler_addop_load_const((C), __new_const)) { \
1492 Py_DECREF(__new_const); \
1493 return 0; \
1494 } \
1495 Py_DECREF(__new_const); \
1496}
1497
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1500 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501}
1502
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001503/* Same as ADDOP_O, but steals a reference. */
1504#define ADDOP_N(C, OP, O, TYPE) { \
1505 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1506 Py_DECREF((O)); \
1507 return 0; \
1508 } \
1509 Py_DECREF((O)); \
1510}
1511
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1514 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515}
1516
1517#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (!compiler_addop_i((C), (OP), (O))) \
1519 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
Mark Shannon582aaf12020-08-04 17:30:11 +01001522#define ADDOP_JUMP(C, OP, O) { \
1523 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525}
1526
Mark Shannon127dde52021-01-04 18:06:55 +00001527/* Add a jump with no line number.
1528 * Used for artificial jumps that have no corresponding
1529 * token in the source code. */
1530#define ADDOP_JUMP_NOLINE(C, OP, O) { \
1531 if (!compiler_addop_j_noline((C), (OP), (O))) \
1532 return 0; \
1533}
1534
Mark Shannon9af0e472020-01-14 10:12:45 +00001535#define ADDOP_COMPARE(C, CMP) { \
1536 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1537 return 0; \
1538}
1539
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001540/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1541 the ASDL name to synthesize the name of the C type and the visit function.
1542*/
1543
1544#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (!compiler_visit_ ## TYPE((C), (V))) \
1546 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547}
1548
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001549#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (!compiler_visit_ ## TYPE((C), (V))) { \
1551 compiler_exit_scope(c); \
1552 return 0; \
1553 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001554}
1555
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001556#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 if (!compiler_visit_slice((C), (V), (CTX))) \
1558 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001559}
1560
1561#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001563 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1565 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1566 if (!compiler_visit_ ## TYPE((C), elt)) \
1567 return 0; \
1568 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001569}
1570
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001571#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001573 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1575 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1576 if (!compiler_visit_ ## TYPE((C), elt)) { \
1577 compiler_exit_scope(c); \
1578 return 0; \
1579 } \
1580 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001581}
1582
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001583/* Search if variable annotations are present statically in a block. */
1584
1585static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001586find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001587{
1588 int i, j, res = 0;
1589 stmt_ty st;
1590
1591 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1592 st = (stmt_ty)asdl_seq_GET(stmts, i);
1593 switch (st->kind) {
1594 case AnnAssign_kind:
1595 return 1;
1596 case For_kind:
1597 res = find_ann(st->v.For.body) ||
1598 find_ann(st->v.For.orelse);
1599 break;
1600 case AsyncFor_kind:
1601 res = find_ann(st->v.AsyncFor.body) ||
1602 find_ann(st->v.AsyncFor.orelse);
1603 break;
1604 case While_kind:
1605 res = find_ann(st->v.While.body) ||
1606 find_ann(st->v.While.orelse);
1607 break;
1608 case If_kind:
1609 res = find_ann(st->v.If.body) ||
1610 find_ann(st->v.If.orelse);
1611 break;
1612 case With_kind:
1613 res = find_ann(st->v.With.body);
1614 break;
1615 case AsyncWith_kind:
1616 res = find_ann(st->v.AsyncWith.body);
1617 break;
1618 case Try_kind:
1619 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1620 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1621 st->v.Try.handlers, j);
1622 if (find_ann(handler->v.ExceptHandler.body)) {
1623 return 1;
1624 }
1625 }
1626 res = find_ann(st->v.Try.body) ||
1627 find_ann(st->v.Try.finalbody) ||
1628 find_ann(st->v.Try.orelse);
1629 break;
1630 default:
1631 res = 0;
1632 }
1633 if (res) {
1634 break;
1635 }
1636 }
1637 return res;
1638}
1639
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001640/*
1641 * Frame block handling functions
1642 */
1643
1644static int
1645compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001646 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001647{
1648 struct fblockinfo *f;
1649 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001650 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001651 }
1652 f = &c->u->u_fblock[c->u->u_nfblocks++];
1653 f->fb_type = t;
1654 f->fb_block = b;
1655 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001656 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001657 return 1;
1658}
1659
1660static void
1661compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1662{
1663 struct compiler_unit *u = c->u;
1664 assert(u->u_nfblocks > 0);
1665 u->u_nfblocks--;
1666 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1667 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1668}
1669
Mark Shannonfee55262019-11-21 09:11:43 +00001670static int
1671compiler_call_exit_with_nones(struct compiler *c) {
1672 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1673 ADDOP(c, DUP_TOP);
1674 ADDOP(c, DUP_TOP);
1675 ADDOP_I(c, CALL_FUNCTION, 3);
1676 return 1;
1677}
1678
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001679/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001680 * popping the blocks will be restored afterwards, unless another
1681 * return, break or continue is found. In which case, the TOS will
1682 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001683 */
1684static int
1685compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1686 int preserve_tos)
1687{
1688 switch (info->fb_type) {
1689 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001690 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001691 return 1;
1692
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001693 case FOR_LOOP:
1694 /* Pop the iterator */
1695 if (preserve_tos) {
1696 ADDOP(c, ROT_TWO);
1697 }
1698 ADDOP(c, POP_TOP);
1699 return 1;
1700
Mark Shannon02d126a2020-09-25 14:04:19 +01001701 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001702 ADDOP(c, POP_BLOCK);
1703 return 1;
1704
1705 case FINALLY_TRY:
Mark Shannon5274b682020-12-16 13:07:01 +00001706 /* This POP_BLOCK gets the line number of the unwinding statement */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001707 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001708 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001709 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1710 return 0;
1711 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001712 }
Mark Shannon5274b682020-12-16 13:07:01 +00001713 /* Emit the finally block */
Mark Shannonfee55262019-11-21 09:11:43 +00001714 VISIT_SEQ(c, stmt, info->fb_datum);
1715 if (preserve_tos) {
1716 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001717 }
Mark Shannon5274b682020-12-16 13:07:01 +00001718 /* The finally block should appear to execute after the
1719 * statement causing the unwinding, so make the unwinding
1720 * instruction artificial */
1721 c->u->u_lineno = -1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001722 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001723
Mark Shannonfee55262019-11-21 09:11:43 +00001724 case FINALLY_END:
1725 if (preserve_tos) {
1726 ADDOP(c, ROT_FOUR);
1727 }
1728 ADDOP(c, POP_TOP);
1729 ADDOP(c, POP_TOP);
1730 ADDOP(c, POP_TOP);
1731 if (preserve_tos) {
1732 ADDOP(c, ROT_FOUR);
1733 }
1734 ADDOP(c, POP_EXCEPT);
1735 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001736
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001737 case WITH:
1738 case ASYNC_WITH:
1739 ADDOP(c, POP_BLOCK);
1740 if (preserve_tos) {
1741 ADDOP(c, ROT_TWO);
1742 }
Mark Shannonfee55262019-11-21 09:11:43 +00001743 if(!compiler_call_exit_with_nones(c)) {
1744 return 0;
1745 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001746 if (info->fb_type == ASYNC_WITH) {
1747 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001748 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001749 ADDOP(c, YIELD_FROM);
1750 }
Mark Shannonfee55262019-11-21 09:11:43 +00001751 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001752 return 1;
1753
1754 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001755 if (info->fb_datum) {
1756 ADDOP(c, POP_BLOCK);
1757 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001758 if (preserve_tos) {
1759 ADDOP(c, ROT_FOUR);
1760 }
Mark Shannonfee55262019-11-21 09:11:43 +00001761 ADDOP(c, POP_EXCEPT);
1762 if (info->fb_datum) {
1763 ADDOP_LOAD_CONST(c, Py_None);
1764 compiler_nameop(c, info->fb_datum, Store);
1765 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001766 }
Mark Shannonfee55262019-11-21 09:11:43 +00001767 return 1;
1768
1769 case POP_VALUE:
1770 if (preserve_tos) {
1771 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001772 }
Mark Shannonfee55262019-11-21 09:11:43 +00001773 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001774 return 1;
1775 }
1776 Py_UNREACHABLE();
1777}
1778
Mark Shannonfee55262019-11-21 09:11:43 +00001779/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1780static int
1781compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1782 if (c->u->u_nfblocks == 0) {
1783 return 1;
1784 }
1785 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1786 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1787 *loop = top;
1788 return 1;
1789 }
1790 struct fblockinfo copy = *top;
1791 c->u->u_nfblocks--;
1792 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1793 return 0;
1794 }
1795 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1796 return 0;
1797 }
1798 c->u->u_fblock[c->u->u_nfblocks] = copy;
1799 c->u->u_nfblocks++;
1800 return 1;
1801}
1802
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001803/* Compile a sequence of statements, checking for a docstring
1804 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805
1806static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001807compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001809 int i = 0;
1810 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001811 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001812
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001813 /* Set current line number to the line number of first statement.
1814 This way line number for SETUP_ANNOTATIONS will always
1815 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301816 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001817 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001818 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001819 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001820 }
1821 /* Every annotated class and module should have __annotations__. */
1822 if (find_ann(stmts)) {
1823 ADDOP(c, SETUP_ANNOTATIONS);
1824 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001825 if (!asdl_seq_LEN(stmts))
1826 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001827 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001828 if (c->c_optimize < 2) {
1829 docstring = _PyAST_GetDocString(stmts);
1830 if (docstring) {
1831 i = 1;
1832 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1833 assert(st->kind == Expr_kind);
1834 VISIT(c, expr, st->v.Expr.value);
1835 if (!compiler_nameop(c, __doc__, Store))
1836 return 0;
1837 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001839 for (; i < asdl_seq_LEN(stmts); i++)
1840 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842}
1843
1844static PyCodeObject *
1845compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 PyCodeObject *co;
1848 int addNone = 1;
1849 static PyObject *module;
1850 if (!module) {
1851 module = PyUnicode_InternFromString("<module>");
1852 if (!module)
1853 return NULL;
1854 }
1855 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001856 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 return NULL;
1858 switch (mod->kind) {
1859 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001860 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 compiler_exit_scope(c);
1862 return 0;
1863 }
1864 break;
1865 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001866 if (find_ann(mod->v.Interactive.body)) {
1867 ADDOP(c, SETUP_ANNOTATIONS);
1868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001870 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 break;
1872 case Expression_kind:
1873 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1874 addNone = 0;
1875 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 default:
1877 PyErr_Format(PyExc_SystemError,
1878 "module kind %d should not be possible",
1879 mod->kind);
1880 return 0;
1881 }
1882 co = assemble(c, addNone);
1883 compiler_exit_scope(c);
1884 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001885}
1886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887/* The test for LOCAL must come before the test for FREE in order to
1888 handle classes where name is both local and free. The local var is
1889 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001890*/
1891
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001892static int
1893get_ref_type(struct compiler *c, PyObject *name)
1894{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001895 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001896 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001897 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001898 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001899 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 if (scope == 0) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001901 PyErr_Format(PyExc_SystemError,
1902 "PyST_GetScope(name=%R) failed: "
1903 "unknown scope in unit %S (%R); "
1904 "symbols: %R; locals: %R; globals: %R",
1905 name,
1906 c->u->u_name, c->u->u_ste->ste_id,
1907 c->u->u_ste->ste_symbols, c->u->u_varnames, c->u->u_names);
1908 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911}
1912
1913static int
1914compiler_lookup_arg(PyObject *dict, PyObject *name)
1915{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001916 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001917 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001919 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001920 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921}
1922
1923static int
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001924compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags,
1925 PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001927 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001928 if (qualname == NULL)
1929 qualname = co->co_name;
1930
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001931 if (free) {
1932 for (i = 0; i < free; ++i) {
1933 /* Bypass com_addop_varname because it will generate
1934 LOAD_DEREF but LOAD_CLOSURE is needed.
1935 */
1936 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001937
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001938 /* Special case: If a class contains a method with a
1939 free variable that has the same name as a method,
1940 the name will be considered free *and* local in the
1941 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001942 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001943 */
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001944 int reftype = get_ref_type(c, name);
1945 if (reftype == -1) {
1946 return 0;
1947 }
1948 int arg;
1949 if (reftype == CELL) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001950 arg = compiler_lookup_arg(c->u->u_cellvars, name);
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001951 }
1952 else {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001953 arg = compiler_lookup_arg(c->u->u_freevars, name);
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001954 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001955 if (arg == -1) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01001956 PyErr_Format(PyExc_SystemError,
1957 "compiler_lookup_arg(name=%R) with reftype=%d failed in %S; "
1958 "freevars of code %S: %R",
1959 name,
1960 reftype,
1961 c->u->u_name,
1962 co->co_name,
1963 co->co_freevars);
1964 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001965 }
1966 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001968 flags |= 0x08;
1969 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001971 ADDOP_LOAD_CONST(c, (PyObject*)co);
1972 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001973 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975}
1976
1977static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001978compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 if (!decos)
1983 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1986 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1987 }
1988 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989}
1990
1991static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001992compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1993 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001994{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001995 /* Push a dict of keyword-only default values.
1996
1997 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1998 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001999 int i;
2000 PyObject *keys = NULL;
2001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
2003 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
2004 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
2005 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04002006 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002007 if (!mangled) {
2008 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002010 if (keys == NULL) {
2011 keys = PyList_New(1);
2012 if (keys == NULL) {
2013 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002014 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002015 }
2016 PyList_SET_ITEM(keys, 0, mangled);
2017 }
2018 else {
2019 int res = PyList_Append(keys, mangled);
2020 Py_DECREF(mangled);
2021 if (res == -1) {
2022 goto error;
2023 }
2024 }
2025 if (!compiler_visit_expr(c, default_)) {
2026 goto error;
2027 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 }
2029 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002030 if (keys != NULL) {
2031 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2032 PyObject *keys_tuple = PyList_AsTuple(keys);
2033 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002034 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002035 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002036 assert(default_count > 0);
2037 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002038 }
2039 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002040 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002041 }
2042
2043error:
2044 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002045 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002046}
2047
2048static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002049compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2050{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002051 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002052 return 1;
2053}
2054
2055static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002056compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002057 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002060 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002061 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002062 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002063
2064 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002065 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002066 VISIT(c, annexpr, annotation);
2067 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002069 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002070}
2071
2072static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002073compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002074 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002075{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002076 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 for (i = 0; i < asdl_seq_LEN(args); i++) {
2078 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002079 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 c,
2081 arg->arg,
2082 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002083 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002084 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002086 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002087}
2088
2089static int
2090compiler_visit_annotations(struct compiler *c, arguments_ty args,
2091 expr_ty returns)
2092{
Yurii Karabas73019792020-11-25 12:43:18 +02002093 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002094 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002095
Yurii Karabas73019792020-11-25 12:43:18 +02002096 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 */
2098 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002099 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002100
Yurii Karabas73019792020-11-25 12:43:18 +02002101 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2102 return 0;
2103 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2104 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002105 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002106 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002107 args->vararg->annotation, &annotations_len))
2108 return 0;
2109 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2110 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002111 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002112 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002113 args->kwarg->annotation, &annotations_len))
2114 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 if (!return_str) {
2117 return_str = PyUnicode_InternFromString("return");
2118 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002119 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 }
Yurii Karabas73019792020-11-25 12:43:18 +02002121 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2122 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 }
2124
Yurii Karabas73019792020-11-25 12:43:18 +02002125 if (annotations_len) {
2126 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002127 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002129
Yurii Karabas73019792020-11-25 12:43:18 +02002130 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002131}
2132
2133static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002134compiler_visit_defaults(struct compiler *c, arguments_ty args)
2135{
2136 VISIT_SEQ(c, expr, args->defaults);
2137 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2138 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139}
2140
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002141static Py_ssize_t
2142compiler_default_arguments(struct compiler *c, arguments_ty args)
2143{
2144 Py_ssize_t funcflags = 0;
2145 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002146 if (!compiler_visit_defaults(c, args))
2147 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002148 funcflags |= 0x01;
2149 }
2150 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002151 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002152 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002153 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002154 return -1;
2155 }
2156 else if (res > 0) {
2157 funcflags |= 0x02;
2158 }
2159 }
2160 return funcflags;
2161}
2162
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002163static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002164forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2165{
2166
2167 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2168 compiler_error(c, "cannot assign to __debug__");
2169 return 1;
2170 }
2171 return 0;
2172}
2173
2174static int
2175compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2176{
2177 if (arg != NULL) {
2178 if (forbidden_name(c, arg->arg, Store))
2179 return 0;
2180 }
2181 return 1;
2182}
2183
2184static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002185compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002186{
2187 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002188 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002189 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2190 return 0;
2191 }
2192 }
2193 return 1;
2194}
2195
2196static int
2197compiler_check_debug_args(struct compiler *c, arguments_ty args)
2198{
2199 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2200 return 0;
2201 if (!compiler_check_debug_args_seq(c, args->args))
2202 return 0;
2203 if (!compiler_check_debug_one_arg(c, args->vararg))
2204 return 0;
2205 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2206 return 0;
2207 if (!compiler_check_debug_one_arg(c, args->kwarg))
2208 return 0;
2209 return 1;
2210}
2211
2212static int
Yury Selivanov75445082015-05-11 22:57:16 -04002213compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002216 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002217 arguments_ty args;
2218 expr_ty returns;
2219 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002220 asdl_expr_seq* decos;
2221 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002222 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002223 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002224 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002225 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226
Yury Selivanov75445082015-05-11 22:57:16 -04002227 if (is_async) {
2228 assert(s->kind == AsyncFunctionDef_kind);
2229
2230 args = s->v.AsyncFunctionDef.args;
2231 returns = s->v.AsyncFunctionDef.returns;
2232 decos = s->v.AsyncFunctionDef.decorator_list;
2233 name = s->v.AsyncFunctionDef.name;
2234 body = s->v.AsyncFunctionDef.body;
2235
2236 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2237 } else {
2238 assert(s->kind == FunctionDef_kind);
2239
2240 args = s->v.FunctionDef.args;
2241 returns = s->v.FunctionDef.returns;
2242 decos = s->v.FunctionDef.decorator_list;
2243 name = s->v.FunctionDef.name;
2244 body = s->v.FunctionDef.body;
2245
2246 scope_type = COMPILER_SCOPE_FUNCTION;
2247 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002248
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002249 if (!compiler_check_debug_args(c, args))
2250 return 0;
2251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 if (!compiler_decorators(c, decos))
2253 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002254
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002255 firstlineno = s->lineno;
2256 if (asdl_seq_LEN(decos)) {
2257 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2258 }
2259
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002260 funcflags = compiler_default_arguments(c, args);
2261 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002263 }
2264
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002265 annotations = compiler_visit_annotations(c, args, returns);
2266 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002267 return 0;
2268 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002269 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002270 funcflags |= 0x04;
2271 }
2272
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002273 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002274 return 0;
2275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276
INADA Naokicb41b272017-02-23 00:31:59 +09002277 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002278 if (c->c_optimize < 2) {
2279 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002280 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002281 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 compiler_exit_scope(c);
2283 return 0;
2284 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002287 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002289 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002290 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002291 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002293 qualname = c->u->u_qualname;
2294 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002296 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002297 Py_XDECREF(qualname);
2298 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002300 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002302 if (!compiler_make_closure(c, co, funcflags, qualname)) {
2303 Py_DECREF(qualname);
2304 Py_DECREF(co);
2305 return 0;
2306 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002307 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* decorators */
2311 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2312 ADDOP_I(c, CALL_FUNCTION, 1);
2313 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314
Yury Selivanov75445082015-05-11 22:57:16 -04002315 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002316}
2317
2318static int
2319compiler_class(struct compiler *c, stmt_ty s)
2320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 PyCodeObject *co;
2322 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002323 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002324 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 if (!compiler_decorators(c, decos))
2327 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002328
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002329 firstlineno = s->lineno;
2330 if (asdl_seq_LEN(decos)) {
2331 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2332 }
2333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* ultimately generate code for:
2335 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2336 where:
2337 <func> is a function/closure created from the class body;
2338 it has a single argument (__locals__) where the dict
2339 (or MutableSequence) representing the locals is passed
2340 <name> is the class name
2341 <bases> is the positional arguments and *varargs argument
2342 <keywords> is the keyword arguments and **kwds argument
2343 This borrows from compiler_call.
2344 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002347 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002348 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 return 0;
2350 /* this block represents what we do in the new scope */
2351 {
2352 /* use the class name for name mangling */
2353 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002354 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 /* load (global) __name__ ... */
2356 str = PyUnicode_InternFromString("__name__");
2357 if (!str || !compiler_nameop(c, str, Load)) {
2358 Py_XDECREF(str);
2359 compiler_exit_scope(c);
2360 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 Py_DECREF(str);
2363 /* ... and store it as __module__ */
2364 str = PyUnicode_InternFromString("__module__");
2365 if (!str || !compiler_nameop(c, str, Store)) {
2366 Py_XDECREF(str);
2367 compiler_exit_scope(c);
2368 return 0;
2369 }
2370 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002371 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002372 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002373 str = PyUnicode_InternFromString("__qualname__");
2374 if (!str || !compiler_nameop(c, str, Store)) {
2375 Py_XDECREF(str);
2376 compiler_exit_scope(c);
2377 return 0;
2378 }
2379 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002381 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 compiler_exit_scope(c);
2383 return 0;
2384 }
Mark Shannone56d54e2021-01-15 13:52:00 +00002385 /* The following code is artificial */
2386 c->u->u_lineno = -1;
Nick Coghlan19d24672016-12-05 16:47:55 +10002387 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002388 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002389 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002390 str = PyUnicode_InternFromString("__class__");
2391 if (str == NULL) {
2392 compiler_exit_scope(c);
2393 return 0;
2394 }
2395 i = compiler_lookup_arg(c->u->u_cellvars, str);
2396 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002397 if (i < 0) {
2398 compiler_exit_scope(c);
2399 return 0;
2400 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002401 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002404 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002405 str = PyUnicode_InternFromString("__classcell__");
2406 if (!str || !compiler_nameop(c, str, Store)) {
2407 Py_XDECREF(str);
2408 compiler_exit_scope(c);
2409 return 0;
2410 }
2411 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002413 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002414 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002415 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002416 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002417 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002418 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 /* create the code object */
2420 co = assemble(c, 1);
2421 }
2422 /* leave the new scope */
2423 compiler_exit_scope(c);
2424 if (co == NULL)
2425 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 /* 2. load the 'build_class' function */
2428 ADDOP(c, LOAD_BUILD_CLASS);
2429
2430 /* 3. load a function (or closure) made from the code object */
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002431 if (!compiler_make_closure(c, co, 0, NULL)) {
2432 Py_DECREF(co);
2433 return 0;
2434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 Py_DECREF(co);
2436
2437 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002438 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439
2440 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002441 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return 0;
2443
2444 /* 6. apply decorators */
2445 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2446 ADDOP_I(c, CALL_FUNCTION, 1);
2447 }
2448
2449 /* 7. store into <name> */
2450 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2451 return 0;
2452 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002453}
2454
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002455/* Return 0 if the expression is a constant value except named singletons.
2456 Return 1 otherwise. */
2457static int
2458check_is_arg(expr_ty e)
2459{
2460 if (e->kind != Constant_kind) {
2461 return 1;
2462 }
2463 PyObject *value = e->v.Constant.value;
2464 return (value == Py_None
2465 || value == Py_False
2466 || value == Py_True
2467 || value == Py_Ellipsis);
2468}
2469
2470/* Check operands of identity chacks ("is" and "is not").
2471 Emit a warning if any operand is a constant except named singletons.
2472 Return 0 on error.
2473 */
2474static int
2475check_compare(struct compiler *c, expr_ty e)
2476{
2477 Py_ssize_t i, n;
2478 int left = check_is_arg(e->v.Compare.left);
2479 n = asdl_seq_LEN(e->v.Compare.ops);
2480 for (i = 0; i < n; i++) {
2481 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2482 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2483 if (op == Is || op == IsNot) {
2484 if (!right || !left) {
2485 const char *msg = (op == Is)
2486 ? "\"is\" with a literal. Did you mean \"==\"?"
2487 : "\"is not\" with a literal. Did you mean \"!=\"?";
2488 return compiler_warn(c, msg);
2489 }
2490 }
2491 left = right;
2492 }
2493 return 1;
2494}
2495
Mark Shannon9af0e472020-01-14 10:12:45 +00002496static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002497{
Mark Shannon9af0e472020-01-14 10:12:45 +00002498 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002499 switch (op) {
2500 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002501 cmp = Py_EQ;
2502 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002503 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002504 cmp = Py_NE;
2505 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002506 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002507 cmp = Py_LT;
2508 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002509 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002510 cmp = Py_LE;
2511 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002512 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002513 cmp = Py_GT;
2514 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002515 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002516 cmp = Py_GE;
2517 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002518 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002519 ADDOP_I(c, IS_OP, 0);
2520 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002521 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002522 ADDOP_I(c, IS_OP, 1);
2523 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002524 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002525 ADDOP_I(c, CONTAINS_OP, 0);
2526 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002527 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002528 ADDOP_I(c, CONTAINS_OP, 1);
2529 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002530 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002531 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002532 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002533 ADDOP_I(c, COMPARE_OP, cmp);
2534 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002535}
2536
Mark Shannon9af0e472020-01-14 10:12:45 +00002537
2538
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002539static int
2540compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2541{
2542 switch (e->kind) {
2543 case UnaryOp_kind:
2544 if (e->v.UnaryOp.op == Not)
2545 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2546 /* fallback to general implementation */
2547 break;
2548 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002549 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002550 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2551 assert(n >= 0);
2552 int cond2 = e->v.BoolOp.op == Or;
2553 basicblock *next2 = next;
2554 if (!cond2 != !cond) {
2555 next2 = compiler_new_block(c);
2556 if (next2 == NULL)
2557 return 0;
2558 }
2559 for (i = 0; i < n; ++i) {
2560 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2561 return 0;
2562 }
2563 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2564 return 0;
2565 if (next2 != next)
2566 compiler_use_next_block(c, next2);
2567 return 1;
2568 }
2569 case IfExp_kind: {
2570 basicblock *end, *next2;
2571 end = compiler_new_block(c);
2572 if (end == NULL)
2573 return 0;
2574 next2 = compiler_new_block(c);
2575 if (next2 == NULL)
2576 return 0;
2577 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2578 return 0;
2579 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2580 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002581 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002582 compiler_use_next_block(c, next2);
2583 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2584 return 0;
2585 compiler_use_next_block(c, end);
2586 return 1;
2587 }
2588 case Compare_kind: {
2589 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2590 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002591 if (!check_compare(c, e)) {
2592 return 0;
2593 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002594 basicblock *cleanup = compiler_new_block(c);
2595 if (cleanup == NULL)
2596 return 0;
2597 VISIT(c, expr, e->v.Compare.left);
2598 for (i = 0; i < n; i++) {
2599 VISIT(c, expr,
2600 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2601 ADDOP(c, DUP_TOP);
2602 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002603 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002604 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002605 NEXT_BLOCK(c);
2606 }
2607 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002608 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002609 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002610 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002611 basicblock *end = compiler_new_block(c);
2612 if (end == NULL)
2613 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002614 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002615 compiler_use_next_block(c, cleanup);
2616 ADDOP(c, POP_TOP);
2617 if (!cond) {
Mark Shannon127dde52021-01-04 18:06:55 +00002618 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002619 }
2620 compiler_use_next_block(c, end);
2621 return 1;
2622 }
2623 /* fallback to general implementation */
2624 break;
2625 }
2626 default:
2627 /* fallback to general implementation */
2628 break;
2629 }
2630
2631 /* general implementation */
2632 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002633 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002634 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002635 return 1;
2636}
2637
2638static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002639compiler_ifexp(struct compiler *c, expr_ty e)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 basicblock *end, *next;
2642
2643 assert(e->kind == IfExp_kind);
2644 end = compiler_new_block(c);
2645 if (end == NULL)
2646 return 0;
2647 next = compiler_new_block(c);
2648 if (next == NULL)
2649 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002650 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2651 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon127dde52021-01-04 18:06:55 +00002653 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 compiler_use_next_block(c, next);
2655 VISIT(c, expr, e->v.IfExp.orelse);
2656 compiler_use_next_block(c, end);
2657 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002658}
2659
2660static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002661compiler_lambda(struct compiler *c, expr_ty e)
2662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002664 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002666 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 arguments_ty args = e->v.Lambda.args;
2668 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002669
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002670 if (!compiler_check_debug_args(c, args))
2671 return 0;
2672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 if (!name) {
2674 name = PyUnicode_InternFromString("<lambda>");
2675 if (!name)
2676 return 0;
2677 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002679 funcflags = compiler_default_arguments(c, args);
2680 if (funcflags == -1) {
2681 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002683
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002684 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002685 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 /* Make None the first constant, so the lambda can't have a
2689 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002690 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002694 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2696 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2697 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002698 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 }
2700 else {
2701 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002702 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002704 qualname = c->u->u_qualname;
2705 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 compiler_exit_scope(c);
Pablo Galindo7fdab832021-01-29 22:40:59 +00002707 if (co == NULL) {
2708 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 return 0;
Pablo Galindo7fdab832021-01-29 22:40:59 +00002710 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002711
Victor Stinnerba7a99d2021-01-30 01:46:44 +01002712 if (!compiler_make_closure(c, co, funcflags, qualname)) {
2713 Py_DECREF(qualname);
2714 Py_DECREF(co);
2715 return 0;
2716 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002717 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 Py_DECREF(co);
2719
2720 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002721}
2722
2723static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724compiler_if(struct compiler *c, stmt_ty s)
2725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 assert(s->kind == If_kind);
2728 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002729 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002731 }
2732 if (asdl_seq_LEN(s->v.If.orelse)) {
2733 next = compiler_new_block(c);
2734 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002735 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002736 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002737 }
2738 else {
2739 next = end;
2740 }
2741 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2742 return 0;
2743 }
2744 VISIT_SEQ(c, stmt, s->v.If.body);
2745 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon127dde52021-01-04 18:06:55 +00002746 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Mark Shannon8473cf82020-12-15 11:07:50 +00002747 compiler_use_next_block(c, next);
2748 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 }
2750 compiler_use_next_block(c, end);
2751 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752}
2753
2754static int
2755compiler_for(struct compiler *c, stmt_ty s)
2756{
Mark Shannon5977a792020-12-02 13:31:40 +00002757 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002760 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 cleanup = compiler_new_block(c);
2762 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002763 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002765 }
2766 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002768 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 VISIT(c, expr, s->v.For.iter);
2770 ADDOP(c, GET_ITER);
2771 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002772 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002773 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 VISIT(c, expr, s->v.For.target);
2775 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002776 /* Mark jump as artificial */
2777 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002778 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002780
2781 compiler_pop_fblock(c, FOR_LOOP, start);
2782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 VISIT_SEQ(c, stmt, s->v.For.orelse);
2784 compiler_use_next_block(c, end);
2785 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786}
2787
Yury Selivanov75445082015-05-11 22:57:16 -04002788
2789static int
2790compiler_async_for(struct compiler *c, stmt_ty s)
2791{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002792 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002793 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002794 c->u->u_ste->ste_coroutine = 1;
2795 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002796 return compiler_error(c, "'async for' outside async function");
2797 }
2798
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002799 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002800 except = compiler_new_block(c);
2801 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002802
Mark Shannonfee55262019-11-21 09:11:43 +00002803 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002804 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002805 }
Yury Selivanov75445082015-05-11 22:57:16 -04002806 VISIT(c, expr, s->v.AsyncFor.iter);
2807 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002808
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002809 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002810 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002811 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002812 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002813 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002814 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002815 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002816 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002817 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002818 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002819
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002820 /* Success block for __anext__ */
2821 VISIT(c, expr, s->v.AsyncFor.target);
2822 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002823 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002824
2825 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002826
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002827 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002828 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002829
2830 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002831 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002832
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002833 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002834 VISIT_SEQ(c, stmt, s->v.For.orelse);
2835
2836 compiler_use_next_block(c, end);
2837
2838 return 1;
2839}
2840
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841static int
2842compiler_while(struct compiler *c, stmt_ty s)
2843{
Mark Shannon266b4622020-11-17 19:30:14 +00002844 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002846 body = compiler_new_block(c);
2847 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002849 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002853 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002856 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2857 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002858 }
2859
2860 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002862 SET_LOC(c, s);
2863 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2864 return 0;
2865 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002867 compiler_pop_fblock(c, WHILE_LOOP, loop);
2868
Mark Shannon266b4622020-11-17 19:30:14 +00002869 compiler_use_next_block(c, anchor);
2870 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002872 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002876}
2877
2878static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002880{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002882 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 if (c->u->u_ste->ste_type != FunctionBlock)
2884 return compiler_error(c, "'return' outside function");
2885 if (s->v.Return.value != NULL &&
2886 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2887 {
2888 return compiler_error(
2889 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002891 if (preserve_tos) {
2892 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002893 } else {
2894 /* Emit instruction with line number for expression */
2895 if (s->v.Return.value != NULL) {
2896 SET_LOC(c, s->v.Return.value);
2897 ADDOP(c, NOP);
2898 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002899 }
Mark Shannonfee55262019-11-21 09:11:43 +00002900 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2901 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002902 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002903 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002904 }
2905 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00002906 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002907 }
2908 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002909 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912}
2913
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002914static int
2915compiler_break(struct compiler *c)
2916{
Mark Shannonfee55262019-11-21 09:11:43 +00002917 struct fblockinfo *loop = NULL;
2918 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2919 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002920 }
Mark Shannonfee55262019-11-21 09:11:43 +00002921 if (loop == NULL) {
2922 return compiler_error(c, "'break' outside loop");
2923 }
2924 if (!compiler_unwind_fblock(c, loop, 0)) {
2925 return 0;
2926 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002927 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002928 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002929 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002930}
2931
2932static int
2933compiler_continue(struct compiler *c)
2934{
Mark Shannonfee55262019-11-21 09:11:43 +00002935 struct fblockinfo *loop = NULL;
2936 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2937 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002938 }
Mark Shannonfee55262019-11-21 09:11:43 +00002939 if (loop == NULL) {
2940 return compiler_error(c, "'continue' not properly in loop");
2941 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002942 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002943 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002944 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002945}
2946
2947
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949
2950 SETUP_FINALLY L
2951 <code for body>
2952 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002953 <code for finalbody>
2954 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002955 L:
2956 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002957 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959 The special instructions use the block stack. Each block
2960 stack entry contains the instruction that created it (here
2961 SETUP_FINALLY), the level of the value stack at the time the
2962 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002964 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965 Pushes the current value stack level and the label
2966 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002967 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002968 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002970 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002971 when a SETUP_FINALLY entry is found, the raised and the caught
2972 exceptions are pushed onto the value stack (and the exception
2973 condition is cleared), and the interpreter jumps to the label
2974 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002975*/
2976
2977static int
2978compiler_try_finally(struct compiler *c, stmt_ty s)
2979{
Mark Shannonfee55262019-11-21 09:11:43 +00002980 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002982 body = compiler_new_block(c);
2983 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002984 exit = compiler_new_block(c);
2985 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002988 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002989 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002991 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002993 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2994 if (!compiler_try_except(c, s))
2995 return 0;
2996 }
2997 else {
2998 VISIT_SEQ(c, stmt, s->v.Try.body);
2999 }
Mark Shannon3bd60352021-01-13 12:05:43 +00003000 ADDOP_NOLINE(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00003001 compiler_pop_fblock(c, FINALLY_TRY, body);
3002 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon127dde52021-01-04 18:06:55 +00003003 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00003004 /* `finally` block */
3005 compiler_use_next_block(c, end);
3006 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
3007 return 0;
3008 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3009 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00003010 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00003011 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003013}
3014
3015/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003016 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 (The contents of the value stack is shown in [], with the top
3018 at the right; 'tb' is trace-back info, 'val' the exception's
3019 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020
3021 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003022 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 [] <code for S>
3024 [] POP_BLOCK
3025 [] JUMP_FORWARD L0
3026
3027 [tb, val, exc] L1: DUP )
3028 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003029 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 [tb, val, exc] POP
3031 [tb, val] <assign to V1> (or POP if no V1)
3032 [tb] POP
3033 [] <code for S1>
3034 JUMP_FORWARD L0
3035
3036 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003037 .............................etc.......................
3038
Mark Shannonfee55262019-11-21 09:11:43 +00003039 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040
3041 [] L0: <next statement>
3042
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003043 Of course, parts are not generated if Vi or Ei is not present.
3044*/
3045static int
3046compiler_try_except(struct compiler *c, stmt_ty s)
3047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003049 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 body = compiler_new_block(c);
3052 except = compiler_new_block(c);
3053 orelse = compiler_new_block(c);
3054 end = compiler_new_block(c);
3055 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3056 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003057 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003059 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003061 VISIT_SEQ(c, stmt, s->v.Try.body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003062 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon3bd60352021-01-13 12:05:43 +00003063 ADDOP_NOLINE(c, POP_BLOCK);
3064 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003065 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003067 /* Runtime will push a block here, so we need to account for that */
3068 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3069 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 for (i = 0; i < n; i++) {
3071 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003072 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 if (!handler->v.ExceptHandler.type && i < n-1)
3074 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003075 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 except = compiler_new_block(c);
3077 if (except == NULL)
3078 return 0;
3079 if (handler->v.ExceptHandler.type) {
3080 ADDOP(c, DUP_TOP);
3081 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003082 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003083 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003084 }
3085 ADDOP(c, POP_TOP);
3086 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003088
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 cleanup_end = compiler_new_block(c);
3090 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003091 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003092 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003093 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003094
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003095 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3096 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003098 /*
3099 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003100 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003102 try:
3103 # body
3104 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003105 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003106 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003107 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003110 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003112 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003113 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 /* second # body */
3116 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003117 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003118 ADDOP(c, POP_BLOCK);
3119 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003120 /* name = None; del name; # Mark as artificial */
3121 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003122 ADDOP_LOAD_CONST(c, Py_None);
3123 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3124 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003125 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126
Mark Shannonfee55262019-11-21 09:11:43 +00003127 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003128 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129
Mark Shannon877df852020-11-12 09:43:29 +00003130 /* name = None; del name; # Mark as artificial */
3131 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003132 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003133 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003134 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135
Mark Shannonbf353f32020-12-17 13:55:28 +00003136 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 }
3138 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003139 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003141 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003142 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003143 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144
Guido van Rossumb940e112007-01-10 16:19:56 +00003145 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003146 ADDOP(c, POP_TOP);
3147 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003148 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003149 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003151 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannon127dde52021-01-04 18:06:55 +00003152 /* name = None; del name; # Mark as artificial */
3153 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003154 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003155 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 compiler_use_next_block(c, except);
3158 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003159 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003160 /* Mark as artificial */
3161 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003162 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003164 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 compiler_use_next_block(c, end);
3166 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003167}
3168
3169static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003170compiler_try(struct compiler *c, stmt_ty s) {
3171 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3172 return compiler_try_finally(c, s);
3173 else
3174 return compiler_try_except(c, s);
3175}
3176
3177
3178static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003179compiler_import_as(struct compiler *c, identifier name, identifier asname)
3180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 /* The IMPORT_NAME opcode was already generated. This function
3182 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003185 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003187 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3188 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003189 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003190 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003191 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003193 while (1) {
3194 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003195 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003196 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003197 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003198 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003199 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003201 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003202 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003203 if (dot == -1) {
3204 break;
3205 }
3206 ADDOP(c, ROT_TWO);
3207 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003209 if (!compiler_nameop(c, asname, Store)) {
3210 return 0;
3211 }
3212 ADDOP(c, POP_TOP);
3213 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 }
3215 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216}
3217
3218static int
3219compiler_import(struct compiler *c, stmt_ty s)
3220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 /* The Import node stores a module name like a.b.c as a single
3222 string. This is convenient for all cases except
3223 import a.b.c as d
3224 where we need to parse that string to extract the individual
3225 module names.
3226 XXX Perhaps change the representation to make this case simpler?
3227 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003228 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003229
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003230 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 for (i = 0; i < n; i++) {
3232 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3233 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003235 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003236 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 if (alias->asname) {
3240 r = compiler_import_as(c, alias->name, alias->asname);
3241 if (!r)
3242 return r;
3243 }
3244 else {
3245 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003246 Py_ssize_t dot = PyUnicode_FindChar(
3247 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003248 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003249 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003250 if (tmp == NULL)
3251 return 0;
3252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003254 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 Py_DECREF(tmp);
3256 }
3257 if (!r)
3258 return r;
3259 }
3260 }
3261 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003262}
3263
3264static int
3265compiler_from_import(struct compiler *c, stmt_ty s)
3266{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003267 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003268 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 if (!empty_string) {
3272 empty_string = PyUnicode_FromString("");
3273 if (!empty_string)
3274 return 0;
3275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003276
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003277 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003278
3279 names = PyTuple_New(n);
3280 if (!names)
3281 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003283 /* build up the names */
3284 for (i = 0; i < n; i++) {
3285 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3286 Py_INCREF(alias->name);
3287 PyTuple_SET_ITEM(names, i, alias->name);
3288 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003291 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 Py_DECREF(names);
3293 return compiler_error(c, "from __future__ imports must occur "
3294 "at the beginning of the file");
3295 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003296 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 if (s->v.ImportFrom.module) {
3299 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3300 }
3301 else {
3302 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3303 }
3304 for (i = 0; i < n; i++) {
3305 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3306 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003307
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003308 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 assert(n == 1);
3310 ADDOP(c, IMPORT_STAR);
3311 return 1;
3312 }
3313
3314 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3315 store_name = alias->name;
3316 if (alias->asname)
3317 store_name = alias->asname;
3318
3319 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 return 0;
3321 }
3322 }
3323 /* remove imported module */
3324 ADDOP(c, POP_TOP);
3325 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003326}
3327
3328static int
3329compiler_assert(struct compiler *c, stmt_ty s)
3330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332
Georg Brandl8334fd92010-12-04 10:26:46 +00003333 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003334 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003335 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003336 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3337 {
3338 if (!compiler_warn(c, "assertion is always true, "
3339 "perhaps remove parentheses?"))
3340 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003341 return 0;
3342 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 end = compiler_new_block(c);
3345 if (end == NULL)
3346 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003347 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3348 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003349 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 if (s->v.Assert.msg) {
3351 VISIT(c, expr, s->v.Assert.msg);
3352 ADDOP_I(c, CALL_FUNCTION, 1);
3353 }
3354 ADDOP_I(c, RAISE_VARARGS, 1);
3355 compiler_use_next_block(c, end);
3356 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003357}
3358
3359static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003360compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3361{
3362 if (c->c_interactive && c->c_nestlevel <= 1) {
3363 VISIT(c, expr, value);
3364 ADDOP(c, PRINT_EXPR);
3365 return 1;
3366 }
3367
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003368 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003369 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003370 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003371 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003372 }
3373
3374 VISIT(c, expr, value);
3375 ADDOP(c, POP_TOP);
3376 return 1;
3377}
3378
3379static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003380compiler_visit_stmt(struct compiler *c, stmt_ty s)
3381{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003382 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003384 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003385 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 switch (s->kind) {
3388 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003389 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 case ClassDef_kind:
3391 return compiler_class(c, s);
3392 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003393 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003394 case Delete_kind:
3395 VISIT_SEQ(c, expr, s->v.Delete.targets)
3396 break;
3397 case Assign_kind:
3398 n = asdl_seq_LEN(s->v.Assign.targets);
3399 VISIT(c, expr, s->v.Assign.value);
3400 for (i = 0; i < n; i++) {
3401 if (i < n - 1)
3402 ADDOP(c, DUP_TOP);
3403 VISIT(c, expr,
3404 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3405 }
3406 break;
3407 case AugAssign_kind:
3408 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003409 case AnnAssign_kind:
3410 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 case For_kind:
3412 return compiler_for(c, s);
3413 case While_kind:
3414 return compiler_while(c, s);
3415 case If_kind:
3416 return compiler_if(c, s);
3417 case Raise_kind:
3418 n = 0;
3419 if (s->v.Raise.exc) {
3420 VISIT(c, expr, s->v.Raise.exc);
3421 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003422 if (s->v.Raise.cause) {
3423 VISIT(c, expr, s->v.Raise.cause);
3424 n++;
3425 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003427 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003428 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003429 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003430 case Try_kind:
3431 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 case Assert_kind:
3433 return compiler_assert(c, s);
3434 case Import_kind:
3435 return compiler_import(c, s);
3436 case ImportFrom_kind:
3437 return compiler_from_import(c, s);
3438 case Global_kind:
3439 case Nonlocal_kind:
3440 break;
3441 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003442 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003444 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 break;
3446 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003447 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 case Continue_kind:
3449 return compiler_continue(c);
3450 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003451 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003452 case AsyncFunctionDef_kind:
3453 return compiler_function(c, s, 1);
3454 case AsyncWith_kind:
3455 return compiler_async_with(c, s, 0);
3456 case AsyncFor_kind:
3457 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 }
Yury Selivanov75445082015-05-11 22:57:16 -04003459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003460 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003461}
3462
3463static int
3464unaryop(unaryop_ty op)
3465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 switch (op) {
3467 case Invert:
3468 return UNARY_INVERT;
3469 case Not:
3470 return UNARY_NOT;
3471 case UAdd:
3472 return UNARY_POSITIVE;
3473 case USub:
3474 return UNARY_NEGATIVE;
3475 default:
3476 PyErr_Format(PyExc_SystemError,
3477 "unary op %d should not be possible", op);
3478 return 0;
3479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003480}
3481
3482static int
Andy Lester76d58772020-03-10 21:18:12 -05003483binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003485 switch (op) {
3486 case Add:
3487 return BINARY_ADD;
3488 case Sub:
3489 return BINARY_SUBTRACT;
3490 case Mult:
3491 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003492 case MatMult:
3493 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 case Div:
3495 return BINARY_TRUE_DIVIDE;
3496 case Mod:
3497 return BINARY_MODULO;
3498 case Pow:
3499 return BINARY_POWER;
3500 case LShift:
3501 return BINARY_LSHIFT;
3502 case RShift:
3503 return BINARY_RSHIFT;
3504 case BitOr:
3505 return BINARY_OR;
3506 case BitXor:
3507 return BINARY_XOR;
3508 case BitAnd:
3509 return BINARY_AND;
3510 case FloorDiv:
3511 return BINARY_FLOOR_DIVIDE;
3512 default:
3513 PyErr_Format(PyExc_SystemError,
3514 "binary op %d should not be possible", op);
3515 return 0;
3516 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003517}
3518
3519static int
Andy Lester76d58772020-03-10 21:18:12 -05003520inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003522 switch (op) {
3523 case Add:
3524 return INPLACE_ADD;
3525 case Sub:
3526 return INPLACE_SUBTRACT;
3527 case Mult:
3528 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003529 case MatMult:
3530 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003531 case Div:
3532 return INPLACE_TRUE_DIVIDE;
3533 case Mod:
3534 return INPLACE_MODULO;
3535 case Pow:
3536 return INPLACE_POWER;
3537 case LShift:
3538 return INPLACE_LSHIFT;
3539 case RShift:
3540 return INPLACE_RSHIFT;
3541 case BitOr:
3542 return INPLACE_OR;
3543 case BitXor:
3544 return INPLACE_XOR;
3545 case BitAnd:
3546 return INPLACE_AND;
3547 case FloorDiv:
3548 return INPLACE_FLOOR_DIVIDE;
3549 default:
3550 PyErr_Format(PyExc_SystemError,
3551 "inplace binary op %d should not be possible", op);
3552 return 0;
3553 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003554}
3555
3556static int
3557compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3558{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003559 int op, scope;
3560 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003563 PyObject *dict = c->u->u_names;
3564 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003565
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003566 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3567 !_PyUnicode_EqualToASCIIString(name, "True") &&
3568 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003569
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003570 if (forbidden_name(c, name, ctx))
3571 return 0;
3572
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003573 mangled = _Py_Mangle(c->u->u_private, name);
3574 if (!mangled)
3575 return 0;
3576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 op = 0;
3578 optype = OP_NAME;
3579 scope = PyST_GetScope(c->u->u_ste, mangled);
3580 switch (scope) {
3581 case FREE:
3582 dict = c->u->u_freevars;
3583 optype = OP_DEREF;
3584 break;
3585 case CELL:
3586 dict = c->u->u_cellvars;
3587 optype = OP_DEREF;
3588 break;
3589 case LOCAL:
3590 if (c->u->u_ste->ste_type == FunctionBlock)
3591 optype = OP_FAST;
3592 break;
3593 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003594 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 optype = OP_GLOBAL;
3596 break;
3597 case GLOBAL_EXPLICIT:
3598 optype = OP_GLOBAL;
3599 break;
3600 default:
3601 /* scope can be 0 */
3602 break;
3603 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003606 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 switch (optype) {
3609 case OP_DEREF:
3610 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003611 case Load:
3612 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3613 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003614 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003615 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 }
3617 break;
3618 case OP_FAST:
3619 switch (ctx) {
3620 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003621 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003624 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 return 1;
3626 case OP_GLOBAL:
3627 switch (ctx) {
3628 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003629 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 }
3632 break;
3633 case OP_NAME:
3634 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003635 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003636 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 }
3639 break;
3640 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003643 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 Py_DECREF(mangled);
3645 if (arg < 0)
3646 return 0;
3647 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003648}
3649
3650static int
3651compiler_boolop(struct compiler *c, expr_ty e)
3652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003654 int jumpi;
3655 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003656 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003658 assert(e->kind == BoolOp_kind);
3659 if (e->v.BoolOp.op == And)
3660 jumpi = JUMP_IF_FALSE_OR_POP;
3661 else
3662 jumpi = JUMP_IF_TRUE_OR_POP;
3663 end = compiler_new_block(c);
3664 if (end == NULL)
3665 return 0;
3666 s = e->v.BoolOp.values;
3667 n = asdl_seq_LEN(s) - 1;
3668 assert(n >= 0);
3669 for (i = 0; i < n; ++i) {
3670 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003671 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003672 basicblock *next = compiler_new_block(c);
3673 if (next == NULL) {
3674 return 0;
3675 }
3676 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003677 }
3678 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3679 compiler_use_next_block(c, end);
3680 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003681}
3682
3683static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003684starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003685 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003686{
3687 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003688 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003689 if (n > 2 && are_all_items_const(elts, 0, n)) {
3690 PyObject *folded = PyTuple_New(n);
3691 if (folded == NULL) {
3692 return 0;
3693 }
3694 PyObject *val;
3695 for (i = 0; i < n; i++) {
3696 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3697 Py_INCREF(val);
3698 PyTuple_SET_ITEM(folded, i, val);
3699 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003700 if (tuple) {
3701 ADDOP_LOAD_CONST_NEW(c, folded);
3702 } else {
3703 if (add == SET_ADD) {
3704 Py_SETREF(folded, PyFrozenSet_New(folded));
3705 if (folded == NULL) {
3706 return 0;
3707 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003708 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003709 ADDOP_I(c, build, pushed);
3710 ADDOP_LOAD_CONST_NEW(c, folded);
3711 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003712 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003713 return 1;
3714 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003715
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003716 for (i = 0; i < n; i++) {
3717 expr_ty elt = asdl_seq_GET(elts, i);
3718 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003719 seen_star = 1;
3720 }
3721 }
3722 if (seen_star) {
3723 seen_star = 0;
3724 for (i = 0; i < n; i++) {
3725 expr_ty elt = asdl_seq_GET(elts, i);
3726 if (elt->kind == Starred_kind) {
3727 if (seen_star == 0) {
3728 ADDOP_I(c, build, i+pushed);
3729 seen_star = 1;
3730 }
3731 VISIT(c, expr, elt->v.Starred.value);
3732 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003733 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003734 else {
3735 VISIT(c, expr, elt);
3736 if (seen_star) {
3737 ADDOP_I(c, add, 1);
3738 }
3739 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003740 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003741 assert(seen_star);
3742 if (tuple) {
3743 ADDOP(c, LIST_TO_TUPLE);
3744 }
3745 }
3746 else {
3747 for (i = 0; i < n; i++) {
3748 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003750 }
3751 if (tuple) {
3752 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3753 } else {
3754 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003755 }
3756 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003757 return 1;
3758}
3759
3760static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003761assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003762{
3763 Py_ssize_t n = asdl_seq_LEN(elts);
3764 Py_ssize_t i;
3765 int seen_star = 0;
3766 for (i = 0; i < n; i++) {
3767 expr_ty elt = asdl_seq_GET(elts, i);
3768 if (elt->kind == Starred_kind && !seen_star) {
3769 if ((i >= (1 << 8)) ||
3770 (n-i-1 >= (INT_MAX >> 8)))
3771 return compiler_error(c,
3772 "too many expressions in "
3773 "star-unpacking assignment");
3774 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3775 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003776 }
3777 else if (elt->kind == Starred_kind) {
3778 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003779 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003780 }
3781 }
3782 if (!seen_star) {
3783 ADDOP_I(c, UNPACK_SEQUENCE, n);
3784 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003785 for (i = 0; i < n; i++) {
3786 expr_ty elt = asdl_seq_GET(elts, i);
3787 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3788 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 return 1;
3790}
3791
3792static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003793compiler_list(struct compiler *c, expr_ty e)
3794{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003795 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003796 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003797 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003798 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003799 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003800 return starunpack_helper(c, elts, 0, BUILD_LIST,
3801 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003802 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003803 else
3804 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003805 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003806}
3807
3808static int
3809compiler_tuple(struct compiler *c, expr_ty e)
3810{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003811 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003812 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003813 return assignment_helper(c, elts);
3814 }
3815 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003816 return starunpack_helper(c, elts, 0, BUILD_LIST,
3817 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003818 }
3819 else
3820 VISIT_SEQ(c, expr, elts);
3821 return 1;
3822}
3823
3824static int
3825compiler_set(struct compiler *c, expr_ty e)
3826{
Mark Shannon13bc1392020-01-23 09:25:17 +00003827 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3828 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003829}
3830
3831static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003832are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003833{
3834 Py_ssize_t i;
3835 for (i = begin; i < end; i++) {
3836 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003837 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003838 return 0;
3839 }
3840 return 1;
3841}
3842
3843static int
3844compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3845{
3846 Py_ssize_t i, n = end - begin;
3847 PyObject *keys, *key;
3848 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3849 for (i = begin; i < end; i++) {
3850 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3851 }
3852 keys = PyTuple_New(n);
3853 if (keys == NULL) {
3854 return 0;
3855 }
3856 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003857 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003858 Py_INCREF(key);
3859 PyTuple_SET_ITEM(keys, i - begin, key);
3860 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003861 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003862 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3863 }
3864 else {
3865 for (i = begin; i < end; i++) {
3866 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3867 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3868 }
3869 ADDOP_I(c, BUILD_MAP, n);
3870 }
3871 return 1;
3872}
3873
3874static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003875compiler_dict(struct compiler *c, expr_ty e)
3876{
Victor Stinner976bb402016-03-23 11:36:19 +01003877 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003878 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003879 int is_unpacking = 0;
3880 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003881 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003882 elements = 0;
3883 for (i = 0; i < n; i++) {
3884 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003885 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003886 if (elements) {
3887 if (!compiler_subdict(c, e, i - elements, i)) {
3888 return 0;
3889 }
3890 if (have_dict) {
3891 ADDOP_I(c, DICT_UPDATE, 1);
3892 }
3893 have_dict = 1;
3894 elements = 0;
3895 }
3896 if (have_dict == 0) {
3897 ADDOP_I(c, BUILD_MAP, 0);
3898 have_dict = 1;
3899 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003900 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003901 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003902 }
3903 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003904 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003905 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003906 return 0;
3907 }
3908 if (have_dict) {
3909 ADDOP_I(c, DICT_UPDATE, 1);
3910 }
3911 have_dict = 1;
3912 elements = 0;
3913 }
3914 else {
3915 elements++;
3916 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003917 }
3918 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003919 if (elements) {
3920 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003921 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003922 }
3923 if (have_dict) {
3924 ADDOP_I(c, DICT_UPDATE, 1);
3925 }
3926 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003927 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003928 if (!have_dict) {
3929 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 }
3931 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003932}
3933
3934static int
3935compiler_compare(struct compiler *c, expr_ty e)
3936{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003937 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003939 if (!check_compare(c, e)) {
3940 return 0;
3941 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003943 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3944 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3945 if (n == 0) {
3946 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003947 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003948 }
3949 else {
3950 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003951 if (cleanup == NULL)
3952 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003953 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003954 VISIT(c, expr,
3955 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003956 ADDOP(c, DUP_TOP);
3957 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003958 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003959 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003960 NEXT_BLOCK(c);
3961 }
3962 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003963 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003964 basicblock *end = compiler_new_block(c);
3965 if (end == NULL)
3966 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00003967 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003968 compiler_use_next_block(c, cleanup);
3969 ADDOP(c, ROT_TWO);
3970 ADDOP(c, POP_TOP);
3971 compiler_use_next_block(c, end);
3972 }
3973 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003974}
3975
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003976static PyTypeObject *
3977infer_type(expr_ty e)
3978{
3979 switch (e->kind) {
3980 case Tuple_kind:
3981 return &PyTuple_Type;
3982 case List_kind:
3983 case ListComp_kind:
3984 return &PyList_Type;
3985 case Dict_kind:
3986 case DictComp_kind:
3987 return &PyDict_Type;
3988 case Set_kind:
3989 case SetComp_kind:
3990 return &PySet_Type;
3991 case GeneratorExp_kind:
3992 return &PyGen_Type;
3993 case Lambda_kind:
3994 return &PyFunction_Type;
3995 case JoinedStr_kind:
3996 case FormattedValue_kind:
3997 return &PyUnicode_Type;
3998 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003999 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004000 default:
4001 return NULL;
4002 }
4003}
4004
4005static int
4006check_caller(struct compiler *c, expr_ty e)
4007{
4008 switch (e->kind) {
4009 case Constant_kind:
4010 case Tuple_kind:
4011 case List_kind:
4012 case ListComp_kind:
4013 case Dict_kind:
4014 case DictComp_kind:
4015 case Set_kind:
4016 case SetComp_kind:
4017 case GeneratorExp_kind:
4018 case JoinedStr_kind:
4019 case FormattedValue_kind:
4020 return compiler_warn(c, "'%.200s' object is not callable; "
4021 "perhaps you missed a comma?",
4022 infer_type(e)->tp_name);
4023 default:
4024 return 1;
4025 }
4026}
4027
4028static int
4029check_subscripter(struct compiler *c, expr_ty e)
4030{
4031 PyObject *v;
4032
4033 switch (e->kind) {
4034 case Constant_kind:
4035 v = e->v.Constant.value;
4036 if (!(v == Py_None || v == Py_Ellipsis ||
4037 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4038 PyAnySet_Check(v)))
4039 {
4040 return 1;
4041 }
4042 /* fall through */
4043 case Set_kind:
4044 case SetComp_kind:
4045 case GeneratorExp_kind:
4046 case Lambda_kind:
4047 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4048 "perhaps you missed a comma?",
4049 infer_type(e)->tp_name);
4050 default:
4051 return 1;
4052 }
4053}
4054
4055static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004056check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004057{
4058 PyObject *v;
4059
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004060 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004061 if (index_type == NULL
4062 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4063 || index_type == &PySlice_Type) {
4064 return 1;
4065 }
4066
4067 switch (e->kind) {
4068 case Constant_kind:
4069 v = e->v.Constant.value;
4070 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4071 return 1;
4072 }
4073 /* fall through */
4074 case Tuple_kind:
4075 case List_kind:
4076 case ListComp_kind:
4077 case JoinedStr_kind:
4078 case FormattedValue_kind:
4079 return compiler_warn(c, "%.200s indices must be integers or slices, "
4080 "not %.200s; "
4081 "perhaps you missed a comma?",
4082 infer_type(e)->tp_name,
4083 index_type->tp_name);
4084 default:
4085 return 1;
4086 }
4087}
4088
Zackery Spytz97f5de02019-03-22 01:30:32 -06004089// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004090static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004091maybe_optimize_method_call(struct compiler *c, expr_ty e)
4092{
4093 Py_ssize_t argsl, i;
4094 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004095 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004096
4097 /* Check that the call node is an attribute access, and that
4098 the call doesn't have keyword parameters. */
4099 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4100 asdl_seq_LEN(e->v.Call.keywords))
4101 return -1;
4102
4103 /* Check that there are no *varargs types of arguments. */
4104 argsl = asdl_seq_LEN(args);
4105 for (i = 0; i < argsl; i++) {
4106 expr_ty elt = asdl_seq_GET(args, i);
4107 if (elt->kind == Starred_kind) {
4108 return -1;
4109 }
4110 }
4111
4112 /* Alright, we can optimize the code. */
4113 VISIT(c, expr, meth->v.Attribute.value);
4114 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4115 VISIT_SEQ(c, expr, e->v.Call.args);
4116 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4117 return 1;
4118}
4119
4120static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004121validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004122{
4123 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4124 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004125 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4126 if (key->arg == NULL) {
4127 continue;
4128 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004129 if (forbidden_name(c, key->arg, Store)) {
4130 return -1;
4131 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004132 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004133 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4134 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4135 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4136 if (msg == NULL) {
4137 return -1;
4138 }
4139 c->u->u_col_offset = other->col_offset;
4140 compiler_error(c, PyUnicode_AsUTF8(msg));
4141 Py_DECREF(msg);
4142 return -1;
4143 }
4144 }
4145 }
4146 return 0;
4147}
4148
4149static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004150compiler_call(struct compiler *c, expr_ty e)
4151{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004152 int ret = maybe_optimize_method_call(c, e);
4153 if (ret >= 0) {
4154 return ret;
4155 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004156 if (!check_caller(c, e->v.Call.func)) {
4157 return 0;
4158 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004159 VISIT(c, expr, e->v.Call.func);
4160 return compiler_call_helper(c, 0,
4161 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004162 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004163}
4164
Eric V. Smith235a6f02015-09-19 14:51:32 -04004165static int
4166compiler_joined_str(struct compiler *c, expr_ty e)
4167{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004168 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004169 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4170 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004171 return 1;
4172}
4173
Eric V. Smitha78c7952015-11-03 12:45:05 -05004174/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004175static int
4176compiler_formatted_value(struct compiler *c, expr_ty e)
4177{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004178 /* Our oparg encodes 2 pieces of information: the conversion
4179 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004180
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004181 Convert the conversion char to 3 bits:
4182 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004183 !s : 001 0x1 FVC_STR
4184 !r : 010 0x2 FVC_REPR
4185 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004186
Eric V. Smitha78c7952015-11-03 12:45:05 -05004187 next bit is whether or not we have a format spec:
4188 yes : 100 0x4
4189 no : 000 0x0
4190 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004191
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004192 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004193 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004194
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004195 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004196 VISIT(c, expr, e->v.FormattedValue.value);
4197
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004198 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004199 case 's': oparg = FVC_STR; break;
4200 case 'r': oparg = FVC_REPR; break;
4201 case 'a': oparg = FVC_ASCII; break;
4202 case -1: oparg = FVC_NONE; break;
4203 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004204 PyErr_Format(PyExc_SystemError,
4205 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004206 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004207 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004208 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004209 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004210 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004211 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004212 }
4213
Eric V. Smitha78c7952015-11-03 12:45:05 -05004214 /* And push our opcode and oparg */
4215 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004216
Eric V. Smith235a6f02015-09-19 14:51:32 -04004217 return 1;
4218}
4219
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004220static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004221compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004222{
4223 Py_ssize_t i, n = end - begin;
4224 keyword_ty kw;
4225 PyObject *keys, *key;
4226 assert(n > 0);
4227 if (n > 1) {
4228 for (i = begin; i < end; i++) {
4229 kw = asdl_seq_GET(keywords, i);
4230 VISIT(c, expr, kw->value);
4231 }
4232 keys = PyTuple_New(n);
4233 if (keys == NULL) {
4234 return 0;
4235 }
4236 for (i = begin; i < end; i++) {
4237 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4238 Py_INCREF(key);
4239 PyTuple_SET_ITEM(keys, i - begin, key);
4240 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004241 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004242 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4243 }
4244 else {
4245 /* a for loop only executes once */
4246 for (i = begin; i < end; i++) {
4247 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004248 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004249 VISIT(c, expr, kw->value);
4250 }
4251 ADDOP_I(c, BUILD_MAP, n);
4252 }
4253 return 1;
4254}
4255
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004256/* shared code between compiler_call and compiler_class */
4257static int
4258compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004259 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004260 asdl_expr_seq *args,
4261 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004262{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004263 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004264
Pablo Galindo254ec782020-04-03 20:37:13 +01004265 if (validate_keywords(c, keywords) == -1) {
4266 return 0;
4267 }
4268
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004269 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004270 nkwelts = asdl_seq_LEN(keywords);
4271
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004272 for (i = 0; i < nelts; i++) {
4273 expr_ty elt = asdl_seq_GET(args, i);
4274 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004275 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004276 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004277 }
4278 for (i = 0; i < nkwelts; i++) {
4279 keyword_ty kw = asdl_seq_GET(keywords, i);
4280 if (kw->arg == NULL) {
4281 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004282 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004283 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004284
Mark Shannon13bc1392020-01-23 09:25:17 +00004285 /* No * or ** args, so can use faster calling sequence */
4286 for (i = 0; i < nelts; i++) {
4287 expr_ty elt = asdl_seq_GET(args, i);
4288 assert(elt->kind != Starred_kind);
4289 VISIT(c, expr, elt);
4290 }
4291 if (nkwelts) {
4292 PyObject *names;
4293 VISIT_SEQ(c, keyword, keywords);
4294 names = PyTuple_New(nkwelts);
4295 if (names == NULL) {
4296 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004297 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004298 for (i = 0; i < nkwelts; i++) {
4299 keyword_ty kw = asdl_seq_GET(keywords, i);
4300 Py_INCREF(kw->arg);
4301 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004302 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004303 ADDOP_LOAD_CONST_NEW(c, names);
4304 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4305 return 1;
4306 }
4307 else {
4308 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4309 return 1;
4310 }
4311
4312ex_call:
4313
4314 /* Do positional arguments. */
4315 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4316 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4317 }
4318 else if (starunpack_helper(c, args, n, BUILD_LIST,
4319 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4320 return 0;
4321 }
4322 /* Then keyword arguments */
4323 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004324 /* Has a new dict been pushed */
4325 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004326
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004327 nseen = 0; /* the number of keyword arguments on the stack following */
4328 for (i = 0; i < nkwelts; i++) {
4329 keyword_ty kw = asdl_seq_GET(keywords, i);
4330 if (kw->arg == NULL) {
4331 /* A keyword argument unpacking. */
4332 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004333 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004334 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004335 }
Mark Shannondb64f122020-06-01 10:42:42 +01004336 if (have_dict) {
4337 ADDOP_I(c, DICT_MERGE, 1);
4338 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004339 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004340 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004341 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004342 if (!have_dict) {
4343 ADDOP_I(c, BUILD_MAP, 0);
4344 have_dict = 1;
4345 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004346 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004347 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004348 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004349 else {
4350 nseen++;
4351 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004352 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004353 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004354 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004355 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004356 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004357 }
4358 if (have_dict) {
4359 ADDOP_I(c, DICT_MERGE, 1);
4360 }
4361 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004362 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004363 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004365 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4366 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004367}
4368
Nick Coghlan650f0d02007-04-15 12:05:43 +00004369
4370/* List and set comprehensions and generator expressions work by creating a
4371 nested function to perform the actual iteration. This means that the
4372 iteration variables don't leak into the current scope.
4373 The defined function is called immediately following its definition, with the
4374 result of that call being the result of the expression.
4375 The LC/SC version returns the populated container, while the GE version is
4376 flagged in symtable.c as a generator, so it returns the generator object
4377 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004378
4379 Possible cleanups:
4380 - iterate over the generator sequence instead of using recursion
4381*/
4382
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004383
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004384static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004386 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004387 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004389{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004390 comprehension_ty gen;
4391 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4392 if (gen->is_async) {
4393 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004394 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004395 } else {
4396 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004397 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004398 }
4399}
4400
4401static int
4402compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004403 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004404 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004405 expr_ty elt, expr_ty val, int type)
4406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 /* generate code for the iterator, then each of the ifs,
4408 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004410 comprehension_ty gen;
4411 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004412 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004414 start = compiler_new_block(c);
4415 skip = compiler_new_block(c);
4416 if_cleanup = compiler_new_block(c);
4417 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004419 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4420 anchor == NULL)
4421 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 if (gen_index == 0) {
4426 /* Receive outermost iter as an implicit argument */
4427 c->u->u_argcount = 1;
4428 ADDOP_I(c, LOAD_FAST, 0);
4429 }
4430 else {
4431 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004432 /* Fast path for the temporary variable assignment idiom:
4433 for y in [f(x)]
4434 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004435 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004436 switch (gen->iter->kind) {
4437 case List_kind:
4438 elts = gen->iter->v.List.elts;
4439 break;
4440 case Tuple_kind:
4441 elts = gen->iter->v.Tuple.elts;
4442 break;
4443 default:
4444 elts = NULL;
4445 }
4446 if (asdl_seq_LEN(elts) == 1) {
4447 expr_ty elt = asdl_seq_GET(elts, 0);
4448 if (elt->kind != Starred_kind) {
4449 VISIT(c, expr, elt);
4450 start = NULL;
4451 }
4452 }
4453 if (start) {
4454 VISIT(c, expr, gen->iter);
4455 ADDOP(c, GET_ITER);
4456 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004458 if (start) {
4459 depth++;
4460 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004461 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004462 NEXT_BLOCK(c);
4463 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004466 /* XXX this needs to be cleaned up...a lot! */
4467 n = asdl_seq_LEN(gen->ifs);
4468 for (i = 0; i < n; i++) {
4469 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004470 if (!compiler_jump_if(c, e, if_cleanup, 0))
4471 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 NEXT_BLOCK(c);
4473 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 if (++gen_index < asdl_seq_LEN(generators))
4476 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004477 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 elt, val, type))
4479 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 /* only append after the last for generator */
4482 if (gen_index >= asdl_seq_LEN(generators)) {
4483 /* comprehension specific code */
4484 switch (type) {
4485 case COMP_GENEXP:
4486 VISIT(c, expr, elt);
4487 ADDOP(c, YIELD_VALUE);
4488 ADDOP(c, POP_TOP);
4489 break;
4490 case COMP_LISTCOMP:
4491 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004492 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004493 break;
4494 case COMP_SETCOMP:
4495 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004496 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004497 break;
4498 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004499 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004500 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004502 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004503 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004504 break;
4505 default:
4506 return 0;
4507 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004509 compiler_use_next_block(c, skip);
4510 }
4511 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004512 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004513 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004514 compiler_use_next_block(c, anchor);
4515 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004516
4517 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004518}
4519
4520static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004521compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004522 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004523 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 expr_ty elt, expr_ty val, int type)
4525{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004526 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004527 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004529 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004532
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004533 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004534 return 0;
4535 }
4536
4537 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4538
4539 if (gen_index == 0) {
4540 /* Receive outermost iter as an implicit argument */
4541 c->u->u_argcount = 1;
4542 ADDOP_I(c, LOAD_FAST, 0);
4543 }
4544 else {
4545 /* Sub-iter - calculate on the fly */
4546 VISIT(c, expr, gen->iter);
4547 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004548 }
4549
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004550 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004551
Mark Shannon582aaf12020-08-04 17:30:11 +01004552 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004554 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004555 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004556 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004557 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004558
4559 n = asdl_seq_LEN(gen->ifs);
4560 for (i = 0; i < n; i++) {
4561 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004562 if (!compiler_jump_if(c, e, if_cleanup, 0))
4563 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004564 NEXT_BLOCK(c);
4565 }
4566
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004567 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004568 if (++gen_index < asdl_seq_LEN(generators))
4569 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004570 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004571 elt, val, type))
4572 return 0;
4573
4574 /* only append after the last for generator */
4575 if (gen_index >= asdl_seq_LEN(generators)) {
4576 /* comprehension specific code */
4577 switch (type) {
4578 case COMP_GENEXP:
4579 VISIT(c, expr, elt);
4580 ADDOP(c, YIELD_VALUE);
4581 ADDOP(c, POP_TOP);
4582 break;
4583 case COMP_LISTCOMP:
4584 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004585 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004586 break;
4587 case COMP_SETCOMP:
4588 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004589 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004590 break;
4591 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004592 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004593 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004594 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004595 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004596 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004597 break;
4598 default:
4599 return 0;
4600 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004601 }
4602 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004603 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004604
4605 compiler_use_next_block(c, except);
4606 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004607
4608 return 1;
4609}
4610
4611static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004612compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004613 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004614 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004617 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004618 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004619 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004620 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004621
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004622
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004623 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004624
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004625 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004626 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4627 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004628 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004629 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004630 }
4631
4632 is_async_generator = c->u->u_ste->ste_coroutine;
4633
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004634 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004635 compiler_error(c, "asynchronous comprehension outside of "
4636 "an asynchronous function");
4637 goto error_in_scope;
4638 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 if (type != COMP_GENEXP) {
4641 int op;
4642 switch (type) {
4643 case COMP_LISTCOMP:
4644 op = BUILD_LIST;
4645 break;
4646 case COMP_SETCOMP:
4647 op = BUILD_SET;
4648 break;
4649 case COMP_DICTCOMP:
4650 op = BUILD_MAP;
4651 break;
4652 default:
4653 PyErr_Format(PyExc_SystemError,
4654 "unknown comprehension type %d", type);
4655 goto error_in_scope;
4656 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 ADDOP_I(c, op, 0);
4659 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004660
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004661 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 val, type))
4663 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 if (type != COMP_GENEXP) {
4666 ADDOP(c, RETURN_VALUE);
4667 }
4668
4669 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004670 qualname = c->u->u_qualname;
4671 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004673 if (top_level_await && is_async_generator){
4674 c->u->u_ste->ste_coroutine = 1;
4675 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004676 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 goto error;
4678
Victor Stinnerba7a99d2021-01-30 01:46:44 +01004679 if (!compiler_make_closure(c, co, 0, qualname)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 goto error;
Victor Stinnerba7a99d2021-01-30 01:46:44 +01004681 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004682 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 Py_DECREF(co);
4684
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004685 VISIT(c, expr, outermost->iter);
4686
4687 if (outermost->is_async) {
4688 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004689 } else {
4690 ADDOP(c, GET_ITER);
4691 }
4692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004694
4695 if (is_async_generator && type != COMP_GENEXP) {
4696 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004697 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004698 ADDOP(c, YIELD_FROM);
4699 }
4700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004702error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004704error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004705 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 Py_XDECREF(co);
4707 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004708}
4709
4710static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004711compiler_genexp(struct compiler *c, expr_ty e)
4712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 static identifier name;
4714 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004715 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 if (!name)
4717 return 0;
4718 }
4719 assert(e->kind == GeneratorExp_kind);
4720 return compiler_comprehension(c, e, COMP_GENEXP, name,
4721 e->v.GeneratorExp.generators,
4722 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004723}
4724
4725static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004726compiler_listcomp(struct compiler *c, expr_ty e)
4727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 static identifier name;
4729 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004730 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 if (!name)
4732 return 0;
4733 }
4734 assert(e->kind == ListComp_kind);
4735 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4736 e->v.ListComp.generators,
4737 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004738}
4739
4740static int
4741compiler_setcomp(struct compiler *c, expr_ty e)
4742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 static identifier name;
4744 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004745 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 if (!name)
4747 return 0;
4748 }
4749 assert(e->kind == SetComp_kind);
4750 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4751 e->v.SetComp.generators,
4752 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004753}
4754
4755
4756static int
4757compiler_dictcomp(struct compiler *c, expr_ty e)
4758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 static identifier name;
4760 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004761 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 if (!name)
4763 return 0;
4764 }
4765 assert(e->kind == DictComp_kind);
4766 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4767 e->v.DictComp.generators,
4768 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004769}
4770
4771
4772static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004773compiler_visit_keyword(struct compiler *c, keyword_ty k)
4774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 VISIT(c, expr, k->value);
4776 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004777}
4778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004780 whether they are true or false.
4781
4782 Return values: 1 for true, 0 for false, -1 for non-constant.
4783 */
4784
4785static int
Mark Shannonfee55262019-11-21 09:11:43 +00004786compiler_with_except_finish(struct compiler *c) {
4787 basicblock *exit;
4788 exit = compiler_new_block(c);
4789 if (exit == NULL)
4790 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004791 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004792 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004793 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004794 compiler_use_next_block(c, exit);
4795 ADDOP(c, POP_TOP);
4796 ADDOP(c, POP_TOP);
4797 ADDOP(c, POP_TOP);
4798 ADDOP(c, POP_EXCEPT);
4799 ADDOP(c, POP_TOP);
4800 return 1;
4801}
Yury Selivanov75445082015-05-11 22:57:16 -04004802
4803/*
4804 Implements the async with statement.
4805
4806 The semantics outlined in that PEP are as follows:
4807
4808 async with EXPR as VAR:
4809 BLOCK
4810
4811 It is implemented roughly as:
4812
4813 context = EXPR
4814 exit = context.__aexit__ # not calling it
4815 value = await context.__aenter__()
4816 try:
4817 VAR = value # if VAR present in the syntax
4818 BLOCK
4819 finally:
4820 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004821 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004822 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004823 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004824 if not (await exit(*exc)):
4825 raise
4826 */
4827static int
4828compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4829{
Mark Shannonfee55262019-11-21 09:11:43 +00004830 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004831 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4832
4833 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004834 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004835 c->u->u_ste->ste_coroutine = 1;
4836 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004837 return compiler_error(c, "'async with' outside async function");
4838 }
Yury Selivanov75445082015-05-11 22:57:16 -04004839
4840 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004841 final = compiler_new_block(c);
4842 exit = compiler_new_block(c);
4843 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004844 return 0;
4845
4846 /* Evaluate EXPR */
4847 VISIT(c, expr, item->context_expr);
4848
4849 ADDOP(c, BEFORE_ASYNC_WITH);
4850 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004851 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004852 ADDOP(c, YIELD_FROM);
4853
Mark Shannon582aaf12020-08-04 17:30:11 +01004854 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004855
4856 /* SETUP_ASYNC_WITH pushes a finally block. */
4857 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004858 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004859 return 0;
4860 }
4861
4862 if (item->optional_vars) {
4863 VISIT(c, expr, item->optional_vars);
4864 }
4865 else {
4866 /* Discard result from context.__aenter__() */
4867 ADDOP(c, POP_TOP);
4868 }
4869
4870 pos++;
4871 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4872 /* BLOCK code */
4873 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4874 else if (!compiler_async_with(c, s, pos))
4875 return 0;
4876
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004877 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004878 ADDOP(c, POP_BLOCK);
4879 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004880
Mark Shannonfee55262019-11-21 09:11:43 +00004881 /* For successful outcome:
4882 * call __exit__(None, None, None)
4883 */
4884 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004885 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004886 ADDOP(c, GET_AWAITABLE);
4887 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4888 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004889
Mark Shannonfee55262019-11-21 09:11:43 +00004890 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004891
Mark Shannon582aaf12020-08-04 17:30:11 +01004892 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004893
4894 /* For exceptional outcome: */
4895 compiler_use_next_block(c, final);
4896
4897 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004898 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004899 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004900 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004901 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004902
Mark Shannonfee55262019-11-21 09:11:43 +00004903compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004904 return 1;
4905}
4906
4907
Guido van Rossumc2e20742006-02-27 22:32:47 +00004908/*
4909 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004910 with EXPR as VAR:
4911 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004912 is implemented as:
4913 <code for EXPR>
4914 SETUP_WITH E
4915 <code to store to VAR> or POP_TOP
4916 <code for BLOCK>
4917 LOAD_CONST (None, None, None)
4918 CALL_FUNCTION_EX 0
4919 JUMP_FORWARD EXIT
4920 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4921 POP_JUMP_IF_TRUE T:
4922 RERAISE
4923 T: POP_TOP * 3 (remove exception from stack)
4924 POP_EXCEPT
4925 POP_TOP
4926 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004927 */
Mark Shannonfee55262019-11-21 09:11:43 +00004928
Guido van Rossumc2e20742006-02-27 22:32:47 +00004929static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004930compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004931{
Mark Shannonfee55262019-11-21 09:11:43 +00004932 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004933 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004934
4935 assert(s->kind == With_kind);
4936
Guido van Rossumc2e20742006-02-27 22:32:47 +00004937 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004938 final = compiler_new_block(c);
4939 exit = compiler_new_block(c);
4940 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004941 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004942
Thomas Wouters477c8d52006-05-27 19:21:47 +00004943 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004944 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004945 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004946 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004947
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004948 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004949 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004950 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004951 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004952 }
4953
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004954 if (item->optional_vars) {
4955 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004956 }
4957 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004958 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004959 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004960 }
4961
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004962 pos++;
4963 if (pos == asdl_seq_LEN(s->v.With.items))
4964 /* BLOCK code */
4965 VISIT_SEQ(c, stmt, s->v.With.body)
4966 else if (!compiler_with(c, s, pos))
4967 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004968
Mark Shannon3bd60352021-01-13 12:05:43 +00004969
4970 /* Mark all following code as artificial */
4971 c->u->u_lineno = -1;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004972 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004973 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004974
Mark Shannonfee55262019-11-21 09:11:43 +00004975 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004976
Mark Shannonfee55262019-11-21 09:11:43 +00004977 /* For successful outcome:
4978 * call __exit__(None, None, None)
4979 */
4980 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004981 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004982 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004983 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004984
Mark Shannonfee55262019-11-21 09:11:43 +00004985 /* For exceptional outcome: */
4986 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004987
Mark Shannonfee55262019-11-21 09:11:43 +00004988 ADDOP(c, WITH_EXCEPT_START);
4989 compiler_with_except_finish(c);
4990
4991 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004992 return 1;
4993}
4994
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004995static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004996compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004999 case NamedExpr_kind:
5000 VISIT(c, expr, e->v.NamedExpr.value);
5001 ADDOP(c, DUP_TOP);
5002 VISIT(c, expr, e->v.NamedExpr.target);
5003 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 case BoolOp_kind:
5005 return compiler_boolop(c, e);
5006 case BinOp_kind:
5007 VISIT(c, expr, e->v.BinOp.left);
5008 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05005009 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 break;
5011 case UnaryOp_kind:
5012 VISIT(c, expr, e->v.UnaryOp.operand);
5013 ADDOP(c, unaryop(e->v.UnaryOp.op));
5014 break;
5015 case Lambda_kind:
5016 return compiler_lambda(c, e);
5017 case IfExp_kind:
5018 return compiler_ifexp(c, e);
5019 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005020 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005022 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 case GeneratorExp_kind:
5024 return compiler_genexp(c, e);
5025 case ListComp_kind:
5026 return compiler_listcomp(c, e);
5027 case SetComp_kind:
5028 return compiler_setcomp(c, e);
5029 case DictComp_kind:
5030 return compiler_dictcomp(c, e);
5031 case Yield_kind:
5032 if (c->u->u_ste->ste_type != FunctionBlock)
5033 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005034 if (e->v.Yield.value) {
5035 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005036 }
5037 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005038 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005040 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005042 case YieldFrom_kind:
5043 if (c->u->u_ste->ste_type != FunctionBlock)
5044 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005045
5046 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5047 return compiler_error(c, "'yield from' inside async function");
5048
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005049 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005050 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005051 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005052 ADDOP(c, YIELD_FROM);
5053 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005054 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005055 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005056 if (c->u->u_ste->ste_type != FunctionBlock){
5057 return compiler_error(c, "'await' outside function");
5058 }
Yury Selivanov75445082015-05-11 22:57:16 -04005059
Victor Stinner331a6a52019-05-27 16:39:22 +02005060 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005061 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5062 return compiler_error(c, "'await' outside async function");
5063 }
5064 }
Yury Selivanov75445082015-05-11 22:57:16 -04005065
5066 VISIT(c, expr, e->v.Await.value);
5067 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005068 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005069 ADDOP(c, YIELD_FROM);
5070 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 case Compare_kind:
5072 return compiler_compare(c, e);
5073 case Call_kind:
5074 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005075 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005076 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005077 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005078 case JoinedStr_kind:
5079 return compiler_joined_str(c, e);
5080 case FormattedValue_kind:
5081 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 /* The following exprs can be assignment targets. */
5083 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005084 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005086 case Load:
5087 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5088 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005090 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5091 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5093 break;
5094 case Del:
5095 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5096 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 }
5098 break;
5099 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005100 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005101 case Starred_kind:
5102 switch (e->v.Starred.ctx) {
5103 case Store:
5104 /* In all legitimate cases, the Starred node was already replaced
5105 * by compiler_list/compiler_tuple. XXX: is that okay? */
5106 return compiler_error(c,
5107 "starred assignment target must be in a list or tuple");
5108 default:
5109 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005110 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005111 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005112 break;
5113 case Slice_kind:
5114 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 case Name_kind:
5116 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5117 /* child nodes of List and Tuple will have expr_context set */
5118 case List_kind:
5119 return compiler_list(c, e);
5120 case Tuple_kind:
5121 return compiler_tuple(c, e);
5122 }
5123 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005124}
5125
5126static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005127compiler_visit_expr(struct compiler *c, expr_ty e)
5128{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005129 int old_lineno = c->u->u_lineno;
5130 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005131 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005132 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005133 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005134 c->u->u_col_offset = old_col_offset;
5135 return res;
5136}
5137
5138static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005139compiler_augassign(struct compiler *c, stmt_ty s)
5140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005142 expr_ty e = s->v.AugAssign.target;
5143
5144 int old_lineno = c->u->u_lineno;
5145 int old_col_offset = c->u->u_col_offset;
5146 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005148 switch (e->kind) {
5149 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005150 VISIT(c, expr, e->v.Attribute.value);
5151 ADDOP(c, DUP_TOP);
5152 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 break;
5154 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005155 VISIT(c, expr, e->v.Subscript.value);
5156 VISIT(c, expr, e->v.Subscript.slice);
5157 ADDOP(c, DUP_TOP_TWO);
5158 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 break;
5160 case Name_kind:
5161 if (!compiler_nameop(c, e->v.Name.id, Load))
5162 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005163 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 default:
5165 PyErr_Format(PyExc_SystemError,
5166 "invalid node type (%d) for augmented assignment",
5167 e->kind);
5168 return 0;
5169 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005170
5171 c->u->u_lineno = old_lineno;
5172 c->u->u_col_offset = old_col_offset;
5173
5174 VISIT(c, expr, s->v.AugAssign.value);
5175 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5176
5177 SET_LOC(c, e);
5178
5179 switch (e->kind) {
5180 case Attribute_kind:
5181 ADDOP(c, ROT_TWO);
5182 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5183 break;
5184 case Subscript_kind:
5185 ADDOP(c, ROT_THREE);
5186 ADDOP(c, STORE_SUBSCR);
5187 break;
5188 case Name_kind:
5189 return compiler_nameop(c, e->v.Name.id, Store);
5190 default:
5191 Py_UNREACHABLE();
5192 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005193 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005194}
5195
5196static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005197check_ann_expr(struct compiler *c, expr_ty e)
5198{
5199 VISIT(c, expr, e);
5200 ADDOP(c, POP_TOP);
5201 return 1;
5202}
5203
5204static int
5205check_annotation(struct compiler *c, stmt_ty s)
5206{
5207 /* Annotations are only evaluated in a module or class. */
5208 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5209 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5210 return check_ann_expr(c, s->v.AnnAssign.annotation);
5211 }
5212 return 1;
5213}
5214
5215static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005216check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005217{
5218 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005219 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005220 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005221 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005222 return 0;
5223 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005224 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5225 return 0;
5226 }
5227 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5228 return 0;
5229 }
5230 return 1;
5231 case Tuple_kind: {
5232 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005233 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005234 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005235 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005236 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005237 return 0;
5238 }
5239 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005240 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005241 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005242 default:
5243 return check_ann_expr(c, e);
5244 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005245}
5246
5247static int
5248compiler_annassign(struct compiler *c, stmt_ty s)
5249{
5250 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005251 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005252
5253 assert(s->kind == AnnAssign_kind);
5254
5255 /* We perform the actual assignment first. */
5256 if (s->v.AnnAssign.value) {
5257 VISIT(c, expr, s->v.AnnAssign.value);
5258 VISIT(c, expr, targ);
5259 }
5260 switch (targ->kind) {
5261 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005262 if (forbidden_name(c, targ->v.Name.id, Store))
5263 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005264 /* If we have a simple name in a module or class, store annotation. */
5265 if (s->v.AnnAssign.simple &&
5266 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5267 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005268 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005269 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005270 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005271 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005272 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005273 }
5274 break;
5275 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005276 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5277 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005278 if (!s->v.AnnAssign.value &&
5279 !check_ann_expr(c, targ->v.Attribute.value)) {
5280 return 0;
5281 }
5282 break;
5283 case Subscript_kind:
5284 if (!s->v.AnnAssign.value &&
5285 (!check_ann_expr(c, targ->v.Subscript.value) ||
5286 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5287 return 0;
5288 }
5289 break;
5290 default:
5291 PyErr_Format(PyExc_SystemError,
5292 "invalid node type (%d) for annotated assignment",
5293 targ->kind);
5294 return 0;
5295 }
5296 /* Annotation is evaluated last. */
5297 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5298 return 0;
5299 }
5300 return 1;
5301}
5302
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005303/* Raises a SyntaxError and returns 0.
5304 If something goes wrong, a different exception may be raised.
5305*/
5306
5307static int
5308compiler_error(struct compiler *c, const char *errstr)
5309{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005310 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005311 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005312
Victor Stinner14e461d2013-08-26 22:28:21 +02005313 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 if (!loc) {
5315 Py_INCREF(Py_None);
5316 loc = Py_None;
5317 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005318 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005319 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005320 if (!u)
5321 goto exit;
5322 v = Py_BuildValue("(zO)", errstr, u);
5323 if (!v)
5324 goto exit;
5325 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005326 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005327 Py_DECREF(loc);
5328 Py_XDECREF(u);
5329 Py_XDECREF(v);
5330 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005331}
5332
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005333/* Emits a SyntaxWarning and returns 1 on success.
5334 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5335 and returns 0.
5336*/
5337static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005338compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005339{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005340 va_list vargs;
5341#ifdef HAVE_STDARG_PROTOTYPES
5342 va_start(vargs, format);
5343#else
5344 va_start(vargs);
5345#endif
5346 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5347 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005348 if (msg == NULL) {
5349 return 0;
5350 }
5351 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5352 c->u->u_lineno, NULL, NULL) < 0)
5353 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005354 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005355 /* Replace the SyntaxWarning exception with a SyntaxError
5356 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005357 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005358 assert(PyUnicode_AsUTF8(msg) != NULL);
5359 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005360 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005361 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005362 return 0;
5363 }
5364 Py_DECREF(msg);
5365 return 1;
5366}
5367
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005368static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005369compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005370{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005371 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005374 if (ctx == Load) {
5375 if (!check_subscripter(c, e->v.Subscript.value)) {
5376 return 0;
5377 }
5378 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5379 return 0;
5380 }
5381 }
5382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 case Store: op = STORE_SUBSCR; break;
5386 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005388 assert(op);
5389 VISIT(c, expr, e->v.Subscript.value);
5390 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 ADDOP(c, op);
5392 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005393}
5394
5395static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005396compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005398 int n = 2;
5399 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 /* only handles the cases where BUILD_SLICE is emitted */
5402 if (s->v.Slice.lower) {
5403 VISIT(c, expr, s->v.Slice.lower);
5404 }
5405 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005406 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005407 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 if (s->v.Slice.upper) {
5410 VISIT(c, expr, s->v.Slice.upper);
5411 }
5412 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005413 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 }
5415
5416 if (s->v.Slice.step) {
5417 n++;
5418 VISIT(c, expr, s->v.Slice.step);
5419 }
5420 ADDOP_I(c, BUILD_SLICE, n);
5421 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005422}
5423
Thomas Wouters89f507f2006-12-13 04:49:30 +00005424/* End of the compiler section, beginning of the assembler section */
5425
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005426/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005427 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005428
5429 XXX must handle implicit jumps from one block to next
5430*/
5431
Thomas Wouters89f507f2006-12-13 04:49:30 +00005432struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 PyObject *a_bytecode; /* string containing bytecode */
5434 int a_offset; /* offset into bytecode */
5435 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 PyObject *a_lnotab; /* string containing lnotab */
5437 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005438 int a_prevlineno; /* lineno of last emitted line in line table */
5439 int a_lineno; /* lineno of last emitted instruction */
5440 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005441 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005442};
5443
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005444Py_LOCAL_INLINE(void)
5445stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005446{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005447 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005448 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005449 assert(b->b_startdepth < 0);
5450 b->b_startdepth = depth;
5451 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005452 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005453}
5454
5455/* Find the flow path that needs the largest stack. We assume that
5456 * cycles in the flow graph have no net effect on the stack depth.
5457 */
5458static int
5459stackdepth(struct compiler *c)
5460{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005461 basicblock *b, *entryblock = NULL;
5462 basicblock **stack, **sp;
5463 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005464 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005465 b->b_startdepth = INT_MIN;
5466 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005467 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 }
5469 if (!entryblock)
5470 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005471 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5472 if (!stack) {
5473 PyErr_NoMemory();
5474 return -1;
5475 }
5476
5477 sp = stack;
5478 stackdepth_push(&sp, entryblock, 0);
5479 while (sp != stack) {
5480 b = *--sp;
5481 int depth = b->b_startdepth;
5482 assert(depth >= 0);
5483 basicblock *next = b->b_next;
5484 for (int i = 0; i < b->b_iused; i++) {
5485 struct instr *instr = &b->b_instr[i];
5486 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5487 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinnerba7a99d2021-01-30 01:46:44 +01005488 PyErr_Format(PyExc_SystemError,
5489 "compiler stack_effect(opcode=%d, arg=%i) failed",
5490 instr->i_opcode, instr->i_oparg);
5491 return -1;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005492 }
5493 int new_depth = depth + effect;
5494 if (new_depth > maxdepth) {
5495 maxdepth = new_depth;
5496 }
5497 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005498 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005499 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5500 assert(effect != PY_INVALID_STACK_EFFECT);
5501 int target_depth = depth + effect;
5502 if (target_depth > maxdepth) {
5503 maxdepth = target_depth;
5504 }
5505 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005506 stackdepth_push(&sp, instr->i_target, target_depth);
5507 }
5508 depth = new_depth;
5509 if (instr->i_opcode == JUMP_ABSOLUTE ||
5510 instr->i_opcode == JUMP_FORWARD ||
5511 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005512 instr->i_opcode == RAISE_VARARGS ||
5513 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005514 {
5515 /* remaining code is dead */
5516 next = NULL;
5517 break;
5518 }
5519 }
5520 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005521 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005522 stackdepth_push(&sp, next, depth);
5523 }
5524 }
5525 PyObject_Free(stack);
5526 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005527}
5528
5529static int
5530assemble_init(struct assembler *a, int nblocks, int firstlineno)
5531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005533 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005534 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005536 if (a->a_bytecode == NULL) {
5537 goto error;
5538 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005540 if (a->a_lnotab == NULL) {
5541 goto error;
5542 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005543 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005545 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005548error:
5549 Py_XDECREF(a->a_bytecode);
5550 Py_XDECREF(a->a_lnotab);
5551 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005552}
5553
5554static void
5555assemble_free(struct assembler *a)
5556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005557 Py_XDECREF(a->a_bytecode);
5558 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005559}
5560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005561static int
5562blocksize(basicblock *b)
5563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005564 int i;
5565 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005567 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005568 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005570}
5571
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005572static int
Mark Shannon877df852020-11-12 09:43:29 +00005573assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005574{
Mark Shannon877df852020-11-12 09:43:29 +00005575 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 if (a->a_lnotab_off + 2 >= len) {
5577 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5578 return 0;
5579 }
Pablo Galindo86e322f2021-01-30 13:54:22 +00005580 unsigned char *lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab);
5581 lnotab += a->a_lnotab_off;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005583 *lnotab++ = bdelta;
5584 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005586}
5587
Mark Shannon877df852020-11-12 09:43:29 +00005588/* Appends a range to the end of the line number table. See
5589 * Objects/lnotab_notes.txt for the description of the line number table. */
5590
5591static int
5592assemble_line_range(struct assembler *a)
5593{
5594 int ldelta, bdelta;
5595 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5596 if (bdelta == 0) {
5597 return 1;
5598 }
5599 if (a->a_lineno < 0) {
5600 ldelta = -128;
5601 }
5602 else {
5603 ldelta = a->a_lineno - a->a_prevlineno;
5604 a->a_prevlineno = a->a_lineno;
5605 while (ldelta > 127) {
5606 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5607 return 0;
5608 }
5609 ldelta -= 127;
5610 }
5611 while (ldelta < -127) {
5612 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5613 return 0;
5614 }
5615 ldelta += 127;
5616 }
5617 }
5618 assert(-128 <= ldelta && ldelta < 128);
5619 while (bdelta > 254) {
5620 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5621 return 0;
5622 }
5623 ldelta = a->a_lineno < 0 ? -128 : 0;
5624 bdelta -= 254;
5625 }
5626 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5627 return 0;
5628 }
5629 a->a_lineno_start = a->a_offset;
5630 return 1;
5631}
5632
5633static int
5634assemble_lnotab(struct assembler *a, struct instr *i)
5635{
5636 if (i->i_lineno == a->a_lineno) {
5637 return 1;
5638 }
5639 if (!assemble_line_range(a)) {
5640 return 0;
5641 }
5642 a->a_lineno = i->i_lineno;
5643 return 1;
5644}
5645
5646
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005647/* assemble_emit()
5648 Extend the bytecode with a new instruction.
5649 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005650*/
5651
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005652static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005653assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005654{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005655 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005657 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005658
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005659 arg = i->i_oparg;
5660 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005661 if (i->i_lineno && !assemble_lnotab(a, i))
5662 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005663 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 if (len > PY_SSIZE_T_MAX / 2)
5665 return 0;
5666 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5667 return 0;
5668 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005669 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005671 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005673}
5674
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005675static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005676assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005679 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 /* Compute the size of each block and fixup jump args.
5683 Replace block pointer with position in bytecode. */
5684 do {
5685 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005686 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005687 bsize = blocksize(b);
5688 b->b_offset = totsize;
5689 totsize += bsize;
5690 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005691 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5693 bsize = b->b_offset;
5694 for (i = 0; i < b->b_iused; i++) {
5695 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005696 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 /* Relative jumps are computed relative to
5698 the instruction pointer after fetching
5699 the jump instruction.
5700 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005701 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005702 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005703 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005704 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005705 instr->i_oparg -= bsize;
5706 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005707 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005708 if (instrsize(instr->i_oparg) != isize) {
5709 extended_arg_recompile = 1;
5710 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005712 }
5713 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 /* XXX: This is an awful hack that could hurt performance, but
5716 on the bright side it should work until we come up
5717 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005719 The issue is that in the first loop blocksize() is called
5720 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005721 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 So we loop until we stop seeing new EXTENDED_ARGs.
5725 The only EXTENDED_ARGs that could be popping up are
5726 ones in jump instructions. So this should converge
5727 fairly quickly.
5728 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005729 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005730}
5731
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005732static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005733dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005736 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 tuple = PyTuple_New(size);
5739 if (tuple == NULL)
5740 return NULL;
5741 while (PyDict_Next(dict, &pos, &k, &v)) {
5742 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005743 Py_INCREF(k);
5744 assert((i - offset) < size);
5745 assert((i - offset) >= 0);
5746 PyTuple_SET_ITEM(tuple, i - offset, k);
5747 }
5748 return tuple;
5749}
5750
5751static PyObject *
5752consts_dict_keys_inorder(PyObject *dict)
5753{
5754 PyObject *consts, *k, *v;
5755 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5756
5757 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5758 if (consts == NULL)
5759 return NULL;
5760 while (PyDict_Next(dict, &pos, &k, &v)) {
5761 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005762 /* The keys of the dictionary can be tuples wrapping a contant.
5763 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5764 * the object we want is always second. */
5765 if (PyTuple_CheckExact(k)) {
5766 k = PyTuple_GET_ITEM(k, 1);
5767 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005769 assert(i < size);
5770 assert(i >= 0);
5771 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005773 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005774}
5775
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005776static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005777compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005779 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005780 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005782 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 if (ste->ste_nested)
5784 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005785 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005786 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005787 if (!ste->ste_generator && ste->ste_coroutine)
5788 flags |= CO_COROUTINE;
5789 if (ste->ste_generator && ste->ste_coroutine)
5790 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 if (ste->ste_varargs)
5792 flags |= CO_VARARGS;
5793 if (ste->ste_varkeywords)
5794 flags |= CO_VARKEYWORDS;
5795 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 /* (Only) inherit compilerflags in PyCF_MASK */
5798 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005799
Pablo Galindo90235812020-03-15 04:29:22 +00005800 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005801 ste->ste_coroutine &&
5802 !ste->ste_generator) {
5803 flags |= CO_COROUTINE;
5804 }
5805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005806 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005807}
5808
INADA Naokic2e16072018-11-26 21:23:22 +09005809// Merge *tuple* with constant cache.
5810// Unlike merge_consts_recursive(), this function doesn't work recursively.
5811static int
5812merge_const_tuple(struct compiler *c, PyObject **tuple)
5813{
5814 assert(PyTuple_CheckExact(*tuple));
5815
5816 PyObject *key = _PyCode_ConstantKey(*tuple);
5817 if (key == NULL) {
5818 return 0;
5819 }
5820
5821 // t is borrowed reference
5822 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5823 Py_DECREF(key);
5824 if (t == NULL) {
5825 return 0;
5826 }
5827 if (t == key) { // tuple is new constant.
5828 return 1;
5829 }
5830
5831 PyObject *u = PyTuple_GET_ITEM(t, 1);
5832 Py_INCREF(u);
5833 Py_DECREF(*tuple);
5834 *tuple = u;
5835 return 1;
5836}
5837
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005838static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005839makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005842 PyObject *names = NULL;
5843 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 PyObject *name = NULL;
5845 PyObject *freevars = NULL;
5846 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005847 Py_ssize_t nlocals;
5848 int nlocals_int;
5849 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005850 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 names = dict_keys_inorder(c->u->u_names, 0);
5853 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005854 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005855 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005856 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5858 if (!cellvars)
5859 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005860 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 if (!freevars)
5862 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005863
INADA Naokic2e16072018-11-26 21:23:22 +09005864 if (!merge_const_tuple(c, &names) ||
5865 !merge_const_tuple(c, &varnames) ||
5866 !merge_const_tuple(c, &cellvars) ||
5867 !merge_const_tuple(c, &freevars))
5868 {
5869 goto error;
5870 }
5871
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005872 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005873 assert(nlocals < INT_MAX);
5874 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005876 flags = compute_code_flags(c);
5877 if (flags < 0)
5878 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005879
Mark Shannon6e8128f2020-07-30 10:03:00 +01005880 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5881 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005882 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005883 }
INADA Naokic2e16072018-11-26 21:23:22 +09005884 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005885 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005886 goto error;
5887 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005888
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005889 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005890 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005891 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005892 maxdepth = stackdepth(c);
5893 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005894 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005895 goto error;
5896 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005897 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005898 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005899 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005900 varnames, freevars, cellvars, c->c_filename,
5901 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005902 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005903 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 Py_XDECREF(names);
5905 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005906 Py_XDECREF(name);
5907 Py_XDECREF(freevars);
5908 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005909 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005910}
5911
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005912
5913/* For debugging purposes only */
5914#if 0
5915static void
5916dump_instr(const struct instr *i)
5917{
Mark Shannon582aaf12020-08-04 17:30:11 +01005918 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5919 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005920 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005922 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005923 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005924 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005925 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5927 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005928}
5929
5930static void
5931dump_basicblock(const basicblock *b)
5932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005933 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005934 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5935 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 if (b->b_instr) {
5937 int i;
5938 for (i = 0; i < b->b_iused; i++) {
5939 fprintf(stderr, " [%02d] ", i);
5940 dump_instr(b->b_instr + i);
5941 }
5942 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005943}
5944#endif
5945
Mark Shannon5977a792020-12-02 13:31:40 +00005946
5947static int
5948normalize_basic_block(basicblock *bb);
5949
Mark Shannon6e8128f2020-07-30 10:03:00 +01005950static int
5951optimize_cfg(struct assembler *a, PyObject *consts);
5952
Mark Shannon5977a792020-12-02 13:31:40 +00005953static int
5954ensure_exits_have_lineno(struct compiler *c);
5955
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005956static PyCodeObject *
5957assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005959 basicblock *b, *entryblock;
5960 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005961 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005963 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005965 /* Make sure every block that falls off the end returns None.
5966 XXX NEXT_BLOCK() isn't quite right, because if the last
5967 block ends with a jump or return b_next shouldn't set.
5968 */
5969 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005970 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005971 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005972 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005973 ADDOP(c, RETURN_VALUE);
5974 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005975
Mark Shannon5977a792020-12-02 13:31:40 +00005976 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
5977 if (normalize_basic_block(b)) {
5978 goto error;
5979 }
5980 }
5981
5982 if (ensure_exits_have_lineno(c)) {
5983 goto error;
5984 }
5985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005986 nblocks = 0;
5987 entryblock = NULL;
5988 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5989 nblocks++;
5990 entryblock = b;
5991 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005993 /* Set firstlineno if it wasn't explicitly set. */
5994 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005995 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005996 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005997 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005998 c->u->u_firstlineno = 1;
5999 }
Mark Shannon5977a792020-12-02 13:31:40 +00006000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006001 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6002 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006003 a.a_entry = entryblock;
6004 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006005
Mark Shannon6e8128f2020-07-30 10:03:00 +01006006 consts = consts_dict_keys_inorder(c->u->u_consts);
6007 if (consts == NULL) {
6008 goto error;
6009 }
6010 if (optimize_cfg(&a, consts)) {
6011 goto error;
6012 }
6013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 /* Can't modify the bytecode after computing jump offsets. */
6015 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006016
Mark Shannoncc75ab72020-11-12 19:49:33 +00006017 /* Emit code. */
6018 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 for (j = 0; j < b->b_iused; j++)
6020 if (!assemble_emit(&a, &b->b_instr[j]))
6021 goto error;
6022 }
Mark Shannon877df852020-11-12 09:43:29 +00006023 if (!assemble_line_range(&a)) {
6024 return 0;
6025 }
6026 /* Emit sentinel at end of line number table */
6027 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
6028 goto error;
6029 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006031 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6032 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006033 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006034 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006035
Mark Shannon6e8128f2020-07-30 10:03:00 +01006036 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006037 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006038 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006039 assemble_free(&a);
6040 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006041}
Georg Brandl8334fd92010-12-04 10:26:46 +00006042
6043#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006044PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006045PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6046 PyArena *arena)
6047{
6048 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6049}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006050
6051
6052/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6053 with LOAD_CONST (c1, c2, ... cn).
6054 The consts table must still be in list form so that the
6055 new constant (c1, c2, ... cn) can be appended.
6056 Called with codestr pointing to the first LOAD_CONST.
6057*/
6058static int
6059fold_tuple_on_constants(struct instr *inst,
6060 int n, PyObject *consts)
6061{
6062 /* Pre-conditions */
6063 assert(PyList_CheckExact(consts));
6064 assert(inst[n].i_opcode == BUILD_TUPLE);
6065 assert(inst[n].i_oparg == n);
6066
6067 for (int i = 0; i < n; i++) {
6068 if (inst[i].i_opcode != LOAD_CONST) {
6069 return 0;
6070 }
6071 }
6072
6073 /* Buildup new tuple of constants */
6074 PyObject *newconst = PyTuple_New(n);
6075 if (newconst == NULL) {
6076 return -1;
6077 }
6078 for (int i = 0; i < n; i++) {
6079 int arg = inst[i].i_oparg;
6080 PyObject *constant = PyList_GET_ITEM(consts, arg);
6081 Py_INCREF(constant);
6082 PyTuple_SET_ITEM(newconst, i, constant);
6083 }
6084 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006085 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006086 Py_DECREF(newconst);
6087 PyErr_SetString(PyExc_OverflowError, "too many constants");
6088 return -1;
6089 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006090 if (PyList_Append(consts, newconst)) {
6091 Py_DECREF(newconst);
6092 return -1;
6093 }
6094 Py_DECREF(newconst);
6095 for (int i = 0; i < n; i++) {
6096 inst[i].i_opcode = NOP;
6097 }
6098 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006099 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006100 return 0;
6101}
6102
Mark Shannon28b75c82020-12-23 11:43:10 +00006103
6104static int
6105eliminate_jump_to_jump(basicblock *bb, int opcode) {
6106 assert (bb->b_iused > 0);
6107 struct instr *inst = &bb->b_instr[bb->b_iused-1];
6108 assert (is_jump(inst));
6109 assert (inst->i_target->b_iused > 0);
6110 struct instr *target = &inst->i_target->b_instr[0];
6111 if (inst->i_target == target->i_target) {
6112 /* Nothing to do */
6113 return 0;
6114 }
6115 int lineno = target->i_lineno;
6116 if (add_jump_to_block(bb, opcode, lineno, target->i_target) == 0) {
6117 return -1;
6118 }
6119 assert (bb->b_iused >= 2);
6120 bb->b_instr[bb->b_iused-2].i_opcode = NOP;
6121 return 0;
6122}
6123
Mark Shannoncc75ab72020-11-12 19:49:33 +00006124/* Maximum size of basic block that should be copied in optimizer */
6125#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006126
6127/* Optimization */
6128static int
6129optimize_basic_block(basicblock *bb, PyObject *consts)
6130{
6131 assert(PyList_CheckExact(consts));
6132 struct instr nop;
6133 nop.i_opcode = NOP;
6134 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006135 for (int i = 0; i < bb->b_iused; i++) {
6136 struct instr *inst = &bb->b_instr[i];
6137 int oparg = inst->i_oparg;
6138 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006139 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006140 /* Skip over empty basic blocks. */
6141 while (inst->i_target->b_iused == 0) {
6142 inst->i_target = inst->i_target->b_next;
6143 }
6144 target = &inst->i_target->b_instr[0];
6145 }
6146 else {
6147 target = &nop;
6148 }
6149 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006150 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006151 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006152 {
6153 PyObject* cnt;
6154 int is_true;
6155 int jump_if_true;
6156 switch(nextop) {
6157 case POP_JUMP_IF_FALSE:
6158 case POP_JUMP_IF_TRUE:
6159 cnt = PyList_GET_ITEM(consts, oparg);
6160 is_true = PyObject_IsTrue(cnt);
6161 if (is_true == -1) {
6162 goto error;
6163 }
6164 inst->i_opcode = NOP;
6165 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6166 if (is_true == jump_if_true) {
6167 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6168 bb->b_nofallthrough = 1;
6169 }
6170 else {
6171 bb->b_instr[i+1].i_opcode = NOP;
6172 }
6173 break;
6174 case JUMP_IF_FALSE_OR_POP:
6175 case JUMP_IF_TRUE_OR_POP:
6176 cnt = PyList_GET_ITEM(consts, oparg);
6177 is_true = PyObject_IsTrue(cnt);
6178 if (is_true == -1) {
6179 goto error;
6180 }
6181 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6182 if (is_true == jump_if_true) {
6183 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6184 bb->b_nofallthrough = 1;
6185 }
6186 else {
6187 inst->i_opcode = NOP;
6188 bb->b_instr[i+1].i_opcode = NOP;
6189 }
6190 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006191 }
6192 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006193 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006194
6195 /* Try to fold tuples of constants.
6196 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6197 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6198 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6199 case BUILD_TUPLE:
6200 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6201 switch(oparg) {
6202 case 1:
6203 inst->i_opcode = NOP;
6204 bb->b_instr[i+1].i_opcode = NOP;
6205 break;
6206 case 2:
6207 inst->i_opcode = ROT_TWO;
6208 bb->b_instr[i+1].i_opcode = NOP;
6209 break;
6210 case 3:
6211 inst->i_opcode = ROT_THREE;
6212 bb->b_instr[i+1].i_opcode = ROT_TWO;
6213 }
6214 break;
6215 }
6216 if (i >= oparg) {
6217 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6218 goto error;
6219 }
6220 }
6221 break;
6222
6223 /* Simplify conditional jump to conditional jump where the
6224 result of the first test implies the success of a similar
6225 test or the failure of the opposite test.
6226 Arises in code like:
6227 "a and b or c"
6228 "(a and b) and c"
6229 "(a or b) or c"
6230 "(a or b) and c"
6231 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6232 --> x:JUMP_IF_FALSE_OR_POP z
6233 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6234 --> x:POP_JUMP_IF_FALSE y+1
6235 where y+1 is the instruction following the second test.
6236 */
6237 case JUMP_IF_FALSE_OR_POP:
6238 switch(target->i_opcode) {
6239 case POP_JUMP_IF_FALSE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006240 if (inst->i_lineno == target->i_lineno) {
6241 *inst = *target;
6242 i--;
6243 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006244 break;
6245 case JUMP_ABSOLUTE:
6246 case JUMP_FORWARD:
6247 case JUMP_IF_FALSE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006248 if (inst->i_lineno == target->i_lineno &&
6249 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006250 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006251 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006252 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006253 break;
6254 case JUMP_IF_TRUE_OR_POP:
6255 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006256 if (inst->i_lineno == target->i_lineno) {
6257 inst->i_opcode = POP_JUMP_IF_FALSE;
6258 inst->i_target = inst->i_target->b_next;
6259 --i;
6260 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006261 break;
6262 }
6263 break;
6264
6265 case JUMP_IF_TRUE_OR_POP:
6266 switch(target->i_opcode) {
6267 case POP_JUMP_IF_TRUE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006268 if (inst->i_lineno == target->i_lineno) {
6269 *inst = *target;
6270 i--;
6271 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006272 break;
6273 case JUMP_ABSOLUTE:
6274 case JUMP_FORWARD:
6275 case JUMP_IF_TRUE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006276 if (inst->i_lineno == target->i_lineno &&
6277 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006278 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006279 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006280 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006281 break;
6282 case JUMP_IF_FALSE_OR_POP:
6283 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006284 if (inst->i_lineno == target->i_lineno) {
6285 inst->i_opcode = POP_JUMP_IF_TRUE;
6286 inst->i_target = inst->i_target->b_next;
6287 --i;
6288 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006289 break;
6290 }
6291 break;
6292
6293 case POP_JUMP_IF_FALSE:
6294 switch(target->i_opcode) {
6295 case JUMP_ABSOLUTE:
6296 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006297 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006298 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006299 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006300 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006301 break;
6302 }
6303 break;
6304
6305 case POP_JUMP_IF_TRUE:
6306 switch(target->i_opcode) {
6307 case JUMP_ABSOLUTE:
6308 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006309 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006310 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006311 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006312 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006313 break;
6314 }
6315 break;
6316
6317 case JUMP_ABSOLUTE:
6318 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006319 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006320 switch(target->i_opcode) {
6321 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006322 if (eliminate_jump_to_jump(bb, inst->i_opcode)) {
6323 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006324 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006325 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006326
Mark Shannon6e8128f2020-07-30 10:03:00 +01006327 case JUMP_ABSOLUTE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006328 if (eliminate_jump_to_jump(bb, JUMP_ABSOLUTE)) {
6329 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006330 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006331 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006332 default:
6333 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6334 basicblock *to_copy = inst->i_target;
6335 inst->i_opcode = NOP;
6336 for (i = 0; i < to_copy->b_iused; i++) {
6337 int index = compiler_next_instr(bb);
6338 if (index < 0) {
6339 return -1;
6340 }
6341 bb->b_instr[index] = to_copy->b_instr[i];
6342 }
6343 bb->b_exit = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006344 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006345 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006346 }
6347 }
6348 return 0;
6349error:
6350 return -1;
6351}
6352
6353
6354static void
Mark Shannon1659ad12021-01-13 15:05:04 +00006355clean_basic_block(basicblock *bb, int prev_lineno) {
6356 /* Remove NOPs when legal to do so. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006357 int dest = 0;
6358 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006359 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006360 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006361 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006362 if (lineno < 0) {
6363 continue;
6364 }
Mark Shannon266b4622020-11-17 19:30:14 +00006365 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006366 if (prev_lineno == lineno) {
6367 continue;
6368 }
Mark Shannon266b4622020-11-17 19:30:14 +00006369 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006370 if (src < bb->b_iused - 1) {
6371 int next_lineno = bb->b_instr[src+1].i_lineno;
6372 if (next_lineno < 0 || next_lineno == lineno) {
6373 bb->b_instr[src+1].i_lineno = lineno;
6374 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006375 }
6376 }
Mark Shannon266b4622020-11-17 19:30:14 +00006377 else {
6378 basicblock* next = bb->b_next;
6379 while (next && next->b_iused == 0) {
6380 next = next->b_next;
6381 }
6382 /* or if last instruction in BB and next BB has same line number */
6383 if (next) {
6384 if (lineno == next->b_instr[0].i_lineno) {
6385 continue;
6386 }
6387 }
6388 }
6389
Mark Shannon6e8128f2020-07-30 10:03:00 +01006390 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006391 if (dest != src) {
6392 bb->b_instr[dest] = bb->b_instr[src];
6393 }
6394 dest++;
6395 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006396 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006397 assert(dest <= bb->b_iused);
6398 bb->b_iused = dest;
6399}
6400
Mark Shannon266b4622020-11-17 19:30:14 +00006401static int
6402normalize_basic_block(basicblock *bb) {
6403 /* Mark blocks as exit and/or nofallthrough.
6404 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006405 for (int i = 0; i < bb->b_iused; i++) {
6406 switch(bb->b_instr[i].i_opcode) {
6407 case RETURN_VALUE:
6408 case RAISE_VARARGS:
6409 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006410 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00006411 bb->b_nofallthrough = 1;
6412 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006413 case JUMP_ABSOLUTE:
6414 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006415 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006416 /* fall through */
6417 case POP_JUMP_IF_FALSE:
6418 case POP_JUMP_IF_TRUE:
6419 case JUMP_IF_FALSE_OR_POP:
6420 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00006421 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00006422 if (i != bb->b_iused-1) {
6423 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6424 return -1;
6425 }
Mark Shannon5977a792020-12-02 13:31:40 +00006426 /* Skip over empty basic blocks. */
6427 while (bb->b_instr[i].i_target->b_iused == 0) {
6428 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
6429 }
6430
Mark Shannoncc75ab72020-11-12 19:49:33 +00006431 }
6432 }
Mark Shannon266b4622020-11-17 19:30:14 +00006433 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006434}
6435
Mark Shannon6e8128f2020-07-30 10:03:00 +01006436static int
6437mark_reachable(struct assembler *a) {
6438 basicblock **stack, **sp;
6439 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6440 if (stack == NULL) {
6441 return -1;
6442 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006443 a->a_entry->b_predecessors = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006444 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006445 while (sp > stack) {
6446 basicblock *b = *(--sp);
Mark Shannon3bd60352021-01-13 12:05:43 +00006447 if (b->b_next && !b->b_nofallthrough) {
6448 if (b->b_next->b_predecessors == 0) {
6449 *sp++ = b->b_next;
6450 }
6451 b->b_next->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006452 }
6453 for (int i = 0; i < b->b_iused; i++) {
6454 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006455 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006456 target = b->b_instr[i].i_target;
Mark Shannon3bd60352021-01-13 12:05:43 +00006457 if (target->b_predecessors == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006458 *sp++ = target;
6459 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006460 target->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006461 }
6462 }
6463 }
6464 PyObject_Free(stack);
6465 return 0;
6466}
6467
Mark Shannon3bd60352021-01-13 12:05:43 +00006468static void
6469eliminate_empty_basic_blocks(basicblock *entry) {
6470 /* Eliminate empty blocks */
6471 for (basicblock *b = entry; b != NULL; b = b->b_next) {
6472 basicblock *next = b->b_next;
6473 if (next) {
6474 while (next->b_iused == 0 && next->b_next) {
6475 next = next->b_next;
6476 }
6477 b->b_next = next;
6478 }
6479 }
6480 for (basicblock *b = entry; b != NULL; b = b->b_next) {
6481 if (b->b_iused == 0) {
6482 continue;
6483 }
6484 if (is_jump(&b->b_instr[b->b_iused-1])) {
6485 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6486 while (target->b_iused == 0) {
6487 target = target->b_next;
6488 }
6489 b->b_instr[b->b_iused-1].i_target = target;
6490 }
6491 }
6492}
6493
6494
Mark Shannon5977a792020-12-02 13:31:40 +00006495/* If an instruction has no line number, but it's predecessor in the BB does,
Mark Shannon3bd60352021-01-13 12:05:43 +00006496 * then copy the line number. If a successor block has no line number, and only
6497 * one predecessor, then inherit the line number.
6498 * This ensures that all exit blocks (with one predecessor) receive a line number.
6499 * Also reduces the size of the line number table,
Mark Shannon5977a792020-12-02 13:31:40 +00006500 * but has no impact on the generated line number events.
6501 */
6502static void
Mark Shannon3bd60352021-01-13 12:05:43 +00006503propogate_line_numbers(struct assembler *a) {
Mark Shannon5977a792020-12-02 13:31:40 +00006504 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006505 if (b->b_iused == 0) {
6506 continue;
6507 }
Mark Shannon5977a792020-12-02 13:31:40 +00006508 int prev_lineno = -1;
6509 for (int i = 0; i < b->b_iused; i++) {
6510 if (b->b_instr[i].i_lineno < 0) {
6511 b->b_instr[i].i_lineno = prev_lineno;
6512 }
6513 else {
6514 prev_lineno = b->b_instr[i].i_lineno;
6515 }
6516 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006517 if (!b->b_nofallthrough && b->b_next->b_predecessors == 1) {
6518 assert(b->b_next->b_iused);
6519 if (b->b_next->b_instr[0].i_lineno < 0) {
6520 b->b_next->b_instr[0].i_lineno = prev_lineno;
6521 }
6522 }
6523 if (is_jump(&b->b_instr[b->b_iused-1])) {
6524 switch (b->b_instr[b->b_iused-1].i_opcode) {
6525 /* Note: Only actual jumps, not exception handlers */
6526 case SETUP_ASYNC_WITH:
6527 case SETUP_WITH:
6528 case SETUP_FINALLY:
6529 continue;
6530 }
6531 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6532 if (target->b_predecessors == 1) {
6533 if (target->b_instr[0].i_lineno < 0) {
6534 target->b_instr[0].i_lineno = prev_lineno;
6535 }
6536 }
6537 }
Mark Shannon5977a792020-12-02 13:31:40 +00006538 }
6539}
6540
6541/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01006542 The consts object should still be in list form to allow new constants
6543 to be appended.
6544
6545 All transformations keep the code size the same or smaller.
6546 For those that reduce size, the gaps are initially filled with
6547 NOPs. Later those NOPs are removed.
6548*/
6549
6550static int
6551optimize_cfg(struct assembler *a, PyObject *consts)
6552{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006553 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006554 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006555 return -1;
6556 }
Mark Shannon1659ad12021-01-13 15:05:04 +00006557 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00006558 assert(b->b_predecessors == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006559 }
6560 if (mark_reachable(a)) {
6561 return -1;
6562 }
6563 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006564 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006565 if (b->b_predecessors == 0) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006566 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05306567 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006568 }
6569 }
Mark Shannon1659ad12021-01-13 15:05:04 +00006570 basicblock *pred = NULL;
6571 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6572 int prev_lineno = -1;
6573 if (pred && pred->b_iused) {
6574 prev_lineno = pred->b_instr[pred->b_iused-1].i_lineno;
6575 }
6576 clean_basic_block(b, prev_lineno);
6577 pred = b->b_nofallthrough ? NULL : b;
6578 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006579 eliminate_empty_basic_blocks(a->a_entry);
Om Gc71581c2020-12-16 17:48:05 +05306580 /* Delete jump instructions made redundant by previous step. If a non-empty
6581 block ends with a jump instruction, check if the next non-empty block
6582 reached through normal flow control is the target of that jump. If it
6583 is, then the jump instruction is redundant and can be deleted.
6584 */
Mark Shannon3bd60352021-01-13 12:05:43 +00006585 int maybe_empty_blocks = 0;
Om Gc71581c2020-12-16 17:48:05 +05306586 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6587 if (b->b_iused > 0) {
6588 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
6589 if (b_last_instr->i_opcode == POP_JUMP_IF_FALSE ||
6590 b_last_instr->i_opcode == POP_JUMP_IF_TRUE ||
6591 b_last_instr->i_opcode == JUMP_ABSOLUTE ||
6592 b_last_instr->i_opcode == JUMP_FORWARD) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006593 if (b_last_instr->i_target == b->b_next) {
6594 assert(b->b_next->b_iused);
Om Gc71581c2020-12-16 17:48:05 +05306595 b->b_nofallthrough = 0;
6596 switch(b_last_instr->i_opcode) {
6597 case POP_JUMP_IF_FALSE:
6598 case POP_JUMP_IF_TRUE:
6599 b_last_instr->i_opcode = POP_TOP;
6600 b_last_instr->i_target = NULL;
6601 b_last_instr->i_oparg = 0;
6602 break;
6603 case JUMP_ABSOLUTE:
6604 case JUMP_FORWARD:
6605 b_last_instr->i_opcode = NOP;
Mark Shannon1659ad12021-01-13 15:05:04 +00006606 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00006607 maybe_empty_blocks = 1;
Om Gc71581c2020-12-16 17:48:05 +05306608 break;
6609 }
Om Gc71581c2020-12-16 17:48:05 +05306610 }
6611 }
6612 }
6613 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006614 if (maybe_empty_blocks) {
6615 eliminate_empty_basic_blocks(a->a_entry);
6616 }
6617 propogate_line_numbers(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006618 return 0;
6619}
6620
Mark Shannon5977a792020-12-02 13:31:40 +00006621static inline int
6622is_exit_without_lineno(basicblock *b) {
6623 return b->b_exit && b->b_instr[0].i_lineno < 0;
6624}
6625
6626/* PEP 626 mandates that the f_lineno of a frame is correct
6627 * after a frame terminates. It would be prohibitively expensive
6628 * to continuously update the f_lineno field at runtime,
6629 * so we make sure that all exiting instruction (raises and returns)
6630 * have a valid line number, allowing us to compute f_lineno lazily.
6631 * We can do this by duplicating the exit blocks without line number
6632 * so that none have more than one predecessor. We can then safely
6633 * copy the line number from the sole predecessor block.
6634 */
6635static int
6636ensure_exits_have_lineno(struct compiler *c)
6637{
Mark Shannoneaccc122020-12-04 15:22:12 +00006638 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006639 /* Copy all exit blocks without line number that are targets of a jump.
6640 */
6641 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6642 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
6643 switch (b->b_instr[b->b_iused-1].i_opcode) {
6644 /* Note: Only actual jumps, not exception handlers */
6645 case SETUP_ASYNC_WITH:
6646 case SETUP_WITH:
6647 case SETUP_FINALLY:
6648 continue;
6649 }
6650 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6651 if (is_exit_without_lineno(target)) {
6652 basicblock *new_target = compiler_copy_block(c, target);
6653 if (new_target == NULL) {
6654 return -1;
6655 }
6656 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6657 b->b_instr[b->b_iused-1].i_target = new_target;
6658 }
6659 }
Mark Shannoneaccc122020-12-04 15:22:12 +00006660 entry = b;
6661 }
6662 assert(entry != NULL);
6663 if (is_exit_without_lineno(entry)) {
6664 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00006665 }
Mark Shannonee9f98d2021-01-05 12:04:10 +00006666 /* Eliminate empty blocks */
6667 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6668 while (b->b_next && b->b_next->b_iused == 0) {
6669 b->b_next = b->b_next->b_next;
6670 }
6671 }
Mark Shannon5977a792020-12-02 13:31:40 +00006672 /* Any remaining reachable exit blocks without line number can only be reached by
6673 * fall through, and thus can only have a single predecessor */
6674 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6675 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
6676 if (is_exit_without_lineno(b->b_next)) {
6677 assert(b->b_next->b_iused > 0);
6678 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6679 }
6680 }
6681 }
6682 return 0;
6683}
6684
6685
Mark Shannon6e8128f2020-07-30 10:03:00 +01006686/* Retained for API compatibility.
6687 * Optimization is now done in optimize_cfg */
6688
6689PyObject *
6690PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6691 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6692{
6693 Py_INCREF(code);
6694 return code;
6695}