blob: d8fea9d047d0c03df162f91defbcf7d221230d02 [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 Stinnerc9bc2902020-10-27 02:24:34 +010025#include "pycore_long.h" // _PyLong_GetZero()
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Mark Shannon582aaf12020-08-04 17:30:11 +010031#define NEED_OPCODE_JUMP_TABLES
Guido van Rossum10dc2e81990-11-18 17:27:39 +000032#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030033#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035#define DEFAULT_BLOCK_SIZE 16
36#define DEFAULT_BLOCKS 8
37#define DEFAULT_CODE_SIZE 128
38#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000039
Nick Coghlan650f0d02007-04-15 12:05:43 +000040#define COMP_GENEXP 0
41#define COMP_LISTCOMP 1
42#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000043#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000044
Pablo Galindo90235812020-03-15 04:29:22 +000045#define IS_TOP_LEVEL_AWAIT(c) ( \
46 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
47 && (c->u->u_ste->ste_type == ModuleBlock))
48
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000049struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Mark Shannon582aaf12020-08-04 17:30:11 +010056#define LOG_BITS_PER_INT 5
57#define MASK_LOW_LOG_BITS 31
58
59static inline int
60is_bit_set_in_table(uint32_t *table, int bitindex) {
61 /* Is the relevant bit set in the relevant word? */
62 /* 256 bits fit into 8 32-bits words.
63 * Word is indexed by (bitindex>>ln(size of int in bits)).
64 * Bit within word is the low bits of bitindex.
65 */
66 uint32_t word = table[bitindex >> LOG_BITS_PER_INT];
67 return (word >> (bitindex & MASK_LOW_LOG_BITS)) & 1;
68}
69
70static inline int
71is_relative_jump(struct instr *i)
72{
73 return is_bit_set_in_table(_PyOpcode_RelativeJump, i->i_opcode);
74}
75
76static inline int
77is_jump(struct instr *i)
78{
79 return is_bit_set_in_table(_PyOpcode_Jump, i->i_opcode);
80}
81
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000083 /* Each basicblock in a compilation unit is linked via b_list in the
84 reverse order that the block are allocated. b_list points to the next
85 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 struct basicblock_ *b_list;
87 /* number of instructions used */
88 int b_iused;
89 /* length of instruction array (b_instr) */
90 int b_ialloc;
91 /* pointer to an array of instructions, initially NULL */
92 struct instr *b_instr;
93 /* If b_next is non-NULL, it is a pointer to the next
94 block reached by normal control flow. */
95 struct basicblock_ *b_next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 /* b_return is true if a RETURN_VALUE opcode is inserted. */
97 unsigned b_return : 1;
Mark Shannon3bd60352021-01-13 12:05:43 +000098 /* Number of predecssors that a block has. */
99 int b_predecessors;
Mark Shannoncc75ab72020-11-12 19:49:33 +0000100 /* Basic block has no fall through (it ends with a return, raise or jump) */
101 unsigned b_nofallthrough : 1;
102 /* Basic block exits scope (it ends with a return or raise) */
103 unsigned b_exit : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 /* depth of stack upon entry of block, computed by stackdepth() */
105 int b_startdepth;
106 /* instruction offset for block, computed by assemble_jump_offsets() */
107 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000108} basicblock;
109
110/* fblockinfo tracks the current frame block.
111
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000112A frame block is used to handle loops, try/except, and try/finally.
113It's called a frame block to distinguish it from a basic block in the
114compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000115*/
116
Mark Shannon02d126a2020-09-25 14:04:19 +0100117enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
118 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000119
120struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 enum fblocktype fb_type;
122 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200123 /* (optional) type-specific exit or cleanup block */
124 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +0000125 /* (optional) additional information required for unwinding */
126 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127};
128
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100129enum {
130 COMPILER_SCOPE_MODULE,
131 COMPILER_SCOPE_CLASS,
132 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400133 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400134 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100135 COMPILER_SCOPE_COMPREHENSION,
136};
137
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000138/* The following items change on entry and exit of code blocks.
139 They must be saved and restored when returning to a block.
140*/
141struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400145 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100146 int u_scope_type;
147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 /* The following fields are dicts that map objects to
149 the index of them in co_XXX. The index is used as
150 the argument for opcodes that refer to those collections.
151 */
152 PyObject *u_consts; /* all constants */
153 PyObject *u_names; /* all names */
154 PyObject *u_varnames; /* local variables */
155 PyObject *u_cellvars; /* cell variables */
156 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000159
Victor Stinnerf8e32212013-11-19 23:56:34 +0100160 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100161 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100162 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 /* Pointer to the most recently allocated block. By following b_list
164 members, you can reach all early allocated blocks. */
165 basicblock *u_blocks;
166 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 int u_nfblocks;
169 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 int u_firstlineno; /* the first lineno of the block */
172 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000173 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000174};
175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000177
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000178The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000180managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000181
182Note that we don't track recursion levels during compilation - the
183task of detecting and rejecting excessive levels of nesting is
184handled by the symbol analysis pass.
185
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000186*/
187
188struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200189 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 struct symtable *c_st;
191 PyFutureFeatures *c_future; /* pointer to module's __future__ */
192 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193
Georg Brandl8334fd92010-12-04 10:26:46 +0000194 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 int c_interactive; /* true if in interactive mode */
196 int c_nestlevel;
INADA Naokic2e16072018-11-26 21:23:22 +0900197 PyObject *c_const_cache; /* Python dict holding all constants,
198 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 struct compiler_unit *u; /* compiler state for current block */
200 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
201 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000202};
203
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100204static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000205static void compiler_free(struct compiler *);
206static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500207static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000208static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100209static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100210static int compiler_addop_j(struct compiler *, int, basicblock *);
Mark Shannon127dde52021-01-04 18:06:55 +0000211static int compiler_addop_j_noline(struct compiler *, int, basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200213static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000214static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
215
216static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
217static int compiler_visit_stmt(struct compiler *, stmt_ty);
218static int compiler_visit_keyword(struct compiler *, keyword_ty);
219static int compiler_visit_expr(struct compiler *, expr_ty);
220static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700221static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200222static int compiler_subscript(struct compiler *, expr_ty);
223static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224
Andy Lester76d58772020-03-10 21:18:12 -0500225static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100226static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Mark Shannon8473cf82020-12-15 11:07:50 +0000227
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500229static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400230static int compiler_async_with(struct compiler *, stmt_ty, int);
231static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100232static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100233 asdl_expr_seq *args,
234 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500235static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400236static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000237
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700238static int compiler_sync_comprehension_generator(
239 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100240 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200241 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700242 expr_ty elt, expr_ty val, int type);
243
244static int compiler_async_comprehension_generator(
245 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100246 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200247 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700248 expr_ty elt, expr_ty val, int type);
249
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000250static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000251static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000252
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400253#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000254
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000255PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000256_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 /* Name mangling: __private becomes _classname__private.
259 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200260 PyObject *result;
261 size_t nlen, plen, ipriv;
262 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 PyUnicode_READ_CHAR(ident, 0) != '_' ||
265 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 Py_INCREF(ident);
267 return ident;
268 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200269 nlen = PyUnicode_GET_LENGTH(ident);
270 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 The only time a name with a dot can occur is when
274 we are compiling an import statement that has a
275 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 TODO(jhylton): Decide whether we want to support
278 mangling of the module name, e.g. __M.X.
279 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200280 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
281 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
282 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 Py_INCREF(ident);
284 return ident; /* Don't mangle __whatever__ */
285 }
286 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200287 ipriv = 0;
288 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
289 ipriv++;
290 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 Py_INCREF(ident);
292 return ident; /* Don't mangle if class is just underscores */
293 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200294 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000295
Antoine Pitrou55bff892013-04-06 21:21:04 +0200296 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
297 PyErr_SetString(PyExc_OverflowError,
298 "private identifier too large to be mangled");
299 return NULL;
300 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200302 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
303 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
304 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
305
306 result = PyUnicode_New(1 + nlen + plen, maxchar);
307 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200309 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
310 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200311 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
312 Py_DECREF(result);
313 return NULL;
314 }
315 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
316 Py_DECREF(result);
317 return NULL;
318 }
Victor Stinner8f825062012-04-27 13:55:39 +0200319 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200320 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000321}
322
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000323static int
324compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000327
INADA Naokic2e16072018-11-26 21:23:22 +0900328 c->c_const_cache = PyDict_New();
329 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900331 }
332
333 c->c_stack = PyList_New(0);
334 if (!c->c_stack) {
335 Py_CLEAR(c->c_const_cache);
336 return 0;
337 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000340}
341
342PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200343PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
344 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 struct compiler c;
347 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200348 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (!__doc__) {
352 __doc__ = PyUnicode_InternFromString("__doc__");
353 if (!__doc__)
354 return NULL;
355 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000356 if (!__annotations__) {
357 __annotations__ = PyUnicode_InternFromString("__annotations__");
358 if (!__annotations__)
359 return NULL;
360 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 if (!compiler_init(&c))
362 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200363 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 c.c_filename = filename;
365 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200366 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (c.c_future == NULL)
368 goto finally;
369 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 flags = &local_flags;
371 }
372 merged = c.c_future->ff_features | flags->cf_flags;
373 c.c_future->ff_features = merged;
374 flags->cf_flags = merged;
375 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200376 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000378
Pablo Galindod112c602020-03-18 23:02:09 +0000379 _PyASTOptimizeState state;
380 state.optimize = c.c_optimize;
381 state.ff_features = merged;
382
383 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900384 goto finally;
385 }
386
Victor Stinner14e461d2013-08-26 22:28:21 +0200387 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (c.c_st == NULL) {
389 if (!PyErr_Occurred())
390 PyErr_SetString(PyExc_SystemError, "no symtable");
391 goto finally;
392 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000395
Thomas Wouters1175c432006-02-27 22:49:54 +0000396 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 compiler_free(&c);
398 assert(co || PyErr_Occurred());
399 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400}
401
402PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200403PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
404 int optimize, PyArena *arena)
405{
406 PyObject *filename;
407 PyCodeObject *co;
408 filename = PyUnicode_DecodeFSDefault(filename_str);
409 if (filename == NULL)
410 return NULL;
411 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
412 Py_DECREF(filename);
413 return co;
414
415}
416
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000417static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000418compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (c->c_st)
421 PySymtable_Free(c->c_st);
422 if (c->c_future)
423 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200424 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900425 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000427}
428
Guido van Rossum79f25d91997-04-29 20:08:16 +0000429static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000430list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 Py_ssize_t i, n;
433 PyObject *v, *k;
434 PyObject *dict = PyDict_New();
435 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 n = PyList_Size(list);
438 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100439 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (!v) {
441 Py_DECREF(dict);
442 return NULL;
443 }
444 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300445 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 Py_DECREF(v);
447 Py_DECREF(dict);
448 return NULL;
449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 Py_DECREF(v);
451 }
452 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000453}
454
455/* Return new dict containing names from src that match scope(s).
456
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000457src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000459values are integers, starting at offset and increasing by one for
460each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000461*/
462
463static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100464dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000465{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700466 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500468 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 assert(offset >= 0);
471 if (dest == NULL)
472 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000473
Meador Inge2ca63152012-07-18 14:20:11 -0500474 /* Sort the keys so that we have a deterministic order on the indexes
475 saved in the returned dictionary. These indexes are used as indexes
476 into the free and cell var storage. Therefore if they aren't
477 deterministic, then the generated bytecode is not deterministic.
478 */
479 sorted_keys = PyDict_Keys(src);
480 if (sorted_keys == NULL)
481 return NULL;
482 if (PyList_Sort(sorted_keys) != 0) {
483 Py_DECREF(sorted_keys);
484 return NULL;
485 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500486 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500487
488 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* XXX this should probably be a macro in symtable.h */
490 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500491 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200492 v = PyDict_GetItemWithError(src, k);
493 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 vi = PyLong_AS_LONG(v);
495 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300498 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500500 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 Py_DECREF(dest);
502 return NULL;
503 }
504 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300505 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500506 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 Py_DECREF(item);
508 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 return NULL;
510 }
511 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 }
513 }
Meador Inge2ca63152012-07-18 14:20:11 -0500514 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000516}
517
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518static void
519compiler_unit_check(struct compiler_unit *u)
520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 basicblock *block;
522 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700523 assert((uintptr_t)block != 0xcbcbcbcbU);
524 assert((uintptr_t)block != 0xfbfbfbfbU);
525 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (block->b_instr != NULL) {
527 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100528 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 assert(block->b_ialloc >= block->b_iused);
530 }
531 else {
532 assert (block->b_iused == 0);
533 assert (block->b_ialloc == 0);
534 }
535 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000536}
537
538static void
539compiler_unit_free(struct compiler_unit *u)
540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 compiler_unit_check(u);
544 b = u->u_blocks;
545 while (b != NULL) {
546 if (b->b_instr)
547 PyObject_Free((void *)b->b_instr);
548 next = b->b_list;
549 PyObject_Free((void *)b);
550 b = next;
551 }
552 Py_CLEAR(u->u_ste);
553 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400554 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 Py_CLEAR(u->u_consts);
556 Py_CLEAR(u->u_names);
557 Py_CLEAR(u->u_varnames);
558 Py_CLEAR(u->u_freevars);
559 Py_CLEAR(u->u_cellvars);
560 Py_CLEAR(u->u_private);
561 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562}
563
564static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100565compiler_enter_scope(struct compiler *c, identifier name,
566 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100569 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000570
Andy Lester7668a8b2020-03-24 23:26:44 -0500571 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 struct compiler_unit));
573 if (!u) {
574 PyErr_NoMemory();
575 return 0;
576 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100577 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100579 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 u->u_kwonlyargcount = 0;
581 u->u_ste = PySymtable_Lookup(c->c_st, key);
582 if (!u->u_ste) {
583 compiler_unit_free(u);
584 return 0;
585 }
586 Py_INCREF(name);
587 u->u_name = name;
588 u->u_varnames = list2dict(u->u_ste->ste_varnames);
589 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
590 if (!u->u_varnames || !u->u_cellvars) {
591 compiler_unit_free(u);
592 return 0;
593 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500594 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000595 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500596 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300597 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500598 int res;
599 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200600 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500601 name = _PyUnicode_FromId(&PyId___class__);
602 if (!name) {
603 compiler_unit_free(u);
604 return 0;
605 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100606 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500607 if (res < 0) {
608 compiler_unit_free(u);
609 return 0;
610 }
611 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200614 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (!u->u_freevars) {
616 compiler_unit_free(u);
617 return 0;
618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 u->u_blocks = NULL;
621 u->u_nfblocks = 0;
622 u->u_firstlineno = lineno;
623 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000624 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 u->u_consts = PyDict_New();
626 if (!u->u_consts) {
627 compiler_unit_free(u);
628 return 0;
629 }
630 u->u_names = PyDict_New();
631 if (!u->u_names) {
632 compiler_unit_free(u);
633 return 0;
634 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 /* Push the old compiler_unit on the stack. */
639 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400640 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
642 Py_XDECREF(capsule);
643 compiler_unit_free(u);
644 return 0;
645 }
646 Py_DECREF(capsule);
647 u->u_private = c->u->u_private;
648 Py_XINCREF(u->u_private);
649 }
650 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100653
654 block = compiler_new_block(c);
655 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100657 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000658
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400659 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
660 if (!compiler_set_qualname(c))
661 return 0;
662 }
663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000665}
666
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000667static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000668compiler_exit_scope(struct compiler *c)
669{
Victor Stinnera6192632021-01-29 16:53:03 +0100670 // Don't call PySequence_DelItem() with an exception raised
671 PyObject *exc_type, *exc_val, *exc_tb;
672 PyErr_Fetch(&exc_type, &exc_val, &exc_tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 c->c_nestlevel--;
675 compiler_unit_free(c->u);
676 /* Restore c->u to the parent unit. */
Victor Stinnera6192632021-01-29 16:53:03 +0100677 Py_ssize_t n = PyList_GET_SIZE(c->c_stack) - 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (n >= 0) {
Victor Stinnera6192632021-01-29 16:53:03 +0100679 PyObject *capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400680 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 assert(c->u);
682 /* we are deleting from a list so this really shouldn't fail */
Victor Stinnera6192632021-01-29 16:53:03 +0100683 if (PySequence_DelItem(c->c_stack, n) < 0) {
684 Py_FatalError("PySequence_DelItem failed");
685 }
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 Stinner87d3b9d2020-03-25 19:27:36 +01001901 _Py_FatalErrorFormat(__func__,
1902 "unknown scope for %.100s in %.100s(%s)\n"
1903 "symbols: %s\nlocals: %s\nglobals: %s",
1904 PyUnicode_AsUTF8(name),
1905 PyUnicode_AsUTF8(c->u->u_name),
1906 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1907 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1908 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1909 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913}
1914
1915static int
1916compiler_lookup_arg(PyObject *dict, PyObject *name)
1917{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001918 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001919 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001921 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001922 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923}
1924
1925static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001926compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001928 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001929 if (qualname == NULL)
1930 qualname = co->co_name;
1931
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001932 if (free) {
1933 for (i = 0; i < free; ++i) {
1934 /* Bypass com_addop_varname because it will generate
1935 LOAD_DEREF but LOAD_CLOSURE is needed.
1936 */
1937 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1938 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001940 /* Special case: If a class contains a method with a
1941 free variable that has the same name as a method,
1942 the name will be considered free *and* local in the
1943 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001944 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001945 */
1946 reftype = get_ref_type(c, name);
1947 if (reftype == CELL)
1948 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1949 else /* (reftype == FREE) */
1950 arg = compiler_lookup_arg(c->u->u_freevars, name);
1951 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001952 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001953 "lookup %s in %s %d %d\n"
1954 "freevars of %s: %s\n",
1955 PyUnicode_AsUTF8(PyObject_Repr(name)),
1956 PyUnicode_AsUTF8(c->u->u_name),
1957 reftype, arg,
1958 PyUnicode_AsUTF8(co->co_name),
1959 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001960 }
1961 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001963 flags |= 0x08;
1964 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001966 ADDOP_LOAD_CONST(c, (PyObject*)co);
1967 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001968 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970}
1971
1972static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001973compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (!decos)
1978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1981 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1982 }
1983 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984}
1985
1986static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001987compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1988 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001989{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001990 /* Push a dict of keyword-only default values.
1991
1992 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1993 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001994 int i;
1995 PyObject *keys = NULL;
1996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1998 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1999 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
2000 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04002001 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002002 if (!mangled) {
2003 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002005 if (keys == NULL) {
2006 keys = PyList_New(1);
2007 if (keys == NULL) {
2008 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002009 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002010 }
2011 PyList_SET_ITEM(keys, 0, mangled);
2012 }
2013 else {
2014 int res = PyList_Append(keys, mangled);
2015 Py_DECREF(mangled);
2016 if (res == -1) {
2017 goto error;
2018 }
2019 }
2020 if (!compiler_visit_expr(c, default_)) {
2021 goto error;
2022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 }
2024 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002025 if (keys != NULL) {
2026 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2027 PyObject *keys_tuple = PyList_AsTuple(keys);
2028 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002029 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002030 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002031 assert(default_count > 0);
2032 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002033 }
2034 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002035 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002036 }
2037
2038error:
2039 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002040 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002041}
2042
2043static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002044compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2045{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002046 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002047 return 1;
2048}
2049
2050static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002051compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002052 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002055 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002056 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002057 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002058
2059 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002060 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002061 VISIT(c, annexpr, annotation);
2062 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002064 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002065}
2066
2067static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002068compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002069 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002070{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002071 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 for (i = 0; i < asdl_seq_LEN(args); i++) {
2073 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002074 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 c,
2076 arg->arg,
2077 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002078 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002079 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002081 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002082}
2083
2084static int
2085compiler_visit_annotations(struct compiler *c, arguments_ty args,
2086 expr_ty returns)
2087{
Yurii Karabas73019792020-11-25 12:43:18 +02002088 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002089 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002090
Yurii Karabas73019792020-11-25 12:43:18 +02002091 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 */
2093 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002094 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002095
Yurii Karabas73019792020-11-25 12:43:18 +02002096 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2097 return 0;
2098 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2099 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002100 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002101 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002102 args->vararg->annotation, &annotations_len))
2103 return 0;
2104 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2105 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002106 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002107 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002108 args->kwarg->annotation, &annotations_len))
2109 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (!return_str) {
2112 return_str = PyUnicode_InternFromString("return");
2113 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002114 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 }
Yurii Karabas73019792020-11-25 12:43:18 +02002116 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2117 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 }
2119
Yurii Karabas73019792020-11-25 12:43:18 +02002120 if (annotations_len) {
2121 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002122 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002124
Yurii Karabas73019792020-11-25 12:43:18 +02002125 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002126}
2127
2128static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002129compiler_visit_defaults(struct compiler *c, arguments_ty args)
2130{
2131 VISIT_SEQ(c, expr, args->defaults);
2132 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2133 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134}
2135
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002136static Py_ssize_t
2137compiler_default_arguments(struct compiler *c, arguments_ty args)
2138{
2139 Py_ssize_t funcflags = 0;
2140 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002141 if (!compiler_visit_defaults(c, args))
2142 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002143 funcflags |= 0x01;
2144 }
2145 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002146 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002147 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002148 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002149 return -1;
2150 }
2151 else if (res > 0) {
2152 funcflags |= 0x02;
2153 }
2154 }
2155 return funcflags;
2156}
2157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002159forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2160{
2161
2162 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2163 compiler_error(c, "cannot assign to __debug__");
2164 return 1;
2165 }
2166 return 0;
2167}
2168
2169static int
2170compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2171{
2172 if (arg != NULL) {
2173 if (forbidden_name(c, arg->arg, Store))
2174 return 0;
2175 }
2176 return 1;
2177}
2178
2179static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002180compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002181{
2182 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002183 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002184 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2185 return 0;
2186 }
2187 }
2188 return 1;
2189}
2190
2191static int
2192compiler_check_debug_args(struct compiler *c, arguments_ty args)
2193{
2194 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2195 return 0;
2196 if (!compiler_check_debug_args_seq(c, args->args))
2197 return 0;
2198 if (!compiler_check_debug_one_arg(c, args->vararg))
2199 return 0;
2200 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2201 return 0;
2202 if (!compiler_check_debug_one_arg(c, args->kwarg))
2203 return 0;
2204 return 1;
2205}
2206
2207static int
Yury Selivanov75445082015-05-11 22:57:16 -04002208compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002211 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002212 arguments_ty args;
2213 expr_ty returns;
2214 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002215 asdl_expr_seq* decos;
2216 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002217 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002218 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002219 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002220 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221
Yury Selivanov75445082015-05-11 22:57:16 -04002222 if (is_async) {
2223 assert(s->kind == AsyncFunctionDef_kind);
2224
2225 args = s->v.AsyncFunctionDef.args;
2226 returns = s->v.AsyncFunctionDef.returns;
2227 decos = s->v.AsyncFunctionDef.decorator_list;
2228 name = s->v.AsyncFunctionDef.name;
2229 body = s->v.AsyncFunctionDef.body;
2230
2231 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2232 } else {
2233 assert(s->kind == FunctionDef_kind);
2234
2235 args = s->v.FunctionDef.args;
2236 returns = s->v.FunctionDef.returns;
2237 decos = s->v.FunctionDef.decorator_list;
2238 name = s->v.FunctionDef.name;
2239 body = s->v.FunctionDef.body;
2240
2241 scope_type = COMPILER_SCOPE_FUNCTION;
2242 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002244 if (!compiler_check_debug_args(c, args))
2245 return 0;
2246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (!compiler_decorators(c, decos))
2248 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002249
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002250 firstlineno = s->lineno;
2251 if (asdl_seq_LEN(decos)) {
2252 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2253 }
2254
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002255 funcflags = compiler_default_arguments(c, args);
2256 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002258 }
2259
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002260 annotations = compiler_visit_annotations(c, args, returns);
2261 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002262 return 0;
2263 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002264 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002265 funcflags |= 0x04;
2266 }
2267
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002268 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002269 return 0;
2270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271
INADA Naokicb41b272017-02-23 00:31:59 +09002272 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002273 if (c->c_optimize < 2) {
2274 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002275 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002276 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 compiler_exit_scope(c);
2278 return 0;
2279 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002282 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002284 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002285 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002288 qualname = c->u->u_qualname;
2289 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002291 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002292 Py_XDECREF(qualname);
2293 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002295 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002297 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002298 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* decorators */
2302 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2303 ADDOP_I(c, CALL_FUNCTION, 1);
2304 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305
Yury Selivanov75445082015-05-11 22:57:16 -04002306 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307}
2308
2309static int
2310compiler_class(struct compiler *c, stmt_ty s)
2311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 PyCodeObject *co;
2313 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002314 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002315 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 if (!compiler_decorators(c, decos))
2318 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002319
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002320 firstlineno = s->lineno;
2321 if (asdl_seq_LEN(decos)) {
2322 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2323 }
2324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* ultimately generate code for:
2326 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2327 where:
2328 <func> is a function/closure created from the class body;
2329 it has a single argument (__locals__) where the dict
2330 (or MutableSequence) representing the locals is passed
2331 <name> is the class name
2332 <bases> is the positional arguments and *varargs argument
2333 <keywords> is the keyword arguments and **kwds argument
2334 This borrows from compiler_call.
2335 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002338 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002339 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 return 0;
2341 /* this block represents what we do in the new scope */
2342 {
2343 /* use the class name for name mangling */
2344 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002345 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* load (global) __name__ ... */
2347 str = PyUnicode_InternFromString("__name__");
2348 if (!str || !compiler_nameop(c, str, Load)) {
2349 Py_XDECREF(str);
2350 compiler_exit_scope(c);
2351 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002352 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 Py_DECREF(str);
2354 /* ... and store it as __module__ */
2355 str = PyUnicode_InternFromString("__module__");
2356 if (!str || !compiler_nameop(c, str, Store)) {
2357 Py_XDECREF(str);
2358 compiler_exit_scope(c);
2359 return 0;
2360 }
2361 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002362 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002363 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002364 str = PyUnicode_InternFromString("__qualname__");
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);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002372 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 compiler_exit_scope(c);
2374 return 0;
2375 }
Mark Shannone56d54e2021-01-15 13:52:00 +00002376 /* The following code is artificial */
2377 c->u->u_lineno = -1;
Nick Coghlan19d24672016-12-05 16:47:55 +10002378 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002379 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002380 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002381 str = PyUnicode_InternFromString("__class__");
2382 if (str == NULL) {
2383 compiler_exit_scope(c);
2384 return 0;
2385 }
2386 i = compiler_lookup_arg(c->u->u_cellvars, str);
2387 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002388 if (i < 0) {
2389 compiler_exit_scope(c);
2390 return 0;
2391 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002392 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002395 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002396 str = PyUnicode_InternFromString("__classcell__");
2397 if (!str || !compiler_nameop(c, str, Store)) {
2398 Py_XDECREF(str);
2399 compiler_exit_scope(c);
2400 return 0;
2401 }
2402 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002404 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002405 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002406 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002407 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002408 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002409 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* create the code object */
2411 co = assemble(c, 1);
2412 }
2413 /* leave the new scope */
2414 compiler_exit_scope(c);
2415 if (co == NULL)
2416 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 /* 2. load the 'build_class' function */
2419 ADDOP(c, LOAD_BUILD_CLASS);
2420
2421 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002422 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 Py_DECREF(co);
2424
2425 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002426 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427
2428 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002429 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 return 0;
2431
2432 /* 6. apply decorators */
2433 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2434 ADDOP_I(c, CALL_FUNCTION, 1);
2435 }
2436
2437 /* 7. store into <name> */
2438 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2439 return 0;
2440 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002441}
2442
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002443/* Return 0 if the expression is a constant value except named singletons.
2444 Return 1 otherwise. */
2445static int
2446check_is_arg(expr_ty e)
2447{
2448 if (e->kind != Constant_kind) {
2449 return 1;
2450 }
2451 PyObject *value = e->v.Constant.value;
2452 return (value == Py_None
2453 || value == Py_False
2454 || value == Py_True
2455 || value == Py_Ellipsis);
2456}
2457
2458/* Check operands of identity chacks ("is" and "is not").
2459 Emit a warning if any operand is a constant except named singletons.
2460 Return 0 on error.
2461 */
2462static int
2463check_compare(struct compiler *c, expr_ty e)
2464{
2465 Py_ssize_t i, n;
2466 int left = check_is_arg(e->v.Compare.left);
2467 n = asdl_seq_LEN(e->v.Compare.ops);
2468 for (i = 0; i < n; i++) {
2469 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2470 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2471 if (op == Is || op == IsNot) {
2472 if (!right || !left) {
2473 const char *msg = (op == Is)
2474 ? "\"is\" with a literal. Did you mean \"==\"?"
2475 : "\"is not\" with a literal. Did you mean \"!=\"?";
2476 return compiler_warn(c, msg);
2477 }
2478 }
2479 left = right;
2480 }
2481 return 1;
2482}
2483
Mark Shannon9af0e472020-01-14 10:12:45 +00002484static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485{
Mark Shannon9af0e472020-01-14 10:12:45 +00002486 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002487 switch (op) {
2488 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002489 cmp = Py_EQ;
2490 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002491 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002492 cmp = Py_NE;
2493 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002494 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002495 cmp = Py_LT;
2496 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002497 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002498 cmp = Py_LE;
2499 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002500 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002501 cmp = Py_GT;
2502 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002503 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002504 cmp = Py_GE;
2505 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002506 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002507 ADDOP_I(c, IS_OP, 0);
2508 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002509 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002510 ADDOP_I(c, IS_OP, 1);
2511 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002512 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002513 ADDOP_I(c, CONTAINS_OP, 0);
2514 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002515 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002516 ADDOP_I(c, CONTAINS_OP, 1);
2517 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002518 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002519 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002520 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002521 ADDOP_I(c, COMPARE_OP, cmp);
2522 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002523}
2524
Mark Shannon9af0e472020-01-14 10:12:45 +00002525
2526
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002527static int
2528compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2529{
2530 switch (e->kind) {
2531 case UnaryOp_kind:
2532 if (e->v.UnaryOp.op == Not)
2533 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2534 /* fallback to general implementation */
2535 break;
2536 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002537 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002538 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2539 assert(n >= 0);
2540 int cond2 = e->v.BoolOp.op == Or;
2541 basicblock *next2 = next;
2542 if (!cond2 != !cond) {
2543 next2 = compiler_new_block(c);
2544 if (next2 == NULL)
2545 return 0;
2546 }
2547 for (i = 0; i < n; ++i) {
2548 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2549 return 0;
2550 }
2551 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2552 return 0;
2553 if (next2 != next)
2554 compiler_use_next_block(c, next2);
2555 return 1;
2556 }
2557 case IfExp_kind: {
2558 basicblock *end, *next2;
2559 end = compiler_new_block(c);
2560 if (end == NULL)
2561 return 0;
2562 next2 = compiler_new_block(c);
2563 if (next2 == NULL)
2564 return 0;
2565 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2566 return 0;
2567 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2568 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002569 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002570 compiler_use_next_block(c, next2);
2571 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2572 return 0;
2573 compiler_use_next_block(c, end);
2574 return 1;
2575 }
2576 case Compare_kind: {
2577 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2578 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002579 if (!check_compare(c, e)) {
2580 return 0;
2581 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002582 basicblock *cleanup = compiler_new_block(c);
2583 if (cleanup == NULL)
2584 return 0;
2585 VISIT(c, expr, e->v.Compare.left);
2586 for (i = 0; i < n; i++) {
2587 VISIT(c, expr,
2588 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2589 ADDOP(c, DUP_TOP);
2590 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002591 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002592 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002593 NEXT_BLOCK(c);
2594 }
2595 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002596 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002597 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002598 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002599 basicblock *end = compiler_new_block(c);
2600 if (end == NULL)
2601 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002602 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002603 compiler_use_next_block(c, cleanup);
2604 ADDOP(c, POP_TOP);
2605 if (!cond) {
Mark Shannon127dde52021-01-04 18:06:55 +00002606 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002607 }
2608 compiler_use_next_block(c, end);
2609 return 1;
2610 }
2611 /* fallback to general implementation */
2612 break;
2613 }
2614 default:
2615 /* fallback to general implementation */
2616 break;
2617 }
2618
2619 /* general implementation */
2620 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002621 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002622 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002623 return 1;
2624}
2625
2626static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002627compiler_ifexp(struct compiler *c, expr_ty e)
2628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 basicblock *end, *next;
2630
2631 assert(e->kind == IfExp_kind);
2632 end = compiler_new_block(c);
2633 if (end == NULL)
2634 return 0;
2635 next = compiler_new_block(c);
2636 if (next == NULL)
2637 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002638 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2639 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon127dde52021-01-04 18:06:55 +00002641 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 compiler_use_next_block(c, next);
2643 VISIT(c, expr, e->v.IfExp.orelse);
2644 compiler_use_next_block(c, end);
2645 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002646}
2647
2648static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649compiler_lambda(struct compiler *c, expr_ty e)
2650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002652 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002654 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 arguments_ty args = e->v.Lambda.args;
2656 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002657
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002658 if (!compiler_check_debug_args(c, args))
2659 return 0;
2660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 if (!name) {
2662 name = PyUnicode_InternFromString("<lambda>");
2663 if (!name)
2664 return 0;
2665 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002666
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002667 funcflags = compiler_default_arguments(c, args);
2668 if (funcflags == -1) {
2669 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002671
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002672 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002673 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 /* Make None the first constant, so the lambda can't have a
2677 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002678 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002682 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2684 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2685 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002686 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 }
2688 else {
2689 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002690 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002692 qualname = c->u->u_qualname;
2693 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002695 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002698 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002699 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 Py_DECREF(co);
2701
2702 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002703}
2704
2705static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002706compiler_if(struct compiler *c, stmt_ty s)
2707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 assert(s->kind == If_kind);
2710 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002711 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002713 }
2714 if (asdl_seq_LEN(s->v.If.orelse)) {
2715 next = compiler_new_block(c);
2716 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002717 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002718 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002719 }
2720 else {
2721 next = end;
2722 }
2723 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2724 return 0;
2725 }
2726 VISIT_SEQ(c, stmt, s->v.If.body);
2727 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon127dde52021-01-04 18:06:55 +00002728 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Mark Shannon8473cf82020-12-15 11:07:50 +00002729 compiler_use_next_block(c, next);
2730 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 }
2732 compiler_use_next_block(c, end);
2733 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734}
2735
2736static int
2737compiler_for(struct compiler *c, stmt_ty s)
2738{
Mark Shannon5977a792020-12-02 13:31:40 +00002739 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002742 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 cleanup = compiler_new_block(c);
2744 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002745 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002747 }
2748 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002750 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 VISIT(c, expr, s->v.For.iter);
2752 ADDOP(c, GET_ITER);
2753 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002754 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002755 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 VISIT(c, expr, s->v.For.target);
2757 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002758 /* Mark jump as artificial */
2759 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002760 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002762
2763 compiler_pop_fblock(c, FOR_LOOP, start);
2764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 VISIT_SEQ(c, stmt, s->v.For.orelse);
2766 compiler_use_next_block(c, end);
2767 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002768}
2769
Yury Selivanov75445082015-05-11 22:57:16 -04002770
2771static int
2772compiler_async_for(struct compiler *c, stmt_ty s)
2773{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002774 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002775 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002776 c->u->u_ste->ste_coroutine = 1;
2777 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002778 return compiler_error(c, "'async for' outside async function");
2779 }
2780
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002781 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002782 except = compiler_new_block(c);
2783 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002784
Mark Shannonfee55262019-11-21 09:11:43 +00002785 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002786 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002787 }
Yury Selivanov75445082015-05-11 22:57:16 -04002788 VISIT(c, expr, s->v.AsyncFor.iter);
2789 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002790
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002791 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002792 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002793 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002794 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002795 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002796 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002797 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002798 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002799 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002800 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002801
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002802 /* Success block for __anext__ */
2803 VISIT(c, expr, s->v.AsyncFor.target);
2804 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002805 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002806
2807 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002808
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002809 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002810 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002811
2812 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002813 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002814
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002815 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002816 VISIT_SEQ(c, stmt, s->v.For.orelse);
2817
2818 compiler_use_next_block(c, end);
2819
2820 return 1;
2821}
2822
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002823static int
2824compiler_while(struct compiler *c, stmt_ty s)
2825{
Mark Shannon266b4622020-11-17 19:30:14 +00002826 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002828 body = compiler_new_block(c);
2829 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002831 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002835 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002838 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2839 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002840 }
2841
2842 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002844 SET_LOC(c, s);
2845 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2846 return 0;
2847 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002849 compiler_pop_fblock(c, WHILE_LOOP, loop);
2850
Mark Shannon266b4622020-11-17 19:30:14 +00002851 compiler_use_next_block(c, anchor);
2852 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858}
2859
2860static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002861compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002863 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002864 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002865 if (c->u->u_ste->ste_type != FunctionBlock)
2866 return compiler_error(c, "'return' outside function");
2867 if (s->v.Return.value != NULL &&
2868 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2869 {
2870 return compiler_error(
2871 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002873 if (preserve_tos) {
2874 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002875 } else {
2876 /* Emit instruction with line number for expression */
2877 if (s->v.Return.value != NULL) {
2878 SET_LOC(c, s->v.Return.value);
2879 ADDOP(c, NOP);
2880 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002881 }
Mark Shannonfee55262019-11-21 09:11:43 +00002882 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2883 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002884 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002885 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002886 }
2887 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00002888 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002889 }
2890 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002891 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002894}
2895
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002896static int
2897compiler_break(struct compiler *c)
2898{
Mark Shannonfee55262019-11-21 09:11:43 +00002899 struct fblockinfo *loop = NULL;
2900 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2901 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002902 }
Mark Shannonfee55262019-11-21 09:11:43 +00002903 if (loop == NULL) {
2904 return compiler_error(c, "'break' outside loop");
2905 }
2906 if (!compiler_unwind_fblock(c, loop, 0)) {
2907 return 0;
2908 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002909 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002910 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002911 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002912}
2913
2914static int
2915compiler_continue(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, "'continue' not properly in loop");
2923 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002924 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002925 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002926 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002927}
2928
2929
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002930/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931
2932 SETUP_FINALLY L
2933 <code for body>
2934 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002935 <code for finalbody>
2936 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002937 L:
2938 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002939 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002941 The special instructions use the block stack. Each block
2942 stack entry contains the instruction that created it (here
2943 SETUP_FINALLY), the level of the value stack at the time the
2944 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947 Pushes the current value stack level and the label
2948 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002949 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002950 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002952 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002953 when a SETUP_FINALLY entry is found, the raised and the caught
2954 exceptions are pushed onto the value stack (and the exception
2955 condition is cleared), and the interpreter jumps to the label
2956 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002957*/
2958
2959static int
2960compiler_try_finally(struct compiler *c, stmt_ty s)
2961{
Mark Shannonfee55262019-11-21 09:11:43 +00002962 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 body = compiler_new_block(c);
2965 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002966 exit = compiler_new_block(c);
2967 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002970 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002971 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002973 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002975 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2976 if (!compiler_try_except(c, s))
2977 return 0;
2978 }
2979 else {
2980 VISIT_SEQ(c, stmt, s->v.Try.body);
2981 }
Mark Shannon3bd60352021-01-13 12:05:43 +00002982 ADDOP_NOLINE(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002983 compiler_pop_fblock(c, FINALLY_TRY, body);
2984 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon127dde52021-01-04 18:06:55 +00002985 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00002986 /* `finally` block */
2987 compiler_use_next_block(c, end);
2988 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2989 return 0;
2990 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2991 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00002992 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00002993 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995}
2996
2997/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002998 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999 (The contents of the value stack is shown in [], with the top
3000 at the right; 'tb' is trace-back info, 'val' the exception's
3001 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002
3003 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003004 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003005 [] <code for S>
3006 [] POP_BLOCK
3007 [] JUMP_FORWARD L0
3008
3009 [tb, val, exc] L1: DUP )
3010 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003011 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003012 [tb, val, exc] POP
3013 [tb, val] <assign to V1> (or POP if no V1)
3014 [tb] POP
3015 [] <code for S1>
3016 JUMP_FORWARD L0
3017
3018 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 .............................etc.......................
3020
Mark Shannonfee55262019-11-21 09:11:43 +00003021 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022
3023 [] L0: <next statement>
3024
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003025 Of course, parts are not generated if Vi or Ei is not present.
3026*/
3027static int
3028compiler_try_except(struct compiler *c, stmt_ty s)
3029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003031 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 body = compiler_new_block(c);
3034 except = compiler_new_block(c);
3035 orelse = compiler_new_block(c);
3036 end = compiler_new_block(c);
3037 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3038 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003039 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003041 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003043 VISIT_SEQ(c, stmt, s->v.Try.body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003044 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon3bd60352021-01-13 12:05:43 +00003045 ADDOP_NOLINE(c, POP_BLOCK);
3046 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003047 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003049 /* Runtime will push a block here, so we need to account for that */
3050 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3051 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 for (i = 0; i < n; i++) {
3053 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003054 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 if (!handler->v.ExceptHandler.type && i < n-1)
3056 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003057 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 except = compiler_new_block(c);
3059 if (except == NULL)
3060 return 0;
3061 if (handler->v.ExceptHandler.type) {
3062 ADDOP(c, DUP_TOP);
3063 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003064 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003065 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003066 }
3067 ADDOP(c, POP_TOP);
3068 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003069 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003070
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003071 cleanup_end = compiler_new_block(c);
3072 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003073 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003074 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003075 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003076
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003077 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3078 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003080 /*
3081 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003082 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003083 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003084 try:
3085 # body
3086 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003087 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003088 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003091 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003092 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003093 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003094 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003095 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003097 /* second # body */
3098 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003099 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003100 ADDOP(c, POP_BLOCK);
3101 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003102 /* name = None; del name; # Mark as artificial */
3103 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003104 ADDOP_LOAD_CONST(c, Py_None);
3105 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3106 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003107 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108
Mark Shannonfee55262019-11-21 09:11:43 +00003109 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003110 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111
Mark Shannon877df852020-11-12 09:43:29 +00003112 /* name = None; del name; # Mark as artificial */
3113 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003114 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003116 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117
Mark Shannonbf353f32020-12-17 13:55:28 +00003118 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 }
3120 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003121 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003123 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003124 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003125 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126
Guido van Rossumb940e112007-01-10 16:19:56 +00003127 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003128 ADDOP(c, POP_TOP);
3129 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003130 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003131 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003133 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannon127dde52021-01-04 18:06:55 +00003134 /* name = None; del name; # Mark as artificial */
3135 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003136 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003137 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 compiler_use_next_block(c, except);
3140 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003141 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003142 /* Mark as artificial */
3143 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003144 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003146 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 compiler_use_next_block(c, end);
3148 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149}
3150
3151static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003152compiler_try(struct compiler *c, stmt_ty s) {
3153 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3154 return compiler_try_finally(c, s);
3155 else
3156 return compiler_try_except(c, s);
3157}
3158
3159
3160static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161compiler_import_as(struct compiler *c, identifier name, identifier asname)
3162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 /* The IMPORT_NAME opcode was already generated. This function
3164 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003167 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003169 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3170 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003171 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003172 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003173 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003175 while (1) {
3176 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003178 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003179 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003180 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003181 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003183 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003184 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003185 if (dot == -1) {
3186 break;
3187 }
3188 ADDOP(c, ROT_TWO);
3189 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003191 if (!compiler_nameop(c, asname, Store)) {
3192 return 0;
3193 }
3194 ADDOP(c, POP_TOP);
3195 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 }
3197 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198}
3199
3200static int
3201compiler_import(struct compiler *c, stmt_ty s)
3202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 /* The Import node stores a module name like a.b.c as a single
3204 string. This is convenient for all cases except
3205 import a.b.c as d
3206 where we need to parse that string to extract the individual
3207 module names.
3208 XXX Perhaps change the representation to make this case simpler?
3209 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003210 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003211
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003212 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 for (i = 0; i < n; i++) {
3214 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3215 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003217 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003218 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 if (alias->asname) {
3222 r = compiler_import_as(c, alias->name, alias->asname);
3223 if (!r)
3224 return r;
3225 }
3226 else {
3227 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003228 Py_ssize_t dot = PyUnicode_FindChar(
3229 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003230 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003231 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003232 if (tmp == NULL)
3233 return 0;
3234 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003236 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 Py_DECREF(tmp);
3238 }
3239 if (!r)
3240 return r;
3241 }
3242 }
3243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244}
3245
3246static int
3247compiler_from_import(struct compiler *c, stmt_ty s)
3248{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003249 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003250 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 if (!empty_string) {
3254 empty_string = PyUnicode_FromString("");
3255 if (!empty_string)
3256 return 0;
3257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003259 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003260
3261 names = PyTuple_New(n);
3262 if (!names)
3263 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 /* build up the names */
3266 for (i = 0; i < n; i++) {
3267 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3268 Py_INCREF(alias->name);
3269 PyTuple_SET_ITEM(names, i, alias->name);
3270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003273 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 Py_DECREF(names);
3275 return compiler_error(c, "from __future__ imports must occur "
3276 "at the beginning of the file");
3277 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003278 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 if (s->v.ImportFrom.module) {
3281 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3282 }
3283 else {
3284 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3285 }
3286 for (i = 0; i < n; i++) {
3287 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3288 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003290 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 assert(n == 1);
3292 ADDOP(c, IMPORT_STAR);
3293 return 1;
3294 }
3295
3296 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3297 store_name = alias->name;
3298 if (alias->asname)
3299 store_name = alias->asname;
3300
3301 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 return 0;
3303 }
3304 }
3305 /* remove imported module */
3306 ADDOP(c, POP_TOP);
3307 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308}
3309
3310static int
3311compiler_assert(struct compiler *c, stmt_ty s)
3312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314
Georg Brandl8334fd92010-12-04 10:26:46 +00003315 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003318 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3319 {
3320 if (!compiler_warn(c, "assertion is always true, "
3321 "perhaps remove parentheses?"))
3322 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003323 return 0;
3324 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 end = compiler_new_block(c);
3327 if (end == NULL)
3328 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003329 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3330 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003331 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 if (s->v.Assert.msg) {
3333 VISIT(c, expr, s->v.Assert.msg);
3334 ADDOP_I(c, CALL_FUNCTION, 1);
3335 }
3336 ADDOP_I(c, RAISE_VARARGS, 1);
3337 compiler_use_next_block(c, end);
3338 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339}
3340
3341static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003342compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3343{
3344 if (c->c_interactive && c->c_nestlevel <= 1) {
3345 VISIT(c, expr, value);
3346 ADDOP(c, PRINT_EXPR);
3347 return 1;
3348 }
3349
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003350 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003351 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003352 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003353 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003354 }
3355
3356 VISIT(c, expr, value);
3357 ADDOP(c, POP_TOP);
3358 return 1;
3359}
3360
3361static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003362compiler_visit_stmt(struct compiler *c, stmt_ty s)
3363{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003364 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003367 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 switch (s->kind) {
3370 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003371 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 case ClassDef_kind:
3373 return compiler_class(c, s);
3374 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003375 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 case Delete_kind:
3377 VISIT_SEQ(c, expr, s->v.Delete.targets)
3378 break;
3379 case Assign_kind:
3380 n = asdl_seq_LEN(s->v.Assign.targets);
3381 VISIT(c, expr, s->v.Assign.value);
3382 for (i = 0; i < n; i++) {
3383 if (i < n - 1)
3384 ADDOP(c, DUP_TOP);
3385 VISIT(c, expr,
3386 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3387 }
3388 break;
3389 case AugAssign_kind:
3390 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003391 case AnnAssign_kind:
3392 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 case For_kind:
3394 return compiler_for(c, s);
3395 case While_kind:
3396 return compiler_while(c, s);
3397 case If_kind:
3398 return compiler_if(c, s);
3399 case Raise_kind:
3400 n = 0;
3401 if (s->v.Raise.exc) {
3402 VISIT(c, expr, s->v.Raise.exc);
3403 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003404 if (s->v.Raise.cause) {
3405 VISIT(c, expr, s->v.Raise.cause);
3406 n++;
3407 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003409 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003410 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003412 case Try_kind:
3413 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 case Assert_kind:
3415 return compiler_assert(c, s);
3416 case Import_kind:
3417 return compiler_import(c, s);
3418 case ImportFrom_kind:
3419 return compiler_from_import(c, s);
3420 case Global_kind:
3421 case Nonlocal_kind:
3422 break;
3423 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003424 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003426 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 break;
3428 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003429 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 case Continue_kind:
3431 return compiler_continue(c);
3432 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003433 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003434 case AsyncFunctionDef_kind:
3435 return compiler_function(c, s, 1);
3436 case AsyncWith_kind:
3437 return compiler_async_with(c, s, 0);
3438 case AsyncFor_kind:
3439 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 }
Yury Selivanov75445082015-05-11 22:57:16 -04003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443}
3444
3445static int
3446unaryop(unaryop_ty op)
3447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 switch (op) {
3449 case Invert:
3450 return UNARY_INVERT;
3451 case Not:
3452 return UNARY_NOT;
3453 case UAdd:
3454 return UNARY_POSITIVE;
3455 case USub:
3456 return UNARY_NEGATIVE;
3457 default:
3458 PyErr_Format(PyExc_SystemError,
3459 "unary op %d should not be possible", op);
3460 return 0;
3461 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462}
3463
3464static int
Andy Lester76d58772020-03-10 21:18:12 -05003465binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 switch (op) {
3468 case Add:
3469 return BINARY_ADD;
3470 case Sub:
3471 return BINARY_SUBTRACT;
3472 case Mult:
3473 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003474 case MatMult:
3475 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 case Div:
3477 return BINARY_TRUE_DIVIDE;
3478 case Mod:
3479 return BINARY_MODULO;
3480 case Pow:
3481 return BINARY_POWER;
3482 case LShift:
3483 return BINARY_LSHIFT;
3484 case RShift:
3485 return BINARY_RSHIFT;
3486 case BitOr:
3487 return BINARY_OR;
3488 case BitXor:
3489 return BINARY_XOR;
3490 case BitAnd:
3491 return BINARY_AND;
3492 case FloorDiv:
3493 return BINARY_FLOOR_DIVIDE;
3494 default:
3495 PyErr_Format(PyExc_SystemError,
3496 "binary op %d should not be possible", op);
3497 return 0;
3498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499}
3500
3501static int
Andy Lester76d58772020-03-10 21:18:12 -05003502inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 switch (op) {
3505 case Add:
3506 return INPLACE_ADD;
3507 case Sub:
3508 return INPLACE_SUBTRACT;
3509 case Mult:
3510 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003511 case MatMult:
3512 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 case Div:
3514 return INPLACE_TRUE_DIVIDE;
3515 case Mod:
3516 return INPLACE_MODULO;
3517 case Pow:
3518 return INPLACE_POWER;
3519 case LShift:
3520 return INPLACE_LSHIFT;
3521 case RShift:
3522 return INPLACE_RSHIFT;
3523 case BitOr:
3524 return INPLACE_OR;
3525 case BitXor:
3526 return INPLACE_XOR;
3527 case BitAnd:
3528 return INPLACE_AND;
3529 case FloorDiv:
3530 return INPLACE_FLOOR_DIVIDE;
3531 default:
3532 PyErr_Format(PyExc_SystemError,
3533 "inplace binary op %d should not be possible", op);
3534 return 0;
3535 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536}
3537
3538static int
3539compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3540{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003541 int op, scope;
3542 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 PyObject *dict = c->u->u_names;
3546 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003548 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3549 !_PyUnicode_EqualToASCIIString(name, "True") &&
3550 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003551
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003552 if (forbidden_name(c, name, ctx))
3553 return 0;
3554
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003555 mangled = _Py_Mangle(c->u->u_private, name);
3556 if (!mangled)
3557 return 0;
3558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 op = 0;
3560 optype = OP_NAME;
3561 scope = PyST_GetScope(c->u->u_ste, mangled);
3562 switch (scope) {
3563 case FREE:
3564 dict = c->u->u_freevars;
3565 optype = OP_DEREF;
3566 break;
3567 case CELL:
3568 dict = c->u->u_cellvars;
3569 optype = OP_DEREF;
3570 break;
3571 case LOCAL:
3572 if (c->u->u_ste->ste_type == FunctionBlock)
3573 optype = OP_FAST;
3574 break;
3575 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003576 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 optype = OP_GLOBAL;
3578 break;
3579 case GLOBAL_EXPLICIT:
3580 optype = OP_GLOBAL;
3581 break;
3582 default:
3583 /* scope can be 0 */
3584 break;
3585 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003588 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 switch (optype) {
3591 case OP_DEREF:
3592 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003593 case Load:
3594 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3595 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003596 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003597 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 }
3599 break;
3600 case OP_FAST:
3601 switch (ctx) {
3602 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003603 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003606 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 return 1;
3608 case OP_GLOBAL:
3609 switch (ctx) {
3610 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003611 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 }
3614 break;
3615 case OP_NAME:
3616 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003617 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003618 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 }
3621 break;
3622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003625 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 Py_DECREF(mangled);
3627 if (arg < 0)
3628 return 0;
3629 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630}
3631
3632static int
3633compiler_boolop(struct compiler *c, expr_ty e)
3634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003636 int jumpi;
3637 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003638 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 assert(e->kind == BoolOp_kind);
3641 if (e->v.BoolOp.op == And)
3642 jumpi = JUMP_IF_FALSE_OR_POP;
3643 else
3644 jumpi = JUMP_IF_TRUE_OR_POP;
3645 end = compiler_new_block(c);
3646 if (end == NULL)
3647 return 0;
3648 s = e->v.BoolOp.values;
3649 n = asdl_seq_LEN(s) - 1;
3650 assert(n >= 0);
3651 for (i = 0; i < n; ++i) {
3652 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003653 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003654 basicblock *next = compiler_new_block(c);
3655 if (next == NULL) {
3656 return 0;
3657 }
3658 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 }
3660 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3661 compiler_use_next_block(c, end);
3662 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663}
3664
3665static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003666starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003667 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003668{
3669 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003670 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003671 if (n > 2 && are_all_items_const(elts, 0, n)) {
3672 PyObject *folded = PyTuple_New(n);
3673 if (folded == NULL) {
3674 return 0;
3675 }
3676 PyObject *val;
3677 for (i = 0; i < n; i++) {
3678 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3679 Py_INCREF(val);
3680 PyTuple_SET_ITEM(folded, i, val);
3681 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003682 if (tuple) {
3683 ADDOP_LOAD_CONST_NEW(c, folded);
3684 } else {
3685 if (add == SET_ADD) {
3686 Py_SETREF(folded, PyFrozenSet_New(folded));
3687 if (folded == NULL) {
3688 return 0;
3689 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003690 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003691 ADDOP_I(c, build, pushed);
3692 ADDOP_LOAD_CONST_NEW(c, folded);
3693 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003694 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003695 return 1;
3696 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003697
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003698 for (i = 0; i < n; i++) {
3699 expr_ty elt = asdl_seq_GET(elts, i);
3700 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003701 seen_star = 1;
3702 }
3703 }
3704 if (seen_star) {
3705 seen_star = 0;
3706 for (i = 0; i < n; i++) {
3707 expr_ty elt = asdl_seq_GET(elts, i);
3708 if (elt->kind == Starred_kind) {
3709 if (seen_star == 0) {
3710 ADDOP_I(c, build, i+pushed);
3711 seen_star = 1;
3712 }
3713 VISIT(c, expr, elt->v.Starred.value);
3714 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003715 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003716 else {
3717 VISIT(c, expr, elt);
3718 if (seen_star) {
3719 ADDOP_I(c, add, 1);
3720 }
3721 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003722 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003723 assert(seen_star);
3724 if (tuple) {
3725 ADDOP(c, LIST_TO_TUPLE);
3726 }
3727 }
3728 else {
3729 for (i = 0; i < n; i++) {
3730 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003731 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003732 }
3733 if (tuple) {
3734 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3735 } else {
3736 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003737 }
3738 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003739 return 1;
3740}
3741
3742static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003743assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003744{
3745 Py_ssize_t n = asdl_seq_LEN(elts);
3746 Py_ssize_t i;
3747 int seen_star = 0;
3748 for (i = 0; i < n; i++) {
3749 expr_ty elt = asdl_seq_GET(elts, i);
3750 if (elt->kind == Starred_kind && !seen_star) {
3751 if ((i >= (1 << 8)) ||
3752 (n-i-1 >= (INT_MAX >> 8)))
3753 return compiler_error(c,
3754 "too many expressions in "
3755 "star-unpacking assignment");
3756 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3757 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003758 }
3759 else if (elt->kind == Starred_kind) {
3760 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003761 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003762 }
3763 }
3764 if (!seen_star) {
3765 ADDOP_I(c, UNPACK_SEQUENCE, n);
3766 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003767 for (i = 0; i < n; i++) {
3768 expr_ty elt = asdl_seq_GET(elts, i);
3769 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3770 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003771 return 1;
3772}
3773
3774static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775compiler_list(struct compiler *c, expr_ty e)
3776{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003777 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003778 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003779 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003781 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003782 return starunpack_helper(c, elts, 0, BUILD_LIST,
3783 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003785 else
3786 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788}
3789
3790static int
3791compiler_tuple(struct compiler *c, expr_ty e)
3792{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003793 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003794 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 return assignment_helper(c, elts);
3796 }
3797 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003798 return starunpack_helper(c, elts, 0, BUILD_LIST,
3799 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003800 }
3801 else
3802 VISIT_SEQ(c, expr, elts);
3803 return 1;
3804}
3805
3806static int
3807compiler_set(struct compiler *c, expr_ty e)
3808{
Mark Shannon13bc1392020-01-23 09:25:17 +00003809 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3810 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003811}
3812
3813static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003814are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003815{
3816 Py_ssize_t i;
3817 for (i = begin; i < end; i++) {
3818 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003819 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003820 return 0;
3821 }
3822 return 1;
3823}
3824
3825static int
3826compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3827{
3828 Py_ssize_t i, n = end - begin;
3829 PyObject *keys, *key;
3830 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3831 for (i = begin; i < end; i++) {
3832 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3833 }
3834 keys = PyTuple_New(n);
3835 if (keys == NULL) {
3836 return 0;
3837 }
3838 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003839 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003840 Py_INCREF(key);
3841 PyTuple_SET_ITEM(keys, i - begin, key);
3842 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003843 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003844 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3845 }
3846 else {
3847 for (i = begin; i < end; i++) {
3848 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3849 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3850 }
3851 ADDOP_I(c, BUILD_MAP, n);
3852 }
3853 return 1;
3854}
3855
3856static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003857compiler_dict(struct compiler *c, expr_ty e)
3858{
Victor Stinner976bb402016-03-23 11:36:19 +01003859 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003860 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003861 int is_unpacking = 0;
3862 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003863 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003864 elements = 0;
3865 for (i = 0; i < n; i++) {
3866 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003867 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003868 if (elements) {
3869 if (!compiler_subdict(c, e, i - elements, i)) {
3870 return 0;
3871 }
3872 if (have_dict) {
3873 ADDOP_I(c, DICT_UPDATE, 1);
3874 }
3875 have_dict = 1;
3876 elements = 0;
3877 }
3878 if (have_dict == 0) {
3879 ADDOP_I(c, BUILD_MAP, 0);
3880 have_dict = 1;
3881 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003882 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003883 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003884 }
3885 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003886 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003887 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003888 return 0;
3889 }
3890 if (have_dict) {
3891 ADDOP_I(c, DICT_UPDATE, 1);
3892 }
3893 have_dict = 1;
3894 elements = 0;
3895 }
3896 else {
3897 elements++;
3898 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 }
3900 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003901 if (elements) {
3902 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003903 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003904 }
3905 if (have_dict) {
3906 ADDOP_I(c, DICT_UPDATE, 1);
3907 }
3908 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003909 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003910 if (!have_dict) {
3911 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 }
3913 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914}
3915
3916static int
3917compiler_compare(struct compiler *c, expr_ty e)
3918{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003919 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003921 if (!check_compare(c, e)) {
3922 return 0;
3923 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003925 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3926 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3927 if (n == 0) {
3928 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003929 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003930 }
3931 else {
3932 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 if (cleanup == NULL)
3934 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003935 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 VISIT(c, expr,
3937 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003938 ADDOP(c, DUP_TOP);
3939 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003940 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003941 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003942 NEXT_BLOCK(c);
3943 }
3944 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003945 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 basicblock *end = compiler_new_block(c);
3947 if (end == NULL)
3948 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00003949 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 compiler_use_next_block(c, cleanup);
3951 ADDOP(c, ROT_TWO);
3952 ADDOP(c, POP_TOP);
3953 compiler_use_next_block(c, end);
3954 }
3955 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003956}
3957
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003958static PyTypeObject *
3959infer_type(expr_ty e)
3960{
3961 switch (e->kind) {
3962 case Tuple_kind:
3963 return &PyTuple_Type;
3964 case List_kind:
3965 case ListComp_kind:
3966 return &PyList_Type;
3967 case Dict_kind:
3968 case DictComp_kind:
3969 return &PyDict_Type;
3970 case Set_kind:
3971 case SetComp_kind:
3972 return &PySet_Type;
3973 case GeneratorExp_kind:
3974 return &PyGen_Type;
3975 case Lambda_kind:
3976 return &PyFunction_Type;
3977 case JoinedStr_kind:
3978 case FormattedValue_kind:
3979 return &PyUnicode_Type;
3980 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003981 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003982 default:
3983 return NULL;
3984 }
3985}
3986
3987static int
3988check_caller(struct compiler *c, expr_ty e)
3989{
3990 switch (e->kind) {
3991 case Constant_kind:
3992 case Tuple_kind:
3993 case List_kind:
3994 case ListComp_kind:
3995 case Dict_kind:
3996 case DictComp_kind:
3997 case Set_kind:
3998 case SetComp_kind:
3999 case GeneratorExp_kind:
4000 case JoinedStr_kind:
4001 case FormattedValue_kind:
4002 return compiler_warn(c, "'%.200s' object is not callable; "
4003 "perhaps you missed a comma?",
4004 infer_type(e)->tp_name);
4005 default:
4006 return 1;
4007 }
4008}
4009
4010static int
4011check_subscripter(struct compiler *c, expr_ty e)
4012{
4013 PyObject *v;
4014
4015 switch (e->kind) {
4016 case Constant_kind:
4017 v = e->v.Constant.value;
4018 if (!(v == Py_None || v == Py_Ellipsis ||
4019 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4020 PyAnySet_Check(v)))
4021 {
4022 return 1;
4023 }
4024 /* fall through */
4025 case Set_kind:
4026 case SetComp_kind:
4027 case GeneratorExp_kind:
4028 case Lambda_kind:
4029 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4030 "perhaps you missed a comma?",
4031 infer_type(e)->tp_name);
4032 default:
4033 return 1;
4034 }
4035}
4036
4037static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004038check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004039{
4040 PyObject *v;
4041
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004042 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004043 if (index_type == NULL
4044 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4045 || index_type == &PySlice_Type) {
4046 return 1;
4047 }
4048
4049 switch (e->kind) {
4050 case Constant_kind:
4051 v = e->v.Constant.value;
4052 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4053 return 1;
4054 }
4055 /* fall through */
4056 case Tuple_kind:
4057 case List_kind:
4058 case ListComp_kind:
4059 case JoinedStr_kind:
4060 case FormattedValue_kind:
4061 return compiler_warn(c, "%.200s indices must be integers or slices, "
4062 "not %.200s; "
4063 "perhaps you missed a comma?",
4064 infer_type(e)->tp_name,
4065 index_type->tp_name);
4066 default:
4067 return 1;
4068 }
4069}
4070
Zackery Spytz97f5de02019-03-22 01:30:32 -06004071// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004072static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004073maybe_optimize_method_call(struct compiler *c, expr_ty e)
4074{
4075 Py_ssize_t argsl, i;
4076 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004077 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004078
4079 /* Check that the call node is an attribute access, and that
4080 the call doesn't have keyword parameters. */
4081 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4082 asdl_seq_LEN(e->v.Call.keywords))
4083 return -1;
4084
4085 /* Check that there are no *varargs types of arguments. */
4086 argsl = asdl_seq_LEN(args);
4087 for (i = 0; i < argsl; i++) {
4088 expr_ty elt = asdl_seq_GET(args, i);
4089 if (elt->kind == Starred_kind) {
4090 return -1;
4091 }
4092 }
4093
4094 /* Alright, we can optimize the code. */
4095 VISIT(c, expr, meth->v.Attribute.value);
4096 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4097 VISIT_SEQ(c, expr, e->v.Call.args);
4098 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4099 return 1;
4100}
4101
4102static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004103validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004104{
4105 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4106 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004107 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4108 if (key->arg == NULL) {
4109 continue;
4110 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004111 if (forbidden_name(c, key->arg, Store)) {
4112 return -1;
4113 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004114 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004115 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4116 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4117 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4118 if (msg == NULL) {
4119 return -1;
4120 }
4121 c->u->u_col_offset = other->col_offset;
4122 compiler_error(c, PyUnicode_AsUTF8(msg));
4123 Py_DECREF(msg);
4124 return -1;
4125 }
4126 }
4127 }
4128 return 0;
4129}
4130
4131static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004132compiler_call(struct compiler *c, expr_ty e)
4133{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004134 int ret = maybe_optimize_method_call(c, e);
4135 if (ret >= 0) {
4136 return ret;
4137 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004138 if (!check_caller(c, e->v.Call.func)) {
4139 return 0;
4140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 VISIT(c, expr, e->v.Call.func);
4142 return compiler_call_helper(c, 0,
4143 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004144 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004145}
4146
Eric V. Smith235a6f02015-09-19 14:51:32 -04004147static int
4148compiler_joined_str(struct compiler *c, expr_ty e)
4149{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004150 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004151 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4152 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004153 return 1;
4154}
4155
Eric V. Smitha78c7952015-11-03 12:45:05 -05004156/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004157static int
4158compiler_formatted_value(struct compiler *c, expr_ty e)
4159{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004160 /* Our oparg encodes 2 pieces of information: the conversion
4161 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004162
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004163 Convert the conversion char to 3 bits:
4164 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004165 !s : 001 0x1 FVC_STR
4166 !r : 010 0x2 FVC_REPR
4167 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004168
Eric V. Smitha78c7952015-11-03 12:45:05 -05004169 next bit is whether or not we have a format spec:
4170 yes : 100 0x4
4171 no : 000 0x0
4172 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004173
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004174 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004175 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004176
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004177 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004178 VISIT(c, expr, e->v.FormattedValue.value);
4179
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004180 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004181 case 's': oparg = FVC_STR; break;
4182 case 'r': oparg = FVC_REPR; break;
4183 case 'a': oparg = FVC_ASCII; break;
4184 case -1: oparg = FVC_NONE; break;
4185 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004186 PyErr_Format(PyExc_SystemError,
4187 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004188 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004189 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004190 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004191 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004192 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004193 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004194 }
4195
Eric V. Smitha78c7952015-11-03 12:45:05 -05004196 /* And push our opcode and oparg */
4197 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004198
Eric V. Smith235a6f02015-09-19 14:51:32 -04004199 return 1;
4200}
4201
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004202static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004203compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004204{
4205 Py_ssize_t i, n = end - begin;
4206 keyword_ty kw;
4207 PyObject *keys, *key;
4208 assert(n > 0);
4209 if (n > 1) {
4210 for (i = begin; i < end; i++) {
4211 kw = asdl_seq_GET(keywords, i);
4212 VISIT(c, expr, kw->value);
4213 }
4214 keys = PyTuple_New(n);
4215 if (keys == NULL) {
4216 return 0;
4217 }
4218 for (i = begin; i < end; i++) {
4219 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4220 Py_INCREF(key);
4221 PyTuple_SET_ITEM(keys, i - begin, key);
4222 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004223 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004224 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4225 }
4226 else {
4227 /* a for loop only executes once */
4228 for (i = begin; i < end; i++) {
4229 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004230 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004231 VISIT(c, expr, kw->value);
4232 }
4233 ADDOP_I(c, BUILD_MAP, n);
4234 }
4235 return 1;
4236}
4237
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004238/* shared code between compiler_call and compiler_class */
4239static int
4240compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004241 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004242 asdl_expr_seq *args,
4243 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004244{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004245 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004246
Pablo Galindo254ec782020-04-03 20:37:13 +01004247 if (validate_keywords(c, keywords) == -1) {
4248 return 0;
4249 }
4250
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004251 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004252 nkwelts = asdl_seq_LEN(keywords);
4253
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004254 for (i = 0; i < nelts; i++) {
4255 expr_ty elt = asdl_seq_GET(args, i);
4256 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004257 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004258 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004259 }
4260 for (i = 0; i < nkwelts; i++) {
4261 keyword_ty kw = asdl_seq_GET(keywords, i);
4262 if (kw->arg == NULL) {
4263 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004266
Mark Shannon13bc1392020-01-23 09:25:17 +00004267 /* No * or ** args, so can use faster calling sequence */
4268 for (i = 0; i < nelts; i++) {
4269 expr_ty elt = asdl_seq_GET(args, i);
4270 assert(elt->kind != Starred_kind);
4271 VISIT(c, expr, elt);
4272 }
4273 if (nkwelts) {
4274 PyObject *names;
4275 VISIT_SEQ(c, keyword, keywords);
4276 names = PyTuple_New(nkwelts);
4277 if (names == NULL) {
4278 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004279 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004280 for (i = 0; i < nkwelts; i++) {
4281 keyword_ty kw = asdl_seq_GET(keywords, i);
4282 Py_INCREF(kw->arg);
4283 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004284 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004285 ADDOP_LOAD_CONST_NEW(c, names);
4286 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4287 return 1;
4288 }
4289 else {
4290 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4291 return 1;
4292 }
4293
4294ex_call:
4295
4296 /* Do positional arguments. */
4297 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4298 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4299 }
4300 else if (starunpack_helper(c, args, n, BUILD_LIST,
4301 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4302 return 0;
4303 }
4304 /* Then keyword arguments */
4305 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004306 /* Has a new dict been pushed */
4307 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004308
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004309 nseen = 0; /* the number of keyword arguments on the stack following */
4310 for (i = 0; i < nkwelts; i++) {
4311 keyword_ty kw = asdl_seq_GET(keywords, i);
4312 if (kw->arg == NULL) {
4313 /* A keyword argument unpacking. */
4314 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004315 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004316 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004317 }
Mark Shannondb64f122020-06-01 10:42:42 +01004318 if (have_dict) {
4319 ADDOP_I(c, DICT_MERGE, 1);
4320 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004321 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004322 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004323 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004324 if (!have_dict) {
4325 ADDOP_I(c, BUILD_MAP, 0);
4326 have_dict = 1;
4327 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004328 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004329 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004330 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004331 else {
4332 nseen++;
4333 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004334 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004335 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004336 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004337 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004338 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004339 }
4340 if (have_dict) {
4341 ADDOP_I(c, DICT_MERGE, 1);
4342 }
4343 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004344 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004345 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004347 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4348 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349}
4350
Nick Coghlan650f0d02007-04-15 12:05:43 +00004351
4352/* List and set comprehensions and generator expressions work by creating a
4353 nested function to perform the actual iteration. This means that the
4354 iteration variables don't leak into the current scope.
4355 The defined function is called immediately following its definition, with the
4356 result of that call being the result of the expression.
4357 The LC/SC version returns the populated container, while the GE version is
4358 flagged in symtable.c as a generator, so it returns the generator object
4359 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004360
4361 Possible cleanups:
4362 - iterate over the generator sequence instead of using recursion
4363*/
4364
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004365
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004366static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004368 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004369 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004371{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004372 comprehension_ty gen;
4373 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4374 if (gen->is_async) {
4375 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004376 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004377 } else {
4378 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004379 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004380 }
4381}
4382
4383static int
4384compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004385 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004386 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004387 expr_ty elt, expr_ty val, int type)
4388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 /* generate code for the iterator, then each of the ifs,
4390 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 comprehension_ty gen;
4393 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004394 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 start = compiler_new_block(c);
4397 skip = compiler_new_block(c);
4398 if_cleanup = compiler_new_block(c);
4399 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4402 anchor == NULL)
4403 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 if (gen_index == 0) {
4408 /* Receive outermost iter as an implicit argument */
4409 c->u->u_argcount = 1;
4410 ADDOP_I(c, LOAD_FAST, 0);
4411 }
4412 else {
4413 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004414 /* Fast path for the temporary variable assignment idiom:
4415 for y in [f(x)]
4416 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004417 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004418 switch (gen->iter->kind) {
4419 case List_kind:
4420 elts = gen->iter->v.List.elts;
4421 break;
4422 case Tuple_kind:
4423 elts = gen->iter->v.Tuple.elts;
4424 break;
4425 default:
4426 elts = NULL;
4427 }
4428 if (asdl_seq_LEN(elts) == 1) {
4429 expr_ty elt = asdl_seq_GET(elts, 0);
4430 if (elt->kind != Starred_kind) {
4431 VISIT(c, expr, elt);
4432 start = NULL;
4433 }
4434 }
4435 if (start) {
4436 VISIT(c, expr, gen->iter);
4437 ADDOP(c, GET_ITER);
4438 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004440 if (start) {
4441 depth++;
4442 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004443 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004444 NEXT_BLOCK(c);
4445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 /* XXX this needs to be cleaned up...a lot! */
4449 n = asdl_seq_LEN(gen->ifs);
4450 for (i = 0; i < n; i++) {
4451 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004452 if (!compiler_jump_if(c, e, if_cleanup, 0))
4453 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 NEXT_BLOCK(c);
4455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 if (++gen_index < asdl_seq_LEN(generators))
4458 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004459 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 elt, val, type))
4461 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 /* only append after the last for generator */
4464 if (gen_index >= asdl_seq_LEN(generators)) {
4465 /* comprehension specific code */
4466 switch (type) {
4467 case COMP_GENEXP:
4468 VISIT(c, expr, elt);
4469 ADDOP(c, YIELD_VALUE);
4470 ADDOP(c, POP_TOP);
4471 break;
4472 case COMP_LISTCOMP:
4473 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004474 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 break;
4476 case COMP_SETCOMP:
4477 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004478 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 break;
4480 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004481 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004484 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004485 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 break;
4487 default:
4488 return 0;
4489 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 compiler_use_next_block(c, skip);
4492 }
4493 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004494 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004495 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004496 compiler_use_next_block(c, anchor);
4497 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498
4499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004500}
4501
4502static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004503compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004504 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004505 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004506 expr_ty elt, expr_ty val, int type)
4507{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004509 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004510 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004511 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004513 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004514
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004515 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004516 return 0;
4517 }
4518
4519 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4520
4521 if (gen_index == 0) {
4522 /* Receive outermost iter as an implicit argument */
4523 c->u->u_argcount = 1;
4524 ADDOP_I(c, LOAD_FAST, 0);
4525 }
4526 else {
4527 /* Sub-iter - calculate on the fly */
4528 VISIT(c, expr, gen->iter);
4529 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530 }
4531
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004532 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004533
Mark Shannon582aaf12020-08-04 17:30:11 +01004534 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004535 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004536 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004537 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004538 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004539 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004540
4541 n = asdl_seq_LEN(gen->ifs);
4542 for (i = 0; i < n; i++) {
4543 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004544 if (!compiler_jump_if(c, e, if_cleanup, 0))
4545 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546 NEXT_BLOCK(c);
4547 }
4548
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004549 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004550 if (++gen_index < asdl_seq_LEN(generators))
4551 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004552 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 elt, val, type))
4554 return 0;
4555
4556 /* only append after the last for generator */
4557 if (gen_index >= asdl_seq_LEN(generators)) {
4558 /* comprehension specific code */
4559 switch (type) {
4560 case COMP_GENEXP:
4561 VISIT(c, expr, elt);
4562 ADDOP(c, YIELD_VALUE);
4563 ADDOP(c, POP_TOP);
4564 break;
4565 case COMP_LISTCOMP:
4566 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004567 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004568 break;
4569 case COMP_SETCOMP:
4570 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004571 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004572 break;
4573 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004574 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004575 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004576 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004577 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004578 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004579 break;
4580 default:
4581 return 0;
4582 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004583 }
4584 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004585 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004586
4587 compiler_use_next_block(c, except);
4588 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004589
4590 return 1;
4591}
4592
4593static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004594compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004595 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004596 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004599 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004600 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004601 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004602 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004603
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004604
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004605 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004606
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004607 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004608 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4609 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004610 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004612 }
4613
4614 is_async_generator = c->u->u_ste->ste_coroutine;
4615
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004616 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004617 compiler_error(c, "asynchronous comprehension outside of "
4618 "an asynchronous function");
4619 goto error_in_scope;
4620 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 if (type != COMP_GENEXP) {
4623 int op;
4624 switch (type) {
4625 case COMP_LISTCOMP:
4626 op = BUILD_LIST;
4627 break;
4628 case COMP_SETCOMP:
4629 op = BUILD_SET;
4630 break;
4631 case COMP_DICTCOMP:
4632 op = BUILD_MAP;
4633 break;
4634 default:
4635 PyErr_Format(PyExc_SystemError,
4636 "unknown comprehension type %d", type);
4637 goto error_in_scope;
4638 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 ADDOP_I(c, op, 0);
4641 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004642
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004643 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 val, type))
4645 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 if (type != COMP_GENEXP) {
4648 ADDOP(c, RETURN_VALUE);
4649 }
4650
4651 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004652 qualname = c->u->u_qualname;
4653 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004655 if (top_level_await && is_async_generator){
4656 c->u->u_ste->ste_coroutine = 1;
4657 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004658 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 goto error;
4660
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004661 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004663 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 Py_DECREF(co);
4665
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004666 VISIT(c, expr, outermost->iter);
4667
4668 if (outermost->is_async) {
4669 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004670 } else {
4671 ADDOP(c, GET_ITER);
4672 }
4673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004675
4676 if (is_async_generator && type != COMP_GENEXP) {
4677 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004678 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004679 ADDOP(c, YIELD_FROM);
4680 }
4681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004683error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004685error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004686 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 Py_XDECREF(co);
4688 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004689}
4690
4691static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004692compiler_genexp(struct compiler *c, expr_ty e)
4693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 static identifier name;
4695 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004696 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 if (!name)
4698 return 0;
4699 }
4700 assert(e->kind == GeneratorExp_kind);
4701 return compiler_comprehension(c, e, COMP_GENEXP, name,
4702 e->v.GeneratorExp.generators,
4703 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004704}
4705
4706static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004707compiler_listcomp(struct compiler *c, expr_ty e)
4708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 static identifier name;
4710 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004711 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 if (!name)
4713 return 0;
4714 }
4715 assert(e->kind == ListComp_kind);
4716 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4717 e->v.ListComp.generators,
4718 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004719}
4720
4721static int
4722compiler_setcomp(struct compiler *c, expr_ty e)
4723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 static identifier name;
4725 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004726 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 if (!name)
4728 return 0;
4729 }
4730 assert(e->kind == SetComp_kind);
4731 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4732 e->v.SetComp.generators,
4733 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004734}
4735
4736
4737static int
4738compiler_dictcomp(struct compiler *c, expr_ty e)
4739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 static identifier name;
4741 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004742 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 if (!name)
4744 return 0;
4745 }
4746 assert(e->kind == DictComp_kind);
4747 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4748 e->v.DictComp.generators,
4749 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004750}
4751
4752
4753static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004754compiler_visit_keyword(struct compiler *c, keyword_ty k)
4755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 VISIT(c, expr, k->value);
4757 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004758}
4759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004761 whether they are true or false.
4762
4763 Return values: 1 for true, 0 for false, -1 for non-constant.
4764 */
4765
4766static int
Mark Shannonfee55262019-11-21 09:11:43 +00004767compiler_with_except_finish(struct compiler *c) {
4768 basicblock *exit;
4769 exit = compiler_new_block(c);
4770 if (exit == NULL)
4771 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004772 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004773 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004774 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004775 compiler_use_next_block(c, exit);
4776 ADDOP(c, POP_TOP);
4777 ADDOP(c, POP_TOP);
4778 ADDOP(c, POP_TOP);
4779 ADDOP(c, POP_EXCEPT);
4780 ADDOP(c, POP_TOP);
4781 return 1;
4782}
Yury Selivanov75445082015-05-11 22:57:16 -04004783
4784/*
4785 Implements the async with statement.
4786
4787 The semantics outlined in that PEP are as follows:
4788
4789 async with EXPR as VAR:
4790 BLOCK
4791
4792 It is implemented roughly as:
4793
4794 context = EXPR
4795 exit = context.__aexit__ # not calling it
4796 value = await context.__aenter__()
4797 try:
4798 VAR = value # if VAR present in the syntax
4799 BLOCK
4800 finally:
4801 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004802 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004803 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004804 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004805 if not (await exit(*exc)):
4806 raise
4807 */
4808static int
4809compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4810{
Mark Shannonfee55262019-11-21 09:11:43 +00004811 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004812 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4813
4814 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004815 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004816 c->u->u_ste->ste_coroutine = 1;
4817 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004818 return compiler_error(c, "'async with' outside async function");
4819 }
Yury Selivanov75445082015-05-11 22:57:16 -04004820
4821 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004822 final = compiler_new_block(c);
4823 exit = compiler_new_block(c);
4824 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004825 return 0;
4826
4827 /* Evaluate EXPR */
4828 VISIT(c, expr, item->context_expr);
4829
4830 ADDOP(c, BEFORE_ASYNC_WITH);
4831 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004832 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004833 ADDOP(c, YIELD_FROM);
4834
Mark Shannon582aaf12020-08-04 17:30:11 +01004835 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004836
4837 /* SETUP_ASYNC_WITH pushes a finally block. */
4838 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004839 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004840 return 0;
4841 }
4842
4843 if (item->optional_vars) {
4844 VISIT(c, expr, item->optional_vars);
4845 }
4846 else {
4847 /* Discard result from context.__aenter__() */
4848 ADDOP(c, POP_TOP);
4849 }
4850
4851 pos++;
4852 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4853 /* BLOCK code */
4854 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4855 else if (!compiler_async_with(c, s, pos))
4856 return 0;
4857
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004858 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004859 ADDOP(c, POP_BLOCK);
4860 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004861
Mark Shannonfee55262019-11-21 09:11:43 +00004862 /* For successful outcome:
4863 * call __exit__(None, None, None)
4864 */
4865 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004866 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004867 ADDOP(c, GET_AWAITABLE);
4868 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4869 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004870
Mark Shannonfee55262019-11-21 09:11:43 +00004871 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004872
Mark Shannon582aaf12020-08-04 17:30:11 +01004873 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004874
4875 /* For exceptional outcome: */
4876 compiler_use_next_block(c, final);
4877
4878 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004879 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004880 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004881 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004882 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004883
Mark Shannonfee55262019-11-21 09:11:43 +00004884compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004885 return 1;
4886}
4887
4888
Guido van Rossumc2e20742006-02-27 22:32:47 +00004889/*
4890 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004891 with EXPR as VAR:
4892 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004893 is implemented as:
4894 <code for EXPR>
4895 SETUP_WITH E
4896 <code to store to VAR> or POP_TOP
4897 <code for BLOCK>
4898 LOAD_CONST (None, None, None)
4899 CALL_FUNCTION_EX 0
4900 JUMP_FORWARD EXIT
4901 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4902 POP_JUMP_IF_TRUE T:
4903 RERAISE
4904 T: POP_TOP * 3 (remove exception from stack)
4905 POP_EXCEPT
4906 POP_TOP
4907 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004908 */
Mark Shannonfee55262019-11-21 09:11:43 +00004909
Guido van Rossumc2e20742006-02-27 22:32:47 +00004910static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004911compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004912{
Mark Shannonfee55262019-11-21 09:11:43 +00004913 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004914 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004915
4916 assert(s->kind == With_kind);
4917
Guido van Rossumc2e20742006-02-27 22:32:47 +00004918 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004919 final = compiler_new_block(c);
4920 exit = compiler_new_block(c);
4921 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004922 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004923
Thomas Wouters477c8d52006-05-27 19:21:47 +00004924 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004925 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004926 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004927 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004928
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004929 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004930 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004931 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004932 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004933 }
4934
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004935 if (item->optional_vars) {
4936 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004937 }
4938 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004939 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004940 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004941 }
4942
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004943 pos++;
4944 if (pos == asdl_seq_LEN(s->v.With.items))
4945 /* BLOCK code */
4946 VISIT_SEQ(c, stmt, s->v.With.body)
4947 else if (!compiler_with(c, s, pos))
4948 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004949
Mark Shannon3bd60352021-01-13 12:05:43 +00004950
4951 /* Mark all following code as artificial */
4952 c->u->u_lineno = -1;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004953 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004954 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004955
Mark Shannonfee55262019-11-21 09:11:43 +00004956 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004957
Mark Shannonfee55262019-11-21 09:11:43 +00004958 /* For successful outcome:
4959 * call __exit__(None, None, None)
4960 */
4961 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004962 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004963 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004964 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004965
Mark Shannonfee55262019-11-21 09:11:43 +00004966 /* For exceptional outcome: */
4967 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004968
Mark Shannonfee55262019-11-21 09:11:43 +00004969 ADDOP(c, WITH_EXCEPT_START);
4970 compiler_with_except_finish(c);
4971
4972 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004973 return 1;
4974}
4975
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004976static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004977compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004980 case NamedExpr_kind:
4981 VISIT(c, expr, e->v.NamedExpr.value);
4982 ADDOP(c, DUP_TOP);
4983 VISIT(c, expr, e->v.NamedExpr.target);
4984 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 case BoolOp_kind:
4986 return compiler_boolop(c, e);
4987 case BinOp_kind:
4988 VISIT(c, expr, e->v.BinOp.left);
4989 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004990 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 break;
4992 case UnaryOp_kind:
4993 VISIT(c, expr, e->v.UnaryOp.operand);
4994 ADDOP(c, unaryop(e->v.UnaryOp.op));
4995 break;
4996 case Lambda_kind:
4997 return compiler_lambda(c, e);
4998 case IfExp_kind:
4999 return compiler_ifexp(c, e);
5000 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005001 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005002 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005003 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 case GeneratorExp_kind:
5005 return compiler_genexp(c, e);
5006 case ListComp_kind:
5007 return compiler_listcomp(c, e);
5008 case SetComp_kind:
5009 return compiler_setcomp(c, e);
5010 case DictComp_kind:
5011 return compiler_dictcomp(c, e);
5012 case Yield_kind:
5013 if (c->u->u_ste->ste_type != FunctionBlock)
5014 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005015 if (e->v.Yield.value) {
5016 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005017 }
5018 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005019 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005020 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005021 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005022 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005023 case YieldFrom_kind:
5024 if (c->u->u_ste->ste_type != FunctionBlock)
5025 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005026
5027 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5028 return compiler_error(c, "'yield from' inside async function");
5029
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005030 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005031 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005032 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005033 ADDOP(c, YIELD_FROM);
5034 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005035 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005036 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005037 if (c->u->u_ste->ste_type != FunctionBlock){
5038 return compiler_error(c, "'await' outside function");
5039 }
Yury Selivanov75445082015-05-11 22:57:16 -04005040
Victor Stinner331a6a52019-05-27 16:39:22 +02005041 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005042 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5043 return compiler_error(c, "'await' outside async function");
5044 }
5045 }
Yury Selivanov75445082015-05-11 22:57:16 -04005046
5047 VISIT(c, expr, e->v.Await.value);
5048 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005049 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005050 ADDOP(c, YIELD_FROM);
5051 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 case Compare_kind:
5053 return compiler_compare(c, e);
5054 case Call_kind:
5055 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005056 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005057 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005058 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005059 case JoinedStr_kind:
5060 return compiler_joined_str(c, e);
5061 case FormattedValue_kind:
5062 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 /* The following exprs can be assignment targets. */
5064 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005065 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 case Load:
5068 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5069 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005070 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005071 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5072 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5074 break;
5075 case Del:
5076 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5077 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 }
5079 break;
5080 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005081 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 case Starred_kind:
5083 switch (e->v.Starred.ctx) {
5084 case Store:
5085 /* In all legitimate cases, the Starred node was already replaced
5086 * by compiler_list/compiler_tuple. XXX: is that okay? */
5087 return compiler_error(c,
5088 "starred assignment target must be in a list or tuple");
5089 default:
5090 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005091 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005093 break;
5094 case Slice_kind:
5095 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 case Name_kind:
5097 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5098 /* child nodes of List and Tuple will have expr_context set */
5099 case List_kind:
5100 return compiler_list(c, e);
5101 case Tuple_kind:
5102 return compiler_tuple(c, e);
5103 }
5104 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005105}
5106
5107static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005108compiler_visit_expr(struct compiler *c, expr_ty e)
5109{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005110 int old_lineno = c->u->u_lineno;
5111 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005112 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005113 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005114 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005115 c->u->u_col_offset = old_col_offset;
5116 return res;
5117}
5118
5119static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005120compiler_augassign(struct compiler *c, stmt_ty s)
5121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005123 expr_ty e = s->v.AugAssign.target;
5124
5125 int old_lineno = c->u->u_lineno;
5126 int old_col_offset = c->u->u_col_offset;
5127 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005129 switch (e->kind) {
5130 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005131 VISIT(c, expr, e->v.Attribute.value);
5132 ADDOP(c, DUP_TOP);
5133 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005134 break;
5135 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005136 VISIT(c, expr, e->v.Subscript.value);
5137 VISIT(c, expr, e->v.Subscript.slice);
5138 ADDOP(c, DUP_TOP_TWO);
5139 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 break;
5141 case Name_kind:
5142 if (!compiler_nameop(c, e->v.Name.id, Load))
5143 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005144 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005145 default:
5146 PyErr_Format(PyExc_SystemError,
5147 "invalid node type (%d) for augmented assignment",
5148 e->kind);
5149 return 0;
5150 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005151
5152 c->u->u_lineno = old_lineno;
5153 c->u->u_col_offset = old_col_offset;
5154
5155 VISIT(c, expr, s->v.AugAssign.value);
5156 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5157
5158 SET_LOC(c, e);
5159
5160 switch (e->kind) {
5161 case Attribute_kind:
5162 ADDOP(c, ROT_TWO);
5163 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5164 break;
5165 case Subscript_kind:
5166 ADDOP(c, ROT_THREE);
5167 ADDOP(c, STORE_SUBSCR);
5168 break;
5169 case Name_kind:
5170 return compiler_nameop(c, e->v.Name.id, Store);
5171 default:
5172 Py_UNREACHABLE();
5173 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005174 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005175}
5176
5177static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005178check_ann_expr(struct compiler *c, expr_ty e)
5179{
5180 VISIT(c, expr, e);
5181 ADDOP(c, POP_TOP);
5182 return 1;
5183}
5184
5185static int
5186check_annotation(struct compiler *c, stmt_ty s)
5187{
5188 /* Annotations are only evaluated in a module or class. */
5189 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5190 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5191 return check_ann_expr(c, s->v.AnnAssign.annotation);
5192 }
5193 return 1;
5194}
5195
5196static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005197check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005198{
5199 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005200 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005201 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005202 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005203 return 0;
5204 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005205 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5206 return 0;
5207 }
5208 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5209 return 0;
5210 }
5211 return 1;
5212 case Tuple_kind: {
5213 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005214 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005215 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005216 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005217 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005218 return 0;
5219 }
5220 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005221 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005222 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005223 default:
5224 return check_ann_expr(c, e);
5225 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005226}
5227
5228static int
5229compiler_annassign(struct compiler *c, stmt_ty s)
5230{
5231 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005232 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005233
5234 assert(s->kind == AnnAssign_kind);
5235
5236 /* We perform the actual assignment first. */
5237 if (s->v.AnnAssign.value) {
5238 VISIT(c, expr, s->v.AnnAssign.value);
5239 VISIT(c, expr, targ);
5240 }
5241 switch (targ->kind) {
5242 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005243 if (forbidden_name(c, targ->v.Name.id, Store))
5244 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005245 /* If we have a simple name in a module or class, store annotation. */
5246 if (s->v.AnnAssign.simple &&
5247 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5248 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005249 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005250 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005251 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005252 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005253 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005254 }
5255 break;
5256 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005257 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5258 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005259 if (!s->v.AnnAssign.value &&
5260 !check_ann_expr(c, targ->v.Attribute.value)) {
5261 return 0;
5262 }
5263 break;
5264 case Subscript_kind:
5265 if (!s->v.AnnAssign.value &&
5266 (!check_ann_expr(c, targ->v.Subscript.value) ||
5267 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5268 return 0;
5269 }
5270 break;
5271 default:
5272 PyErr_Format(PyExc_SystemError,
5273 "invalid node type (%d) for annotated assignment",
5274 targ->kind);
5275 return 0;
5276 }
5277 /* Annotation is evaluated last. */
5278 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5279 return 0;
5280 }
5281 return 1;
5282}
5283
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005284/* Raises a SyntaxError and returns 0.
5285 If something goes wrong, a different exception may be raised.
5286*/
5287
5288static int
5289compiler_error(struct compiler *c, const char *errstr)
5290{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005291 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005293
Victor Stinner14e461d2013-08-26 22:28:21 +02005294 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 if (!loc) {
5296 Py_INCREF(Py_None);
5297 loc = Py_None;
5298 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005299 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005300 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 if (!u)
5302 goto exit;
5303 v = Py_BuildValue("(zO)", errstr, u);
5304 if (!v)
5305 goto exit;
5306 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005307 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005308 Py_DECREF(loc);
5309 Py_XDECREF(u);
5310 Py_XDECREF(v);
5311 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005312}
5313
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005314/* Emits a SyntaxWarning and returns 1 on success.
5315 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5316 and returns 0.
5317*/
5318static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005319compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005320{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005321 va_list vargs;
5322#ifdef HAVE_STDARG_PROTOTYPES
5323 va_start(vargs, format);
5324#else
5325 va_start(vargs);
5326#endif
5327 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5328 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005329 if (msg == NULL) {
5330 return 0;
5331 }
5332 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5333 c->u->u_lineno, NULL, NULL) < 0)
5334 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005335 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005336 /* Replace the SyntaxWarning exception with a SyntaxError
5337 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005338 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005339 assert(PyUnicode_AsUTF8(msg) != NULL);
5340 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005341 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005342 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005343 return 0;
5344 }
5345 Py_DECREF(msg);
5346 return 1;
5347}
5348
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005349static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005350compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005351{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005352 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005354
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005355 if (ctx == Load) {
5356 if (!check_subscripter(c, e->v.Subscript.value)) {
5357 return 0;
5358 }
5359 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5360 return 0;
5361 }
5362 }
5363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 case Store: op = STORE_SUBSCR; break;
5367 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005369 assert(op);
5370 VISIT(c, expr, e->v.Subscript.value);
5371 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 ADDOP(c, op);
5373 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005374}
5375
5376static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005377compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 int n = 2;
5380 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 /* only handles the cases where BUILD_SLICE is emitted */
5383 if (s->v.Slice.lower) {
5384 VISIT(c, expr, s->v.Slice.lower);
5385 }
5386 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005387 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 if (s->v.Slice.upper) {
5391 VISIT(c, expr, s->v.Slice.upper);
5392 }
5393 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005394 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 }
5396
5397 if (s->v.Slice.step) {
5398 n++;
5399 VISIT(c, expr, s->v.Slice.step);
5400 }
5401 ADDOP_I(c, BUILD_SLICE, n);
5402 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005403}
5404
Thomas Wouters89f507f2006-12-13 04:49:30 +00005405/* End of the compiler section, beginning of the assembler section */
5406
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005407/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005408 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005409
5410 XXX must handle implicit jumps from one block to next
5411*/
5412
Thomas Wouters89f507f2006-12-13 04:49:30 +00005413struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 PyObject *a_bytecode; /* string containing bytecode */
5415 int a_offset; /* offset into bytecode */
5416 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 PyObject *a_lnotab; /* string containing lnotab */
5418 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005419 int a_prevlineno; /* lineno of last emitted line in line table */
5420 int a_lineno; /* lineno of last emitted instruction */
5421 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005422 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005423};
5424
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005425Py_LOCAL_INLINE(void)
5426stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005427{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005428 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005429 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005430 assert(b->b_startdepth < 0);
5431 b->b_startdepth = depth;
5432 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005433 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005434}
5435
5436/* Find the flow path that needs the largest stack. We assume that
5437 * cycles in the flow graph have no net effect on the stack depth.
5438 */
5439static int
5440stackdepth(struct compiler *c)
5441{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005442 basicblock *b, *entryblock = NULL;
5443 basicblock **stack, **sp;
5444 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005446 b->b_startdepth = INT_MIN;
5447 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005448 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005449 }
5450 if (!entryblock)
5451 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005452 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5453 if (!stack) {
5454 PyErr_NoMemory();
5455 return -1;
5456 }
5457
5458 sp = stack;
5459 stackdepth_push(&sp, entryblock, 0);
5460 while (sp != stack) {
5461 b = *--sp;
5462 int depth = b->b_startdepth;
5463 assert(depth >= 0);
5464 basicblock *next = b->b_next;
5465 for (int i = 0; i < b->b_iused; i++) {
5466 struct instr *instr = &b->b_instr[i];
5467 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5468 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005469 _Py_FatalErrorFormat(__func__,
5470 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005471 }
5472 int new_depth = depth + effect;
5473 if (new_depth > maxdepth) {
5474 maxdepth = new_depth;
5475 }
5476 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005477 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005478 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5479 assert(effect != PY_INVALID_STACK_EFFECT);
5480 int target_depth = depth + effect;
5481 if (target_depth > maxdepth) {
5482 maxdepth = target_depth;
5483 }
5484 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005485 stackdepth_push(&sp, instr->i_target, target_depth);
5486 }
5487 depth = new_depth;
5488 if (instr->i_opcode == JUMP_ABSOLUTE ||
5489 instr->i_opcode == JUMP_FORWARD ||
5490 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005491 instr->i_opcode == RAISE_VARARGS ||
5492 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005493 {
5494 /* remaining code is dead */
5495 next = NULL;
5496 break;
5497 }
5498 }
5499 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005500 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005501 stackdepth_push(&sp, next, depth);
5502 }
5503 }
5504 PyObject_Free(stack);
5505 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005506}
5507
5508static int
5509assemble_init(struct assembler *a, int nblocks, int firstlineno)
5510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005512 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005513 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005515 if (a->a_bytecode == NULL) {
5516 goto error;
5517 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005519 if (a->a_lnotab == NULL) {
5520 goto error;
5521 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005522 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005524 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005525 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005526 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005527error:
5528 Py_XDECREF(a->a_bytecode);
5529 Py_XDECREF(a->a_lnotab);
5530 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005531}
5532
5533static void
5534assemble_free(struct assembler *a)
5535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 Py_XDECREF(a->a_bytecode);
5537 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005538}
5539
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005540static int
5541blocksize(basicblock *b)
5542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005543 int i;
5544 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005547 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005549}
5550
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005551static int
Mark Shannon877df852020-11-12 09:43:29 +00005552assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005553{
Mark Shannon877df852020-11-12 09:43:29 +00005554 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 if (a->a_lnotab_off + 2 >= len) {
5556 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5557 return 0;
5558 }
Mark Shannon877df852020-11-12 09:43:29 +00005559 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005560 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005562 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005563 *lnotab++ = bdelta;
5564 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005566}
5567
Mark Shannon877df852020-11-12 09:43:29 +00005568/* Appends a range to the end of the line number table. See
5569 * Objects/lnotab_notes.txt for the description of the line number table. */
5570
5571static int
5572assemble_line_range(struct assembler *a)
5573{
5574 int ldelta, bdelta;
5575 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5576 if (bdelta == 0) {
5577 return 1;
5578 }
5579 if (a->a_lineno < 0) {
5580 ldelta = -128;
5581 }
5582 else {
5583 ldelta = a->a_lineno - a->a_prevlineno;
5584 a->a_prevlineno = a->a_lineno;
5585 while (ldelta > 127) {
5586 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5587 return 0;
5588 }
5589 ldelta -= 127;
5590 }
5591 while (ldelta < -127) {
5592 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5593 return 0;
5594 }
5595 ldelta += 127;
5596 }
5597 }
5598 assert(-128 <= ldelta && ldelta < 128);
5599 while (bdelta > 254) {
5600 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5601 return 0;
5602 }
5603 ldelta = a->a_lineno < 0 ? -128 : 0;
5604 bdelta -= 254;
5605 }
5606 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5607 return 0;
5608 }
5609 a->a_lineno_start = a->a_offset;
5610 return 1;
5611}
5612
5613static int
5614assemble_lnotab(struct assembler *a, struct instr *i)
5615{
5616 if (i->i_lineno == a->a_lineno) {
5617 return 1;
5618 }
5619 if (!assemble_line_range(a)) {
5620 return 0;
5621 }
5622 a->a_lineno = i->i_lineno;
5623 return 1;
5624}
5625
5626
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005627/* assemble_emit()
5628 Extend the bytecode with a new instruction.
5629 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005630*/
5631
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005632static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005633assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005634{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005635 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005636 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005637 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005638
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005639 arg = i->i_oparg;
5640 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 if (i->i_lineno && !assemble_lnotab(a, i))
5642 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005643 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005644 if (len > PY_SSIZE_T_MAX / 2)
5645 return 0;
5646 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5647 return 0;
5648 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005649 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005651 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005653}
5654
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005655static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005656assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005659 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005660 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005662 /* Compute the size of each block and fixup jump args.
5663 Replace block pointer with position in bytecode. */
5664 do {
5665 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005666 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 bsize = blocksize(b);
5668 b->b_offset = totsize;
5669 totsize += bsize;
5670 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005671 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5673 bsize = b->b_offset;
5674 for (i = 0; i < b->b_iused; i++) {
5675 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005676 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 /* Relative jumps are computed relative to
5678 the instruction pointer after fetching
5679 the jump instruction.
5680 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005681 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005682 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005684 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005685 instr->i_oparg -= bsize;
5686 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005687 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005688 if (instrsize(instr->i_oparg) != isize) {
5689 extended_arg_recompile = 1;
5690 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 }
5693 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 /* XXX: This is an awful hack that could hurt performance, but
5696 on the bright side it should work until we come up
5697 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 The issue is that in the first loop blocksize() is called
5700 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005701 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005704 So we loop until we stop seeing new EXTENDED_ARGs.
5705 The only EXTENDED_ARGs that could be popping up are
5706 ones in jump instructions. So this should converge
5707 fairly quickly.
5708 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005709 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005710}
5711
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005712static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005713dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005716 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 tuple = PyTuple_New(size);
5719 if (tuple == NULL)
5720 return NULL;
5721 while (PyDict_Next(dict, &pos, &k, &v)) {
5722 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005723 Py_INCREF(k);
5724 assert((i - offset) < size);
5725 assert((i - offset) >= 0);
5726 PyTuple_SET_ITEM(tuple, i - offset, k);
5727 }
5728 return tuple;
5729}
5730
5731static PyObject *
5732consts_dict_keys_inorder(PyObject *dict)
5733{
5734 PyObject *consts, *k, *v;
5735 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5736
5737 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5738 if (consts == NULL)
5739 return NULL;
5740 while (PyDict_Next(dict, &pos, &k, &v)) {
5741 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005742 /* The keys of the dictionary can be tuples wrapping a contant.
5743 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5744 * the object we want is always second. */
5745 if (PyTuple_CheckExact(k)) {
5746 k = PyTuple_GET_ITEM(k, 1);
5747 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005749 assert(i < size);
5750 assert(i >= 0);
5751 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005753 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005754}
5755
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005756static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005757compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005760 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005761 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005762 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005763 if (ste->ste_nested)
5764 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005765 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005766 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005767 if (!ste->ste_generator && ste->ste_coroutine)
5768 flags |= CO_COROUTINE;
5769 if (ste->ste_generator && ste->ste_coroutine)
5770 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005771 if (ste->ste_varargs)
5772 flags |= CO_VARARGS;
5773 if (ste->ste_varkeywords)
5774 flags |= CO_VARKEYWORDS;
5775 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 /* (Only) inherit compilerflags in PyCF_MASK */
5778 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005779
Pablo Galindo90235812020-03-15 04:29:22 +00005780 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005781 ste->ste_coroutine &&
5782 !ste->ste_generator) {
5783 flags |= CO_COROUTINE;
5784 }
5785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005786 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005787}
5788
INADA Naokic2e16072018-11-26 21:23:22 +09005789// Merge *tuple* with constant cache.
5790// Unlike merge_consts_recursive(), this function doesn't work recursively.
5791static int
5792merge_const_tuple(struct compiler *c, PyObject **tuple)
5793{
5794 assert(PyTuple_CheckExact(*tuple));
5795
5796 PyObject *key = _PyCode_ConstantKey(*tuple);
5797 if (key == NULL) {
5798 return 0;
5799 }
5800
5801 // t is borrowed reference
5802 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5803 Py_DECREF(key);
5804 if (t == NULL) {
5805 return 0;
5806 }
5807 if (t == key) { // tuple is new constant.
5808 return 1;
5809 }
5810
5811 PyObject *u = PyTuple_GET_ITEM(t, 1);
5812 Py_INCREF(u);
5813 Py_DECREF(*tuple);
5814 *tuple = u;
5815 return 1;
5816}
5817
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005818static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005819makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005821 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 PyObject *names = NULL;
5823 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 PyObject *name = NULL;
5825 PyObject *freevars = NULL;
5826 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005827 Py_ssize_t nlocals;
5828 int nlocals_int;
5829 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005830 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 names = dict_keys_inorder(c->u->u_names, 0);
5833 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005834 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005835 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005836 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5838 if (!cellvars)
5839 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005840 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 if (!freevars)
5842 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005843
INADA Naokic2e16072018-11-26 21:23:22 +09005844 if (!merge_const_tuple(c, &names) ||
5845 !merge_const_tuple(c, &varnames) ||
5846 !merge_const_tuple(c, &cellvars) ||
5847 !merge_const_tuple(c, &freevars))
5848 {
5849 goto error;
5850 }
5851
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005852 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005853 assert(nlocals < INT_MAX);
5854 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005856 flags = compute_code_flags(c);
5857 if (flags < 0)
5858 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005859
Mark Shannon6e8128f2020-07-30 10:03:00 +01005860 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5861 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005862 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005863 }
INADA Naokic2e16072018-11-26 21:23:22 +09005864 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005865 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005866 goto error;
5867 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005869 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005870 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005871 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005872 maxdepth = stackdepth(c);
5873 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005874 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005875 goto error;
5876 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005877 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005878 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005879 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005880 varnames, freevars, cellvars, c->c_filename,
5881 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005882 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005883 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 Py_XDECREF(names);
5885 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 Py_XDECREF(name);
5887 Py_XDECREF(freevars);
5888 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005889 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005890}
5891
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005892
5893/* For debugging purposes only */
5894#if 0
5895static void
5896dump_instr(const struct instr *i)
5897{
Mark Shannon582aaf12020-08-04 17:30:11 +01005898 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5899 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005903 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005905 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005906 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5907 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005908}
5909
5910static void
5911dump_basicblock(const basicblock *b)
5912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005913 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005914 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5915 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005916 if (b->b_instr) {
5917 int i;
5918 for (i = 0; i < b->b_iused; i++) {
5919 fprintf(stderr, " [%02d] ", i);
5920 dump_instr(b->b_instr + i);
5921 }
5922 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005923}
5924#endif
5925
Mark Shannon5977a792020-12-02 13:31:40 +00005926
5927static int
5928normalize_basic_block(basicblock *bb);
5929
Mark Shannon6e8128f2020-07-30 10:03:00 +01005930static int
5931optimize_cfg(struct assembler *a, PyObject *consts);
5932
Mark Shannon5977a792020-12-02 13:31:40 +00005933static int
5934ensure_exits_have_lineno(struct compiler *c);
5935
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005936static PyCodeObject *
5937assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005939 basicblock *b, *entryblock;
5940 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005941 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005943 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005945 /* Make sure every block that falls off the end returns None.
5946 XXX NEXT_BLOCK() isn't quite right, because if the last
5947 block ends with a jump or return b_next shouldn't set.
5948 */
5949 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005950 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005952 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 ADDOP(c, RETURN_VALUE);
5954 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005955
Mark Shannon5977a792020-12-02 13:31:40 +00005956 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
5957 if (normalize_basic_block(b)) {
5958 goto error;
5959 }
5960 }
5961
5962 if (ensure_exits_have_lineno(c)) {
5963 goto error;
5964 }
5965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005966 nblocks = 0;
5967 entryblock = NULL;
5968 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5969 nblocks++;
5970 entryblock = b;
5971 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005973 /* Set firstlineno if it wasn't explicitly set. */
5974 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005975 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005976 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005977 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978 c->u->u_firstlineno = 1;
5979 }
Mark Shannon5977a792020-12-02 13:31:40 +00005980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5982 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005983 a.a_entry = entryblock;
5984 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005985
Mark Shannon6e8128f2020-07-30 10:03:00 +01005986 consts = consts_dict_keys_inorder(c->u->u_consts);
5987 if (consts == NULL) {
5988 goto error;
5989 }
5990 if (optimize_cfg(&a, consts)) {
5991 goto error;
5992 }
5993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005994 /* Can't modify the bytecode after computing jump offsets. */
5995 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005996
Mark Shannoncc75ab72020-11-12 19:49:33 +00005997 /* Emit code. */
5998 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 for (j = 0; j < b->b_iused; j++)
6000 if (!assemble_emit(&a, &b->b_instr[j]))
6001 goto error;
6002 }
Mark Shannon877df852020-11-12 09:43:29 +00006003 if (!assemble_line_range(&a)) {
6004 return 0;
6005 }
6006 /* Emit sentinel at end of line number table */
6007 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
6008 goto error;
6009 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006011 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6012 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006013 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006014 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006015
Mark Shannon6e8128f2020-07-30 10:03:00 +01006016 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006017 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006018 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 assemble_free(&a);
6020 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006021}
Georg Brandl8334fd92010-12-04 10:26:46 +00006022
6023#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006024PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006025PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6026 PyArena *arena)
6027{
6028 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6029}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006030
6031
6032/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6033 with LOAD_CONST (c1, c2, ... cn).
6034 The consts table must still be in list form so that the
6035 new constant (c1, c2, ... cn) can be appended.
6036 Called with codestr pointing to the first LOAD_CONST.
6037*/
6038static int
6039fold_tuple_on_constants(struct instr *inst,
6040 int n, PyObject *consts)
6041{
6042 /* Pre-conditions */
6043 assert(PyList_CheckExact(consts));
6044 assert(inst[n].i_opcode == BUILD_TUPLE);
6045 assert(inst[n].i_oparg == n);
6046
6047 for (int i = 0; i < n; i++) {
6048 if (inst[i].i_opcode != LOAD_CONST) {
6049 return 0;
6050 }
6051 }
6052
6053 /* Buildup new tuple of constants */
6054 PyObject *newconst = PyTuple_New(n);
6055 if (newconst == NULL) {
6056 return -1;
6057 }
6058 for (int i = 0; i < n; i++) {
6059 int arg = inst[i].i_oparg;
6060 PyObject *constant = PyList_GET_ITEM(consts, arg);
6061 Py_INCREF(constant);
6062 PyTuple_SET_ITEM(newconst, i, constant);
6063 }
6064 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006065 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006066 Py_DECREF(newconst);
6067 PyErr_SetString(PyExc_OverflowError, "too many constants");
6068 return -1;
6069 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006070 if (PyList_Append(consts, newconst)) {
6071 Py_DECREF(newconst);
6072 return -1;
6073 }
6074 Py_DECREF(newconst);
6075 for (int i = 0; i < n; i++) {
6076 inst[i].i_opcode = NOP;
6077 }
6078 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006079 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006080 return 0;
6081}
6082
Mark Shannon28b75c82020-12-23 11:43:10 +00006083
6084static int
6085eliminate_jump_to_jump(basicblock *bb, int opcode) {
6086 assert (bb->b_iused > 0);
6087 struct instr *inst = &bb->b_instr[bb->b_iused-1];
6088 assert (is_jump(inst));
6089 assert (inst->i_target->b_iused > 0);
6090 struct instr *target = &inst->i_target->b_instr[0];
6091 if (inst->i_target == target->i_target) {
6092 /* Nothing to do */
6093 return 0;
6094 }
6095 int lineno = target->i_lineno;
6096 if (add_jump_to_block(bb, opcode, lineno, target->i_target) == 0) {
6097 return -1;
6098 }
6099 assert (bb->b_iused >= 2);
6100 bb->b_instr[bb->b_iused-2].i_opcode = NOP;
6101 return 0;
6102}
6103
Mark Shannoncc75ab72020-11-12 19:49:33 +00006104/* Maximum size of basic block that should be copied in optimizer */
6105#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006106
6107/* Optimization */
6108static int
6109optimize_basic_block(basicblock *bb, PyObject *consts)
6110{
6111 assert(PyList_CheckExact(consts));
6112 struct instr nop;
6113 nop.i_opcode = NOP;
6114 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006115 for (int i = 0; i < bb->b_iused; i++) {
6116 struct instr *inst = &bb->b_instr[i];
6117 int oparg = inst->i_oparg;
6118 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006119 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006120 /* Skip over empty basic blocks. */
6121 while (inst->i_target->b_iused == 0) {
6122 inst->i_target = inst->i_target->b_next;
6123 }
6124 target = &inst->i_target->b_instr[0];
6125 }
6126 else {
6127 target = &nop;
6128 }
6129 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006130 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006131 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006132 {
6133 PyObject* cnt;
6134 int is_true;
6135 int jump_if_true;
6136 switch(nextop) {
6137 case POP_JUMP_IF_FALSE:
6138 case POP_JUMP_IF_TRUE:
6139 cnt = PyList_GET_ITEM(consts, oparg);
6140 is_true = PyObject_IsTrue(cnt);
6141 if (is_true == -1) {
6142 goto error;
6143 }
6144 inst->i_opcode = NOP;
6145 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6146 if (is_true == jump_if_true) {
6147 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6148 bb->b_nofallthrough = 1;
6149 }
6150 else {
6151 bb->b_instr[i+1].i_opcode = NOP;
6152 }
6153 break;
6154 case JUMP_IF_FALSE_OR_POP:
6155 case JUMP_IF_TRUE_OR_POP:
6156 cnt = PyList_GET_ITEM(consts, oparg);
6157 is_true = PyObject_IsTrue(cnt);
6158 if (is_true == -1) {
6159 goto error;
6160 }
6161 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6162 if (is_true == jump_if_true) {
6163 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6164 bb->b_nofallthrough = 1;
6165 }
6166 else {
6167 inst->i_opcode = NOP;
6168 bb->b_instr[i+1].i_opcode = NOP;
6169 }
6170 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006171 }
6172 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006173 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006174
6175 /* Try to fold tuples of constants.
6176 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6177 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6178 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6179 case BUILD_TUPLE:
6180 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6181 switch(oparg) {
6182 case 1:
6183 inst->i_opcode = NOP;
6184 bb->b_instr[i+1].i_opcode = NOP;
6185 break;
6186 case 2:
6187 inst->i_opcode = ROT_TWO;
6188 bb->b_instr[i+1].i_opcode = NOP;
6189 break;
6190 case 3:
6191 inst->i_opcode = ROT_THREE;
6192 bb->b_instr[i+1].i_opcode = ROT_TWO;
6193 }
6194 break;
6195 }
6196 if (i >= oparg) {
6197 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6198 goto error;
6199 }
6200 }
6201 break;
6202
6203 /* Simplify conditional jump to conditional jump where the
6204 result of the first test implies the success of a similar
6205 test or the failure of the opposite test.
6206 Arises in code like:
6207 "a and b or c"
6208 "(a and b) and c"
6209 "(a or b) or c"
6210 "(a or b) and c"
6211 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6212 --> x:JUMP_IF_FALSE_OR_POP z
6213 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6214 --> x:POP_JUMP_IF_FALSE y+1
6215 where y+1 is the instruction following the second test.
6216 */
6217 case JUMP_IF_FALSE_OR_POP:
6218 switch(target->i_opcode) {
6219 case POP_JUMP_IF_FALSE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006220 if (inst->i_lineno == target->i_lineno) {
6221 *inst = *target;
6222 i--;
6223 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006224 break;
6225 case JUMP_ABSOLUTE:
6226 case JUMP_FORWARD:
6227 case JUMP_IF_FALSE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006228 if (inst->i_lineno == target->i_lineno &&
6229 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006230 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006231 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006232 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006233 break;
6234 case JUMP_IF_TRUE_OR_POP:
6235 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006236 if (inst->i_lineno == target->i_lineno) {
6237 inst->i_opcode = POP_JUMP_IF_FALSE;
6238 inst->i_target = inst->i_target->b_next;
6239 --i;
6240 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006241 break;
6242 }
6243 break;
6244
6245 case JUMP_IF_TRUE_OR_POP:
6246 switch(target->i_opcode) {
6247 case POP_JUMP_IF_TRUE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006248 if (inst->i_lineno == target->i_lineno) {
6249 *inst = *target;
6250 i--;
6251 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006252 break;
6253 case JUMP_ABSOLUTE:
6254 case JUMP_FORWARD:
6255 case JUMP_IF_TRUE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006256 if (inst->i_lineno == target->i_lineno &&
6257 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006258 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006259 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006260 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006261 break;
6262 case JUMP_IF_FALSE_OR_POP:
6263 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006264 if (inst->i_lineno == target->i_lineno) {
6265 inst->i_opcode = POP_JUMP_IF_TRUE;
6266 inst->i_target = inst->i_target->b_next;
6267 --i;
6268 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006269 break;
6270 }
6271 break;
6272
6273 case POP_JUMP_IF_FALSE:
6274 switch(target->i_opcode) {
6275 case JUMP_ABSOLUTE:
6276 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006277 if (inst->i_lineno == target->i_lineno) {
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 }
6283 break;
6284
6285 case POP_JUMP_IF_TRUE:
6286 switch(target->i_opcode) {
6287 case JUMP_ABSOLUTE:
6288 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006289 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006290 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006291 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006292 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006293 break;
6294 }
6295 break;
6296
6297 case JUMP_ABSOLUTE:
6298 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006299 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006300 switch(target->i_opcode) {
6301 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006302 if (eliminate_jump_to_jump(bb, inst->i_opcode)) {
6303 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006304 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006305 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006306
Mark Shannon6e8128f2020-07-30 10:03:00 +01006307 case JUMP_ABSOLUTE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006308 if (eliminate_jump_to_jump(bb, JUMP_ABSOLUTE)) {
6309 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006310 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006311 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006312 default:
6313 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6314 basicblock *to_copy = inst->i_target;
6315 inst->i_opcode = NOP;
6316 for (i = 0; i < to_copy->b_iused; i++) {
6317 int index = compiler_next_instr(bb);
6318 if (index < 0) {
6319 return -1;
6320 }
6321 bb->b_instr[index] = to_copy->b_instr[i];
6322 }
6323 bb->b_exit = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006324 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006325 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006326 }
6327 }
6328 return 0;
6329error:
6330 return -1;
6331}
6332
6333
6334static void
Mark Shannon1659ad12021-01-13 15:05:04 +00006335clean_basic_block(basicblock *bb, int prev_lineno) {
6336 /* Remove NOPs when legal to do so. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006337 int dest = 0;
6338 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006339 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006340 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006341 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006342 if (lineno < 0) {
6343 continue;
6344 }
Mark Shannon266b4622020-11-17 19:30:14 +00006345 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006346 if (prev_lineno == lineno) {
6347 continue;
6348 }
Mark Shannon266b4622020-11-17 19:30:14 +00006349 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006350 if (src < bb->b_iused - 1) {
6351 int next_lineno = bb->b_instr[src+1].i_lineno;
6352 if (next_lineno < 0 || next_lineno == lineno) {
6353 bb->b_instr[src+1].i_lineno = lineno;
6354 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006355 }
6356 }
Mark Shannon266b4622020-11-17 19:30:14 +00006357 else {
6358 basicblock* next = bb->b_next;
6359 while (next && next->b_iused == 0) {
6360 next = next->b_next;
6361 }
6362 /* or if last instruction in BB and next BB has same line number */
6363 if (next) {
6364 if (lineno == next->b_instr[0].i_lineno) {
6365 continue;
6366 }
6367 }
6368 }
6369
Mark Shannon6e8128f2020-07-30 10:03:00 +01006370 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006371 if (dest != src) {
6372 bb->b_instr[dest] = bb->b_instr[src];
6373 }
6374 dest++;
6375 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006376 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006377 assert(dest <= bb->b_iused);
6378 bb->b_iused = dest;
6379}
6380
Mark Shannon266b4622020-11-17 19:30:14 +00006381static int
6382normalize_basic_block(basicblock *bb) {
6383 /* Mark blocks as exit and/or nofallthrough.
6384 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006385 for (int i = 0; i < bb->b_iused; i++) {
6386 switch(bb->b_instr[i].i_opcode) {
6387 case RETURN_VALUE:
6388 case RAISE_VARARGS:
6389 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006390 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00006391 bb->b_nofallthrough = 1;
6392 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006393 case JUMP_ABSOLUTE:
6394 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006395 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006396 /* fall through */
6397 case POP_JUMP_IF_FALSE:
6398 case POP_JUMP_IF_TRUE:
6399 case JUMP_IF_FALSE_OR_POP:
6400 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00006401 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00006402 if (i != bb->b_iused-1) {
6403 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6404 return -1;
6405 }
Mark Shannon5977a792020-12-02 13:31:40 +00006406 /* Skip over empty basic blocks. */
6407 while (bb->b_instr[i].i_target->b_iused == 0) {
6408 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
6409 }
6410
Mark Shannoncc75ab72020-11-12 19:49:33 +00006411 }
6412 }
Mark Shannon266b4622020-11-17 19:30:14 +00006413 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006414}
6415
Mark Shannon6e8128f2020-07-30 10:03:00 +01006416static int
6417mark_reachable(struct assembler *a) {
6418 basicblock **stack, **sp;
6419 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6420 if (stack == NULL) {
6421 return -1;
6422 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006423 a->a_entry->b_predecessors = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006424 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006425 while (sp > stack) {
6426 basicblock *b = *(--sp);
Mark Shannon3bd60352021-01-13 12:05:43 +00006427 if (b->b_next && !b->b_nofallthrough) {
6428 if (b->b_next->b_predecessors == 0) {
6429 *sp++ = b->b_next;
6430 }
6431 b->b_next->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006432 }
6433 for (int i = 0; i < b->b_iused; i++) {
6434 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006435 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006436 target = b->b_instr[i].i_target;
Mark Shannon3bd60352021-01-13 12:05:43 +00006437 if (target->b_predecessors == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006438 *sp++ = target;
6439 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006440 target->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006441 }
6442 }
6443 }
6444 PyObject_Free(stack);
6445 return 0;
6446}
6447
Mark Shannon3bd60352021-01-13 12:05:43 +00006448static void
6449eliminate_empty_basic_blocks(basicblock *entry) {
6450 /* Eliminate empty blocks */
6451 for (basicblock *b = entry; b != NULL; b = b->b_next) {
6452 basicblock *next = b->b_next;
6453 if (next) {
6454 while (next->b_iused == 0 && next->b_next) {
6455 next = next->b_next;
6456 }
6457 b->b_next = next;
6458 }
6459 }
6460 for (basicblock *b = entry; b != NULL; b = b->b_next) {
6461 if (b->b_iused == 0) {
6462 continue;
6463 }
6464 if (is_jump(&b->b_instr[b->b_iused-1])) {
6465 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6466 while (target->b_iused == 0) {
6467 target = target->b_next;
6468 }
6469 b->b_instr[b->b_iused-1].i_target = target;
6470 }
6471 }
6472}
6473
6474
Mark Shannon5977a792020-12-02 13:31:40 +00006475/* If an instruction has no line number, but it's predecessor in the BB does,
Mark Shannon3bd60352021-01-13 12:05:43 +00006476 * then copy the line number. If a successor block has no line number, and only
6477 * one predecessor, then inherit the line number.
6478 * This ensures that all exit blocks (with one predecessor) receive a line number.
6479 * Also reduces the size of the line number table,
Mark Shannon5977a792020-12-02 13:31:40 +00006480 * but has no impact on the generated line number events.
6481 */
6482static void
Mark Shannon3bd60352021-01-13 12:05:43 +00006483propogate_line_numbers(struct assembler *a) {
Mark Shannon5977a792020-12-02 13:31:40 +00006484 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006485 if (b->b_iused == 0) {
6486 continue;
6487 }
Mark Shannon5977a792020-12-02 13:31:40 +00006488 int prev_lineno = -1;
6489 for (int i = 0; i < b->b_iused; i++) {
6490 if (b->b_instr[i].i_lineno < 0) {
6491 b->b_instr[i].i_lineno = prev_lineno;
6492 }
6493 else {
6494 prev_lineno = b->b_instr[i].i_lineno;
6495 }
6496 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006497 if (!b->b_nofallthrough && b->b_next->b_predecessors == 1) {
6498 assert(b->b_next->b_iused);
6499 if (b->b_next->b_instr[0].i_lineno < 0) {
6500 b->b_next->b_instr[0].i_lineno = prev_lineno;
6501 }
6502 }
6503 if (is_jump(&b->b_instr[b->b_iused-1])) {
6504 switch (b->b_instr[b->b_iused-1].i_opcode) {
6505 /* Note: Only actual jumps, not exception handlers */
6506 case SETUP_ASYNC_WITH:
6507 case SETUP_WITH:
6508 case SETUP_FINALLY:
6509 continue;
6510 }
6511 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6512 if (target->b_predecessors == 1) {
6513 if (target->b_instr[0].i_lineno < 0) {
6514 target->b_instr[0].i_lineno = prev_lineno;
6515 }
6516 }
6517 }
Mark Shannon5977a792020-12-02 13:31:40 +00006518 }
6519}
6520
6521/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01006522 The consts object should still be in list form to allow new constants
6523 to be appended.
6524
6525 All transformations keep the code size the same or smaller.
6526 For those that reduce size, the gaps are initially filled with
6527 NOPs. Later those NOPs are removed.
6528*/
6529
6530static int
6531optimize_cfg(struct assembler *a, PyObject *consts)
6532{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006533 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006534 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006535 return -1;
6536 }
Mark Shannon1659ad12021-01-13 15:05:04 +00006537 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00006538 assert(b->b_predecessors == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006539 }
6540 if (mark_reachable(a)) {
6541 return -1;
6542 }
6543 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006544 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006545 if (b->b_predecessors == 0) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006546 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05306547 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006548 }
6549 }
Mark Shannon1659ad12021-01-13 15:05:04 +00006550 basicblock *pred = NULL;
6551 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6552 int prev_lineno = -1;
6553 if (pred && pred->b_iused) {
6554 prev_lineno = pred->b_instr[pred->b_iused-1].i_lineno;
6555 }
6556 clean_basic_block(b, prev_lineno);
6557 pred = b->b_nofallthrough ? NULL : b;
6558 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006559 eliminate_empty_basic_blocks(a->a_entry);
Om Gc71581c2020-12-16 17:48:05 +05306560 /* Delete jump instructions made redundant by previous step. If a non-empty
6561 block ends with a jump instruction, check if the next non-empty block
6562 reached through normal flow control is the target of that jump. If it
6563 is, then the jump instruction is redundant and can be deleted.
6564 */
Mark Shannon3bd60352021-01-13 12:05:43 +00006565 int maybe_empty_blocks = 0;
Om Gc71581c2020-12-16 17:48:05 +05306566 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6567 if (b->b_iused > 0) {
6568 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
6569 if (b_last_instr->i_opcode == POP_JUMP_IF_FALSE ||
6570 b_last_instr->i_opcode == POP_JUMP_IF_TRUE ||
6571 b_last_instr->i_opcode == JUMP_ABSOLUTE ||
6572 b_last_instr->i_opcode == JUMP_FORWARD) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006573 if (b_last_instr->i_target == b->b_next) {
6574 assert(b->b_next->b_iused);
Om Gc71581c2020-12-16 17:48:05 +05306575 b->b_nofallthrough = 0;
6576 switch(b_last_instr->i_opcode) {
6577 case POP_JUMP_IF_FALSE:
6578 case POP_JUMP_IF_TRUE:
6579 b_last_instr->i_opcode = POP_TOP;
6580 b_last_instr->i_target = NULL;
6581 b_last_instr->i_oparg = 0;
6582 break;
6583 case JUMP_ABSOLUTE:
6584 case JUMP_FORWARD:
6585 b_last_instr->i_opcode = NOP;
Mark Shannon1659ad12021-01-13 15:05:04 +00006586 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00006587 maybe_empty_blocks = 1;
Om Gc71581c2020-12-16 17:48:05 +05306588 break;
6589 }
Om Gc71581c2020-12-16 17:48:05 +05306590 }
6591 }
6592 }
6593 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006594 if (maybe_empty_blocks) {
6595 eliminate_empty_basic_blocks(a->a_entry);
6596 }
6597 propogate_line_numbers(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006598 return 0;
6599}
6600
Mark Shannon5977a792020-12-02 13:31:40 +00006601static inline int
6602is_exit_without_lineno(basicblock *b) {
6603 return b->b_exit && b->b_instr[0].i_lineno < 0;
6604}
6605
6606/* PEP 626 mandates that the f_lineno of a frame is correct
6607 * after a frame terminates. It would be prohibitively expensive
6608 * to continuously update the f_lineno field at runtime,
6609 * so we make sure that all exiting instruction (raises and returns)
6610 * have a valid line number, allowing us to compute f_lineno lazily.
6611 * We can do this by duplicating the exit blocks without line number
6612 * so that none have more than one predecessor. We can then safely
6613 * copy the line number from the sole predecessor block.
6614 */
6615static int
6616ensure_exits_have_lineno(struct compiler *c)
6617{
Mark Shannoneaccc122020-12-04 15:22:12 +00006618 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006619 /* Copy all exit blocks without line number that are targets of a jump.
6620 */
6621 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6622 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
6623 switch (b->b_instr[b->b_iused-1].i_opcode) {
6624 /* Note: Only actual jumps, not exception handlers */
6625 case SETUP_ASYNC_WITH:
6626 case SETUP_WITH:
6627 case SETUP_FINALLY:
6628 continue;
6629 }
6630 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6631 if (is_exit_without_lineno(target)) {
6632 basicblock *new_target = compiler_copy_block(c, target);
6633 if (new_target == NULL) {
6634 return -1;
6635 }
6636 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6637 b->b_instr[b->b_iused-1].i_target = new_target;
6638 }
6639 }
Mark Shannoneaccc122020-12-04 15:22:12 +00006640 entry = b;
6641 }
6642 assert(entry != NULL);
6643 if (is_exit_without_lineno(entry)) {
6644 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00006645 }
Mark Shannonee9f98d2021-01-05 12:04:10 +00006646 /* Eliminate empty blocks */
6647 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6648 while (b->b_next && b->b_next->b_iused == 0) {
6649 b->b_next = b->b_next->b_next;
6650 }
6651 }
Mark Shannon5977a792020-12-02 13:31:40 +00006652 /* Any remaining reachable exit blocks without line number can only be reached by
6653 * fall through, and thus can only have a single predecessor */
6654 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6655 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
6656 if (is_exit_without_lineno(b->b_next)) {
6657 assert(b->b_next->b_iused > 0);
6658 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6659 }
6660 }
6661 }
6662 return 0;
6663}
6664
6665
Mark Shannon6e8128f2020-07-30 10:03:00 +01006666/* Retained for API compatibility.
6667 * Optimization is now done in optimize_cfg */
6668
6669PyObject *
6670PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6671 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6672{
6673 Py_INCREF(code);
6674 return code;
6675}
6676