blob: 223c63637ff411e6f2f4c6b00e6053452fe2b831 [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 Stinnerad9a0662013-11-19 22:23:20 +0100670 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 c->c_nestlevel--;
674 compiler_unit_free(c->u);
675 /* Restore c->u to the parent unit. */
676 n = PyList_GET_SIZE(c->c_stack) - 1;
677 if (n >= 0) {
678 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400679 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 assert(c->u);
681 /* we are deleting from a list so this really shouldn't fail */
682 if (PySequence_DelItem(c->c_stack, n) < 0)
683 Py_FatalError("compiler_exit_scope()");
684 compiler_unit_check(c->u);
685 }
686 else
687 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000688
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000689}
690
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400691static int
692compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100693{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100694 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400695 _Py_static_string(dot_locals, ".<locals>");
696 Py_ssize_t stack_size;
697 struct compiler_unit *u = c->u;
698 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100699
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400700 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100701 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400702 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400703 if (stack_size > 1) {
704 int scope, force_global = 0;
705 struct compiler_unit *parent;
706 PyObject *mangled, *capsule;
707
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400708 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400709 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400710 assert(parent);
711
Yury Selivanov75445082015-05-11 22:57:16 -0400712 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
713 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
714 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400715 assert(u->u_name);
716 mangled = _Py_Mangle(parent->u_private, u->u_name);
717 if (!mangled)
718 return 0;
719 scope = PyST_GetScope(parent->u_ste, mangled);
720 Py_DECREF(mangled);
721 assert(scope != GLOBAL_IMPLICIT);
722 if (scope == GLOBAL_EXPLICIT)
723 force_global = 1;
724 }
725
726 if (!force_global) {
727 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400728 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400729 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
730 dot_locals_str = _PyUnicode_FromId(&dot_locals);
731 if (dot_locals_str == NULL)
732 return 0;
733 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
734 if (base == NULL)
735 return 0;
736 }
737 else {
738 Py_INCREF(parent->u_qualname);
739 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400740 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100741 }
742 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400743
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400744 if (base != NULL) {
745 dot_str = _PyUnicode_FromId(&dot);
746 if (dot_str == NULL) {
747 Py_DECREF(base);
748 return 0;
749 }
750 name = PyUnicode_Concat(base, dot_str);
751 Py_DECREF(base);
752 if (name == NULL)
753 return 0;
754 PyUnicode_Append(&name, u->u_name);
755 if (name == NULL)
756 return 0;
757 }
758 else {
759 Py_INCREF(u->u_name);
760 name = u->u_name;
761 }
762 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100763
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400764 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100765}
766
Eric V. Smith235a6f02015-09-19 14:51:32 -0400767
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000768/* Allocate a new block and return a pointer to it.
769 Returns NULL on error.
770*/
771
772static basicblock *
773compiler_new_block(struct compiler *c)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 basicblock *b;
776 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500779 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 if (b == NULL) {
781 PyErr_NoMemory();
782 return NULL;
783 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Extend the singly linked list of blocks with new block. */
785 b->b_list = u->u_blocks;
786 u->u_blocks = b;
787 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000788}
789
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791compiler_next_block(struct compiler *c)
792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 basicblock *block = compiler_new_block(c);
794 if (block == NULL)
795 return NULL;
796 c->u->u_curblock->b_next = block;
797 c->u->u_curblock = block;
798 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000799}
800
801static basicblock *
802compiler_use_next_block(struct compiler *c, basicblock *block)
803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 assert(block != NULL);
805 c->u->u_curblock->b_next = block;
806 c->u->u_curblock = block;
807 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000808}
809
Mark Shannon5977a792020-12-02 13:31:40 +0000810static basicblock *
811compiler_copy_block(struct compiler *c, basicblock *block)
812{
813 /* Cannot copy a block if it has a fallthrough, since
814 * a block can only have one fallthrough predecessor.
815 */
816 assert(block->b_nofallthrough);
817 basicblock *result = compiler_next_block(c);
818 if (result == NULL) {
819 return NULL;
820 }
821 for (int i = 0; i < block->b_iused; i++) {
822 int n = compiler_next_instr(result);
823 if (n < 0) {
824 return NULL;
825 }
826 result->b_instr[n] = block->b_instr[i];
827 }
828 result->b_exit = block->b_exit;
Mark Shannon3bd60352021-01-13 12:05:43 +0000829 result->b_nofallthrough = 1;
Mark Shannon5977a792020-12-02 13:31:40 +0000830 return result;
831}
832
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000833/* Returns the offset of the next instruction in the current block's
834 b_instr array. Resizes the b_instr as necessary.
835 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000836*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837
838static int
Andy Lester76d58772020-03-10 21:18:12 -0500839compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 assert(b != NULL);
842 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500843 b->b_instr = (struct instr *)PyObject_Calloc(
844 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (b->b_instr == NULL) {
846 PyErr_NoMemory();
847 return -1;
848 }
849 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 }
851 else if (b->b_iused == b->b_ialloc) {
852 struct instr *tmp;
853 size_t oldsize, newsize;
854 oldsize = b->b_ialloc * sizeof(struct instr);
855 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000856
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700857 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 PyErr_NoMemory();
859 return -1;
860 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (newsize == 0) {
863 PyErr_NoMemory();
864 return -1;
865 }
866 b->b_ialloc <<= 1;
867 tmp = (struct instr *)PyObject_Realloc(
868 (void *)b->b_instr, newsize);
869 if (tmp == NULL) {
870 PyErr_NoMemory();
871 return -1;
872 }
873 b->b_instr = tmp;
874 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
875 }
876 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000877}
878
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200879/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000880
Christian Heimes2202f872008-02-06 14:31:34 +0000881 The line number is reset in the following cases:
882 - when entering a new scope
883 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200884 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200885 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000886*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000887
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200888#define SET_LOC(c, x) \
889 (c)->u->u_lineno = (x)->lineno; \
890 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000891
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200892/* Return the stack effect of opcode with argument oparg.
893
894 Some opcodes have different stack effect when jump to the target and
895 when not jump. The 'jump' parameter specifies the case:
896
897 * 0 -- when not jump
898 * 1 -- when jump
899 * -1 -- maximal
900 */
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200901static int
902stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300905 case NOP:
906 case EXTENDED_ARG:
907 return 0;
908
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200909 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case POP_TOP:
911 return -1;
912 case ROT_TWO:
913 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200914 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 return 0;
916 case DUP_TOP:
917 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000918 case DUP_TOP_TWO:
919 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200921 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case UNARY_POSITIVE:
923 case UNARY_NEGATIVE:
924 case UNARY_NOT:
925 case UNARY_INVERT:
926 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case SET_ADD:
929 case LIST_APPEND:
930 return -1;
931 case MAP_ADD:
932 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000933
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200934 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 case BINARY_POWER:
936 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400937 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case BINARY_MODULO:
939 case BINARY_ADD:
940 case BINARY_SUBTRACT:
941 case BINARY_SUBSCR:
942 case BINARY_FLOOR_DIVIDE:
943 case BINARY_TRUE_DIVIDE:
944 return -1;
945 case INPLACE_FLOOR_DIVIDE:
946 case INPLACE_TRUE_DIVIDE:
947 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case INPLACE_ADD:
950 case INPLACE_SUBTRACT:
951 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400952 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case INPLACE_MODULO:
954 return -1;
955 case STORE_SUBSCR:
956 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case DELETE_SUBSCR:
958 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case BINARY_LSHIFT:
961 case BINARY_RSHIFT:
962 case BINARY_AND:
963 case BINARY_XOR:
964 case BINARY_OR:
965 return -1;
966 case INPLACE_POWER:
967 return -1;
968 case GET_ITER:
969 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case PRINT_EXPR:
972 return -1;
973 case LOAD_BUILD_CLASS:
974 return 1;
975 case INPLACE_LSHIFT:
976 case INPLACE_RSHIFT:
977 case INPLACE_AND:
978 case INPLACE_XOR:
979 case INPLACE_OR:
980 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200983 /* 1 in the normal flow.
984 * Restore the stack position and push 6 values before jumping to
985 * the handler if an exception be raised. */
986 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case RETURN_VALUE:
988 return -1;
989 case IMPORT_STAR:
990 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700991 case SETUP_ANNOTATIONS:
992 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case YIELD_VALUE:
994 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500995 case YIELD_FROM:
996 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case POP_BLOCK:
998 return 0;
999 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001000 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 case STORE_NAME:
1003 return -1;
1004 case DELETE_NAME:
1005 return 0;
1006 case UNPACK_SEQUENCE:
1007 return oparg-1;
1008 case UNPACK_EX:
1009 return (oparg&0xFF) + (oparg>>8);
1010 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001011 /* -1 at end of iterator, 1 if continue iterating. */
1012 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case STORE_ATTR:
1015 return -2;
1016 case DELETE_ATTR:
1017 return -1;
1018 case STORE_GLOBAL:
1019 return -1;
1020 case DELETE_GLOBAL:
1021 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 case LOAD_CONST:
1023 return 1;
1024 case LOAD_NAME:
1025 return 1;
1026 case BUILD_TUPLE:
1027 case BUILD_LIST:
1028 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001029 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 return 1-oparg;
1031 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001032 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001033 case BUILD_CONST_KEY_MAP:
1034 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case LOAD_ATTR:
1036 return 0;
1037 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001038 case IS_OP:
1039 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001041 case JUMP_IF_NOT_EXC_MATCH:
1042 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case IMPORT_NAME:
1044 return -1;
1045 case IMPORT_FROM:
1046 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001048 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case JUMP_ABSOLUTE:
1051 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001053 case JUMP_IF_TRUE_OR_POP:
1054 case JUMP_IF_FALSE_OR_POP:
1055 return jump ? 0 : -1;
1056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 case POP_JUMP_IF_FALSE:
1058 case POP_JUMP_IF_TRUE:
1059 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 case LOAD_GLOBAL:
1062 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001064 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001066 /* 0 in the normal flow.
1067 * Restore the stack position and push 6 values before jumping to
1068 * the handler if an exception be raised. */
1069 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001070 case RERAISE:
1071 return -3;
1072
1073 case WITH_EXCEPT_START:
1074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 case LOAD_FAST:
1077 return 1;
1078 case STORE_FAST:
1079 return -1;
1080 case DELETE_FAST:
1081 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 case RAISE_VARARGS:
1084 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001085
1086 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001088 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001089 case CALL_METHOD:
1090 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001092 return -oparg-1;
1093 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001094 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001095 case MAKE_FUNCTION:
1096 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1097 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 case BUILD_SLICE:
1099 if (oparg == 3)
1100 return -2;
1101 else
1102 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001104 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 case LOAD_CLOSURE:
1106 return 1;
1107 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001108 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 return 1;
1110 case STORE_DEREF:
1111 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001112 case DELETE_DEREF:
1113 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001114
1115 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001116 case GET_AWAITABLE:
1117 return 0;
1118 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001119 /* 0 in the normal flow.
1120 * Restore the stack position to the position before the result
1121 * of __aenter__ and push 6 values before jumping to the handler
1122 * if an exception be raised. */
1123 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001124 case BEFORE_ASYNC_WITH:
1125 return 1;
1126 case GET_AITER:
1127 return 0;
1128 case GET_ANEXT:
1129 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001130 case GET_YIELD_FROM_ITER:
1131 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001132 case END_ASYNC_FOR:
1133 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001134 case FORMAT_VALUE:
1135 /* If there's a fmt_spec on the stack, we go from 2->1,
1136 else 1->1. */
1137 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001138 case LOAD_METHOD:
1139 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001140 case LOAD_ASSERTION_ERROR:
1141 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001142 case LIST_TO_TUPLE:
1143 return 0;
1144 case LIST_EXTEND:
1145 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001146 case DICT_MERGE:
1147 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001148 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001150 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 }
Larry Hastings3a907972013-11-23 14:49:22 -08001152 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153}
1154
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001155int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001156PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1157{
1158 return stack_effect(opcode, oparg, jump);
1159}
1160
1161int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001162PyCompile_OpcodeStackEffect(int opcode, int oparg)
1163{
1164 return stack_effect(opcode, oparg, -1);
1165}
1166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167/* Add an opcode with no argument.
1168 Returns 0 on failure, 1 on success.
1169*/
1170
1171static int
Mark Shannon3bd60352021-01-13 12:05:43 +00001172compiler_addop_line(struct compiler *c, int opcode, int line)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 basicblock *b;
1175 struct instr *i;
1176 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001177 assert(!HAS_ARG(opcode));
Andy Lester76d58772020-03-10 21:18:12 -05001178 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (off < 0)
1180 return 0;
1181 b = c->u->u_curblock;
1182 i = &b->b_instr[off];
1183 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001184 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (opcode == RETURN_VALUE)
1186 b->b_return = 1;
Mark Shannon3bd60352021-01-13 12:05:43 +00001187 i->i_lineno = line;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189}
1190
Mark Shannon3bd60352021-01-13 12:05:43 +00001191static int
1192compiler_addop(struct compiler *c, int opcode)
1193{
1194 return compiler_addop_line(c, opcode, c->u->u_lineno);
1195}
1196
1197static int
1198compiler_addop_noline(struct compiler *c, int opcode)
1199{
1200 return compiler_addop_line(c, opcode, -1);
1201}
1202
1203
Victor Stinnerf8e32212013-11-19 23:56:34 +01001204static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001205compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001206{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001207 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001209
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001210 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001212 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001214 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001215 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001216 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 return -1;
1219 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001220 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 Py_DECREF(v);
1222 return -1;
1223 }
1224 Py_DECREF(v);
1225 }
1226 else
1227 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001228 return arg;
1229}
1230
INADA Naokic2e16072018-11-26 21:23:22 +09001231// Merge const *o* recursively and return constant key object.
1232static PyObject*
1233merge_consts_recursive(struct compiler *c, PyObject *o)
1234{
1235 // None and Ellipsis are singleton, and key is the singleton.
1236 // No need to merge object and key.
1237 if (o == Py_None || o == Py_Ellipsis) {
1238 Py_INCREF(o);
1239 return o;
1240 }
1241
1242 PyObject *key = _PyCode_ConstantKey(o);
1243 if (key == NULL) {
1244 return NULL;
1245 }
1246
1247 // t is borrowed reference
1248 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1249 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001250 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001251 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001252 Py_DECREF(key);
1253 return t;
1254 }
1255
INADA Naokif7e4d362018-11-29 00:58:46 +09001256 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001257 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001258 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001259 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001260 Py_ssize_t len = PyTuple_GET_SIZE(o);
1261 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001262 PyObject *item = PyTuple_GET_ITEM(o, i);
1263 PyObject *u = merge_consts_recursive(c, item);
1264 if (u == NULL) {
1265 Py_DECREF(key);
1266 return NULL;
1267 }
1268
1269 // See _PyCode_ConstantKey()
1270 PyObject *v; // borrowed
1271 if (PyTuple_CheckExact(u)) {
1272 v = PyTuple_GET_ITEM(u, 1);
1273 }
1274 else {
1275 v = u;
1276 }
1277 if (v != item) {
1278 Py_INCREF(v);
1279 PyTuple_SET_ITEM(o, i, v);
1280 Py_DECREF(item);
1281 }
1282
1283 Py_DECREF(u);
1284 }
1285 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001286 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001287 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001288 // constant keys.
1289 // See _PyCode_ConstantKey() for detail.
1290 assert(PyTuple_CheckExact(key));
1291 assert(PyTuple_GET_SIZE(key) == 2);
1292
1293 Py_ssize_t len = PySet_GET_SIZE(o);
1294 if (len == 0) { // empty frozenset should not be re-created.
1295 return key;
1296 }
1297 PyObject *tuple = PyTuple_New(len);
1298 if (tuple == NULL) {
1299 Py_DECREF(key);
1300 return NULL;
1301 }
1302 Py_ssize_t i = 0, pos = 0;
1303 PyObject *item;
1304 Py_hash_t hash;
1305 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1306 PyObject *k = merge_consts_recursive(c, item);
1307 if (k == NULL) {
1308 Py_DECREF(tuple);
1309 Py_DECREF(key);
1310 return NULL;
1311 }
1312 PyObject *u;
1313 if (PyTuple_CheckExact(k)) {
1314 u = PyTuple_GET_ITEM(k, 1);
1315 Py_INCREF(u);
1316 Py_DECREF(k);
1317 }
1318 else {
1319 u = k;
1320 }
1321 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1322 i++;
1323 }
1324
1325 // Instead of rewriting o, we create new frozenset and embed in the
1326 // key tuple. Caller should get merged frozenset from the key tuple.
1327 PyObject *new = PyFrozenSet_New(tuple);
1328 Py_DECREF(tuple);
1329 if (new == NULL) {
1330 Py_DECREF(key);
1331 return NULL;
1332 }
1333 assert(PyTuple_GET_ITEM(key, 1) == o);
1334 Py_DECREF(o);
1335 PyTuple_SET_ITEM(key, 1, new);
1336 }
INADA Naokic2e16072018-11-26 21:23:22 +09001337
1338 return key;
1339}
1340
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001341static Py_ssize_t
1342compiler_add_const(struct compiler *c, PyObject *o)
1343{
INADA Naokic2e16072018-11-26 21:23:22 +09001344 PyObject *key = merge_consts_recursive(c, o);
1345 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001346 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001347 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001348
Andy Lester76d58772020-03-10 21:18:12 -05001349 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001350 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352}
1353
1354static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001355compiler_addop_load_const(struct compiler *c, PyObject *o)
1356{
1357 Py_ssize_t arg = compiler_add_const(c, o);
1358 if (arg < 0)
1359 return 0;
1360 return compiler_addop_i(c, LOAD_CONST, arg);
1361}
1362
1363static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001364compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366{
Andy Lester76d58772020-03-10 21:18:12 -05001367 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001369 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370 return compiler_addop_i(c, opcode, arg);
1371}
1372
1373static int
1374compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001377 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001378
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001379 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1380 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001381 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001382 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001383 Py_DECREF(mangled);
1384 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001385 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001386 return compiler_addop_i(c, opcode, arg);
1387}
1388
1389/* Add an opcode with an integer argument.
1390 Returns 0 on failure, 1 on success.
1391*/
1392
1393static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001394compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 struct instr *i;
1397 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001398
Victor Stinner2ad474b2016-03-01 23:34:47 +01001399 /* oparg value is unsigned, but a signed C int is usually used to store
1400 it in the C code (like Python/ceval.c).
1401
1402 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1403
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001404 The argument of a concrete bytecode instruction is limited to 8-bit.
1405 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1406 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001407 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001408
Andy Lester76d58772020-03-10 21:18:12 -05001409 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (off < 0)
1411 return 0;
1412 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001413 i->i_opcode = opcode;
1414 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001415 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001417}
1418
Mark Shannon28b75c82020-12-23 11:43:10 +00001419static int add_jump_to_block(basicblock *b, int opcode, int lineno, basicblock *target)
1420{
1421 assert(HAS_ARG(opcode));
1422 assert(b != NULL);
1423 assert(target != NULL);
1424
1425 int off = compiler_next_instr(b);
1426 struct instr *i = &b->b_instr[off];
1427 if (off < 0) {
1428 return 0;
1429 }
1430 i->i_opcode = opcode;
1431 i->i_target = target;
1432 i->i_lineno = lineno;
1433 return 1;
1434}
1435
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001436static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001437compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438{
Mark Shannon28b75c82020-12-23 11:43:10 +00001439 return add_jump_to_block(c->u->u_curblock, opcode, c->u->u_lineno, b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440}
1441
Mark Shannon127dde52021-01-04 18:06:55 +00001442static int
1443compiler_addop_j_noline(struct compiler *c, int opcode, basicblock *b)
1444{
1445 return add_jump_to_block(c->u->u_curblock, opcode, -1, b);
1446}
1447
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001448/* NEXT_BLOCK() creates an implicit jump from the current block
1449 to the new block.
1450
1451 The returns inside this macro make it impossible to decref objects
1452 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (compiler_next_block((C)) == NULL) \
1456 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457}
1458
1459#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (!compiler_addop((C), (OP))) \
1461 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462}
1463
Mark Shannon3bd60352021-01-13 12:05:43 +00001464#define ADDOP_NOLINE(C, OP) { \
1465 if (!compiler_addop_noline((C), (OP))) \
1466 return 0; \
1467}
1468
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001469#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (!compiler_addop((C), (OP))) { \
1471 compiler_exit_scope(c); \
1472 return 0; \
1473 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001474}
1475
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001476#define ADDOP_LOAD_CONST(C, O) { \
1477 if (!compiler_addop_load_const((C), (O))) \
1478 return 0; \
1479}
1480
1481/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1482#define ADDOP_LOAD_CONST_NEW(C, O) { \
1483 PyObject *__new_const = (O); \
1484 if (__new_const == NULL) { \
1485 return 0; \
1486 } \
1487 if (!compiler_addop_load_const((C), __new_const)) { \
1488 Py_DECREF(__new_const); \
1489 return 0; \
1490 } \
1491 Py_DECREF(__new_const); \
1492}
1493
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1496 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001497}
1498
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001499/* Same as ADDOP_O, but steals a reference. */
1500#define ADDOP_N(C, OP, O, TYPE) { \
1501 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1502 Py_DECREF((O)); \
1503 return 0; \
1504 } \
1505 Py_DECREF((O)); \
1506}
1507
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001508#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1510 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001511}
1512
1513#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 if (!compiler_addop_i((C), (OP), (O))) \
1515 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516}
1517
Mark Shannon582aaf12020-08-04 17:30:11 +01001518#define ADDOP_JUMP(C, OP, O) { \
1519 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001521}
1522
Mark Shannon127dde52021-01-04 18:06:55 +00001523/* Add a jump with no line number.
1524 * Used for artificial jumps that have no corresponding
1525 * token in the source code. */
1526#define ADDOP_JUMP_NOLINE(C, OP, O) { \
1527 if (!compiler_addop_j_noline((C), (OP), (O))) \
1528 return 0; \
1529}
1530
Mark Shannon9af0e472020-01-14 10:12:45 +00001531#define ADDOP_COMPARE(C, CMP) { \
1532 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1533 return 0; \
1534}
1535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1537 the ASDL name to synthesize the name of the C type and the visit function.
1538*/
1539
1540#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 if (!compiler_visit_ ## TYPE((C), (V))) \
1542 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001543}
1544
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001545#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (!compiler_visit_ ## TYPE((C), (V))) { \
1547 compiler_exit_scope(c); \
1548 return 0; \
1549 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001550}
1551
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001552#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 if (!compiler_visit_slice((C), (V), (CTX))) \
1554 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555}
1556
1557#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001559 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1561 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1562 if (!compiler_visit_ ## TYPE((C), elt)) \
1563 return 0; \
1564 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565}
1566
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001567#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001569 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1571 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1572 if (!compiler_visit_ ## TYPE((C), elt)) { \
1573 compiler_exit_scope(c); \
1574 return 0; \
1575 } \
1576 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001577}
1578
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001579/* Search if variable annotations are present statically in a block. */
1580
1581static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001582find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001583{
1584 int i, j, res = 0;
1585 stmt_ty st;
1586
1587 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1588 st = (stmt_ty)asdl_seq_GET(stmts, i);
1589 switch (st->kind) {
1590 case AnnAssign_kind:
1591 return 1;
1592 case For_kind:
1593 res = find_ann(st->v.For.body) ||
1594 find_ann(st->v.For.orelse);
1595 break;
1596 case AsyncFor_kind:
1597 res = find_ann(st->v.AsyncFor.body) ||
1598 find_ann(st->v.AsyncFor.orelse);
1599 break;
1600 case While_kind:
1601 res = find_ann(st->v.While.body) ||
1602 find_ann(st->v.While.orelse);
1603 break;
1604 case If_kind:
1605 res = find_ann(st->v.If.body) ||
1606 find_ann(st->v.If.orelse);
1607 break;
1608 case With_kind:
1609 res = find_ann(st->v.With.body);
1610 break;
1611 case AsyncWith_kind:
1612 res = find_ann(st->v.AsyncWith.body);
1613 break;
1614 case Try_kind:
1615 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1616 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1617 st->v.Try.handlers, j);
1618 if (find_ann(handler->v.ExceptHandler.body)) {
1619 return 1;
1620 }
1621 }
1622 res = find_ann(st->v.Try.body) ||
1623 find_ann(st->v.Try.finalbody) ||
1624 find_ann(st->v.Try.orelse);
1625 break;
1626 default:
1627 res = 0;
1628 }
1629 if (res) {
1630 break;
1631 }
1632 }
1633 return res;
1634}
1635
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001636/*
1637 * Frame block handling functions
1638 */
1639
1640static int
1641compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001642 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001643{
1644 struct fblockinfo *f;
1645 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001646 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001647 }
1648 f = &c->u->u_fblock[c->u->u_nfblocks++];
1649 f->fb_type = t;
1650 f->fb_block = b;
1651 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001652 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001653 return 1;
1654}
1655
1656static void
1657compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1658{
1659 struct compiler_unit *u = c->u;
1660 assert(u->u_nfblocks > 0);
1661 u->u_nfblocks--;
1662 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1663 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1664}
1665
Mark Shannonfee55262019-11-21 09:11:43 +00001666static int
1667compiler_call_exit_with_nones(struct compiler *c) {
1668 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1669 ADDOP(c, DUP_TOP);
1670 ADDOP(c, DUP_TOP);
1671 ADDOP_I(c, CALL_FUNCTION, 3);
1672 return 1;
1673}
1674
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001675/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001676 * popping the blocks will be restored afterwards, unless another
1677 * return, break or continue is found. In which case, the TOS will
1678 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001679 */
1680static int
1681compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1682 int preserve_tos)
1683{
1684 switch (info->fb_type) {
1685 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001686 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001687 return 1;
1688
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001689 case FOR_LOOP:
1690 /* Pop the iterator */
1691 if (preserve_tos) {
1692 ADDOP(c, ROT_TWO);
1693 }
1694 ADDOP(c, POP_TOP);
1695 return 1;
1696
Mark Shannon02d126a2020-09-25 14:04:19 +01001697 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001698 ADDOP(c, POP_BLOCK);
1699 return 1;
1700
1701 case FINALLY_TRY:
Mark Shannon5274b682020-12-16 13:07:01 +00001702 /* This POP_BLOCK gets the line number of the unwinding statement */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001703 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001704 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001705 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1706 return 0;
1707 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001708 }
Mark Shannon5274b682020-12-16 13:07:01 +00001709 /* Emit the finally block */
Mark Shannonfee55262019-11-21 09:11:43 +00001710 VISIT_SEQ(c, stmt, info->fb_datum);
1711 if (preserve_tos) {
1712 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001713 }
Mark Shannon5274b682020-12-16 13:07:01 +00001714 /* The finally block should appear to execute after the
1715 * statement causing the unwinding, so make the unwinding
1716 * instruction artificial */
1717 c->u->u_lineno = -1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001718 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001719
Mark Shannonfee55262019-11-21 09:11:43 +00001720 case FINALLY_END:
1721 if (preserve_tos) {
1722 ADDOP(c, ROT_FOUR);
1723 }
1724 ADDOP(c, POP_TOP);
1725 ADDOP(c, POP_TOP);
1726 ADDOP(c, POP_TOP);
1727 if (preserve_tos) {
1728 ADDOP(c, ROT_FOUR);
1729 }
1730 ADDOP(c, POP_EXCEPT);
1731 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001732
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001733 case WITH:
1734 case ASYNC_WITH:
1735 ADDOP(c, POP_BLOCK);
1736 if (preserve_tos) {
1737 ADDOP(c, ROT_TWO);
1738 }
Mark Shannonfee55262019-11-21 09:11:43 +00001739 if(!compiler_call_exit_with_nones(c)) {
1740 return 0;
1741 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001742 if (info->fb_type == ASYNC_WITH) {
1743 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001744 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001745 ADDOP(c, YIELD_FROM);
1746 }
Mark Shannonfee55262019-11-21 09:11:43 +00001747 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001748 return 1;
1749
1750 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001751 if (info->fb_datum) {
1752 ADDOP(c, POP_BLOCK);
1753 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001754 if (preserve_tos) {
1755 ADDOP(c, ROT_FOUR);
1756 }
Mark Shannonfee55262019-11-21 09:11:43 +00001757 ADDOP(c, POP_EXCEPT);
1758 if (info->fb_datum) {
1759 ADDOP_LOAD_CONST(c, Py_None);
1760 compiler_nameop(c, info->fb_datum, Store);
1761 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001762 }
Mark Shannonfee55262019-11-21 09:11:43 +00001763 return 1;
1764
1765 case POP_VALUE:
1766 if (preserve_tos) {
1767 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001768 }
Mark Shannonfee55262019-11-21 09:11:43 +00001769 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001770 return 1;
1771 }
1772 Py_UNREACHABLE();
1773}
1774
Mark Shannonfee55262019-11-21 09:11:43 +00001775/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1776static int
1777compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1778 if (c->u->u_nfblocks == 0) {
1779 return 1;
1780 }
1781 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1782 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1783 *loop = top;
1784 return 1;
1785 }
1786 struct fblockinfo copy = *top;
1787 c->u->u_nfblocks--;
1788 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1789 return 0;
1790 }
1791 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1792 return 0;
1793 }
1794 c->u->u_fblock[c->u->u_nfblocks] = copy;
1795 c->u->u_nfblocks++;
1796 return 1;
1797}
1798
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001799/* Compile a sequence of statements, checking for a docstring
1800 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801
1802static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001803compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001805 int i = 0;
1806 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001807 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001808
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001809 /* Set current line number to the line number of first statement.
1810 This way line number for SETUP_ANNOTATIONS will always
1811 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301812 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001813 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001814 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001815 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001816 }
1817 /* Every annotated class and module should have __annotations__. */
1818 if (find_ann(stmts)) {
1819 ADDOP(c, SETUP_ANNOTATIONS);
1820 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001821 if (!asdl_seq_LEN(stmts))
1822 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001823 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001824 if (c->c_optimize < 2) {
1825 docstring = _PyAST_GetDocString(stmts);
1826 if (docstring) {
1827 i = 1;
1828 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1829 assert(st->kind == Expr_kind);
1830 VISIT(c, expr, st->v.Expr.value);
1831 if (!compiler_nameop(c, __doc__, Store))
1832 return 0;
1833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001835 for (; i < asdl_seq_LEN(stmts); i++)
1836 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838}
1839
1840static PyCodeObject *
1841compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyCodeObject *co;
1844 int addNone = 1;
1845 static PyObject *module;
1846 if (!module) {
1847 module = PyUnicode_InternFromString("<module>");
1848 if (!module)
1849 return NULL;
1850 }
1851 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001852 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 return NULL;
1854 switch (mod->kind) {
1855 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001856 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 compiler_exit_scope(c);
1858 return 0;
1859 }
1860 break;
1861 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001862 if (find_ann(mod->v.Interactive.body)) {
1863 ADDOP(c, SETUP_ANNOTATIONS);
1864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001866 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 break;
1868 case Expression_kind:
1869 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1870 addNone = 0;
1871 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 default:
1873 PyErr_Format(PyExc_SystemError,
1874 "module kind %d should not be possible",
1875 mod->kind);
1876 return 0;
1877 }
1878 co = assemble(c, addNone);
1879 compiler_exit_scope(c);
1880 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001881}
1882
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883/* The test for LOCAL must come before the test for FREE in order to
1884 handle classes where name is both local and free. The local var is
1885 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001886*/
1887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888static int
1889get_ref_type(struct compiler *c, PyObject *name)
1890{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001891 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001892 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001893 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001894 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001895 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001897 _Py_FatalErrorFormat(__func__,
1898 "unknown scope for %.100s in %.100s(%s)\n"
1899 "symbols: %s\nlocals: %s\nglobals: %s",
1900 PyUnicode_AsUTF8(name),
1901 PyUnicode_AsUTF8(c->u->u_name),
1902 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1903 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1904 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1905 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909}
1910
1911static int
1912compiler_lookup_arg(PyObject *dict, PyObject *name)
1913{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001914 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001915 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001917 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001918 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919}
1920
1921static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001922compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001924 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001925 if (qualname == NULL)
1926 qualname = co->co_name;
1927
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001928 if (free) {
1929 for (i = 0; i < free; ++i) {
1930 /* Bypass com_addop_varname because it will generate
1931 LOAD_DEREF but LOAD_CLOSURE is needed.
1932 */
1933 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1934 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001936 /* Special case: If a class contains a method with a
1937 free variable that has the same name as a method,
1938 the name will be considered free *and* local in the
1939 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001940 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 */
1942 reftype = get_ref_type(c, name);
1943 if (reftype == CELL)
1944 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1945 else /* (reftype == FREE) */
1946 arg = compiler_lookup_arg(c->u->u_freevars, name);
1947 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001948 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001949 "lookup %s in %s %d %d\n"
1950 "freevars of %s: %s\n",
1951 PyUnicode_AsUTF8(PyObject_Repr(name)),
1952 PyUnicode_AsUTF8(c->u->u_name),
1953 reftype, arg,
1954 PyUnicode_AsUTF8(co->co_name),
1955 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001956 }
1957 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001959 flags |= 0x08;
1960 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001962 ADDOP_LOAD_CONST(c, (PyObject*)co);
1963 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001964 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966}
1967
1968static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001969compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (!decos)
1974 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1977 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1978 }
1979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980}
1981
1982static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001983compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1984 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001985{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001986 /* Push a dict of keyword-only default values.
1987
1988 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1989 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001990 int i;
1991 PyObject *keys = NULL;
1992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1994 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1995 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1996 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001997 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001998 if (!mangled) {
1999 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002001 if (keys == NULL) {
2002 keys = PyList_New(1);
2003 if (keys == NULL) {
2004 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002005 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002006 }
2007 PyList_SET_ITEM(keys, 0, mangled);
2008 }
2009 else {
2010 int res = PyList_Append(keys, mangled);
2011 Py_DECREF(mangled);
2012 if (res == -1) {
2013 goto error;
2014 }
2015 }
2016 if (!compiler_visit_expr(c, default_)) {
2017 goto error;
2018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 }
2020 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002021 if (keys != NULL) {
2022 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2023 PyObject *keys_tuple = PyList_AsTuple(keys);
2024 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002025 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002026 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002027 assert(default_count > 0);
2028 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002029 }
2030 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002031 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002032 }
2033
2034error:
2035 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002036 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002037}
2038
2039static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002040compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2041{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002042 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002043 return 1;
2044}
2045
2046static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002047compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002048 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002051 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002052 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002053 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002054
2055 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002056 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002057 VISIT(c, annexpr, annotation);
2058 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002060 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002061}
2062
2063static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002064compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002065 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002066{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002067 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 for (i = 0; i < asdl_seq_LEN(args); i++) {
2069 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002070 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 c,
2072 arg->arg,
2073 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002074 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002075 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002077 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002078}
2079
2080static int
2081compiler_visit_annotations(struct compiler *c, arguments_ty args,
2082 expr_ty returns)
2083{
Yurii Karabas73019792020-11-25 12:43:18 +02002084 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002085 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002086
Yurii Karabas73019792020-11-25 12:43:18 +02002087 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 */
2089 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002090 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002091
Yurii Karabas73019792020-11-25 12:43:18 +02002092 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2093 return 0;
2094 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2095 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002096 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002097 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002098 args->vararg->annotation, &annotations_len))
2099 return 0;
2100 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2101 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002102 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002103 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002104 args->kwarg->annotation, &annotations_len))
2105 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (!return_str) {
2108 return_str = PyUnicode_InternFromString("return");
2109 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002110 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 }
Yurii Karabas73019792020-11-25 12:43:18 +02002112 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2113 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 }
2115
Yurii Karabas73019792020-11-25 12:43:18 +02002116 if (annotations_len) {
2117 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002118 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002120
Yurii Karabas73019792020-11-25 12:43:18 +02002121 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002122}
2123
2124static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002125compiler_visit_defaults(struct compiler *c, arguments_ty args)
2126{
2127 VISIT_SEQ(c, expr, args->defaults);
2128 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2129 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130}
2131
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002132static Py_ssize_t
2133compiler_default_arguments(struct compiler *c, arguments_ty args)
2134{
2135 Py_ssize_t funcflags = 0;
2136 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002137 if (!compiler_visit_defaults(c, args))
2138 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002139 funcflags |= 0x01;
2140 }
2141 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002142 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002143 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002144 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002145 return -1;
2146 }
2147 else if (res > 0) {
2148 funcflags |= 0x02;
2149 }
2150 }
2151 return funcflags;
2152}
2153
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002155forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2156{
2157
2158 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2159 compiler_error(c, "cannot assign to __debug__");
2160 return 1;
2161 }
2162 return 0;
2163}
2164
2165static int
2166compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2167{
2168 if (arg != NULL) {
2169 if (forbidden_name(c, arg->arg, Store))
2170 return 0;
2171 }
2172 return 1;
2173}
2174
2175static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002176compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002177{
2178 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002179 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002180 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2181 return 0;
2182 }
2183 }
2184 return 1;
2185}
2186
2187static int
2188compiler_check_debug_args(struct compiler *c, arguments_ty args)
2189{
2190 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2191 return 0;
2192 if (!compiler_check_debug_args_seq(c, args->args))
2193 return 0;
2194 if (!compiler_check_debug_one_arg(c, args->vararg))
2195 return 0;
2196 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2197 return 0;
2198 if (!compiler_check_debug_one_arg(c, args->kwarg))
2199 return 0;
2200 return 1;
2201}
2202
2203static int
Yury Selivanov75445082015-05-11 22:57:16 -04002204compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002207 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002208 arguments_ty args;
2209 expr_ty returns;
2210 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002211 asdl_expr_seq* decos;
2212 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002213 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002214 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002215 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002216 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002217
Yury Selivanov75445082015-05-11 22:57:16 -04002218 if (is_async) {
2219 assert(s->kind == AsyncFunctionDef_kind);
2220
2221 args = s->v.AsyncFunctionDef.args;
2222 returns = s->v.AsyncFunctionDef.returns;
2223 decos = s->v.AsyncFunctionDef.decorator_list;
2224 name = s->v.AsyncFunctionDef.name;
2225 body = s->v.AsyncFunctionDef.body;
2226
2227 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2228 } else {
2229 assert(s->kind == FunctionDef_kind);
2230
2231 args = s->v.FunctionDef.args;
2232 returns = s->v.FunctionDef.returns;
2233 decos = s->v.FunctionDef.decorator_list;
2234 name = s->v.FunctionDef.name;
2235 body = s->v.FunctionDef.body;
2236
2237 scope_type = COMPILER_SCOPE_FUNCTION;
2238 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002240 if (!compiler_check_debug_args(c, args))
2241 return 0;
2242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (!compiler_decorators(c, decos))
2244 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002245
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002246 firstlineno = s->lineno;
2247 if (asdl_seq_LEN(decos)) {
2248 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2249 }
2250
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002251 funcflags = compiler_default_arguments(c, args);
2252 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002254 }
2255
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002256 annotations = compiler_visit_annotations(c, args, returns);
2257 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002258 return 0;
2259 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002260 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002261 funcflags |= 0x04;
2262 }
2263
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002264 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002265 return 0;
2266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267
INADA Naokicb41b272017-02-23 00:31:59 +09002268 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002269 if (c->c_optimize < 2) {
2270 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002271 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002272 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 compiler_exit_scope(c);
2274 return 0;
2275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002278 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002280 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002281 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002282 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002284 qualname = c->u->u_qualname;
2285 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002287 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002288 Py_XDECREF(qualname);
2289 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002291 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002293 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002294 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* decorators */
2298 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2299 ADDOP_I(c, CALL_FUNCTION, 1);
2300 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301
Yury Selivanov75445082015-05-11 22:57:16 -04002302 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303}
2304
2305static int
2306compiler_class(struct compiler *c, stmt_ty s)
2307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 PyCodeObject *co;
2309 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002310 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002311 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 if (!compiler_decorators(c, decos))
2314 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002315
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002316 firstlineno = s->lineno;
2317 if (asdl_seq_LEN(decos)) {
2318 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2319 }
2320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* ultimately generate code for:
2322 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2323 where:
2324 <func> is a function/closure created from the class body;
2325 it has a single argument (__locals__) where the dict
2326 (or MutableSequence) representing the locals is passed
2327 <name> is the class name
2328 <bases> is the positional arguments and *varargs argument
2329 <keywords> is the keyword arguments and **kwds argument
2330 This borrows from compiler_call.
2331 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002334 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002335 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 return 0;
2337 /* this block represents what we do in the new scope */
2338 {
2339 /* use the class name for name mangling */
2340 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002341 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* load (global) __name__ ... */
2343 str = PyUnicode_InternFromString("__name__");
2344 if (!str || !compiler_nameop(c, str, Load)) {
2345 Py_XDECREF(str);
2346 compiler_exit_scope(c);
2347 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 Py_DECREF(str);
2350 /* ... and store it as __module__ */
2351 str = PyUnicode_InternFromString("__module__");
2352 if (!str || !compiler_nameop(c, str, Store)) {
2353 Py_XDECREF(str);
2354 compiler_exit_scope(c);
2355 return 0;
2356 }
2357 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002358 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002359 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002360 str = PyUnicode_InternFromString("__qualname__");
2361 if (!str || !compiler_nameop(c, str, Store)) {
2362 Py_XDECREF(str);
2363 compiler_exit_scope(c);
2364 return 0;
2365 }
2366 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002368 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 compiler_exit_scope(c);
2370 return 0;
2371 }
Mark Shannone56d54e2021-01-15 13:52:00 +00002372 /* The following code is artificial */
2373 c->u->u_lineno = -1;
Nick Coghlan19d24672016-12-05 16:47:55 +10002374 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002375 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002376 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002377 str = PyUnicode_InternFromString("__class__");
2378 if (str == NULL) {
2379 compiler_exit_scope(c);
2380 return 0;
2381 }
2382 i = compiler_lookup_arg(c->u->u_cellvars, str);
2383 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002384 if (i < 0) {
2385 compiler_exit_scope(c);
2386 return 0;
2387 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002388 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002391 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002392 str = PyUnicode_InternFromString("__classcell__");
2393 if (!str || !compiler_nameop(c, str, Store)) {
2394 Py_XDECREF(str);
2395 compiler_exit_scope(c);
2396 return 0;
2397 }
2398 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002400 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002401 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002402 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002403 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002404 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002405 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 /* create the code object */
2407 co = assemble(c, 1);
2408 }
2409 /* leave the new scope */
2410 compiler_exit_scope(c);
2411 if (co == NULL)
2412 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 /* 2. load the 'build_class' function */
2415 ADDOP(c, LOAD_BUILD_CLASS);
2416
2417 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002418 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 Py_DECREF(co);
2420
2421 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002422 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423
2424 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002425 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 return 0;
2427
2428 /* 6. apply decorators */
2429 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2430 ADDOP_I(c, CALL_FUNCTION, 1);
2431 }
2432
2433 /* 7. store into <name> */
2434 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2435 return 0;
2436 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002437}
2438
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002439/* Return 0 if the expression is a constant value except named singletons.
2440 Return 1 otherwise. */
2441static int
2442check_is_arg(expr_ty e)
2443{
2444 if (e->kind != Constant_kind) {
2445 return 1;
2446 }
2447 PyObject *value = e->v.Constant.value;
2448 return (value == Py_None
2449 || value == Py_False
2450 || value == Py_True
2451 || value == Py_Ellipsis);
2452}
2453
2454/* Check operands of identity chacks ("is" and "is not").
2455 Emit a warning if any operand is a constant except named singletons.
2456 Return 0 on error.
2457 */
2458static int
2459check_compare(struct compiler *c, expr_ty e)
2460{
2461 Py_ssize_t i, n;
2462 int left = check_is_arg(e->v.Compare.left);
2463 n = asdl_seq_LEN(e->v.Compare.ops);
2464 for (i = 0; i < n; i++) {
2465 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2466 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2467 if (op == Is || op == IsNot) {
2468 if (!right || !left) {
2469 const char *msg = (op == Is)
2470 ? "\"is\" with a literal. Did you mean \"==\"?"
2471 : "\"is not\" with a literal. Did you mean \"!=\"?";
2472 return compiler_warn(c, msg);
2473 }
2474 }
2475 left = right;
2476 }
2477 return 1;
2478}
2479
Mark Shannon9af0e472020-01-14 10:12:45 +00002480static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002481{
Mark Shannon9af0e472020-01-14 10:12:45 +00002482 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483 switch (op) {
2484 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002485 cmp = Py_EQ;
2486 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002487 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002488 cmp = Py_NE;
2489 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002490 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002491 cmp = Py_LT;
2492 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002493 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002494 cmp = Py_LE;
2495 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002496 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002497 cmp = Py_GT;
2498 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002499 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002500 cmp = Py_GE;
2501 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002502 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002503 ADDOP_I(c, IS_OP, 0);
2504 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002505 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002506 ADDOP_I(c, IS_OP, 1);
2507 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002508 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002509 ADDOP_I(c, CONTAINS_OP, 0);
2510 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002511 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002512 ADDOP_I(c, CONTAINS_OP, 1);
2513 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002514 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002515 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002516 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002517 ADDOP_I(c, COMPARE_OP, cmp);
2518 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002519}
2520
Mark Shannon9af0e472020-01-14 10:12:45 +00002521
2522
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002523static int
2524compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2525{
2526 switch (e->kind) {
2527 case UnaryOp_kind:
2528 if (e->v.UnaryOp.op == Not)
2529 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2530 /* fallback to general implementation */
2531 break;
2532 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002533 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002534 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2535 assert(n >= 0);
2536 int cond2 = e->v.BoolOp.op == Or;
2537 basicblock *next2 = next;
2538 if (!cond2 != !cond) {
2539 next2 = compiler_new_block(c);
2540 if (next2 == NULL)
2541 return 0;
2542 }
2543 for (i = 0; i < n; ++i) {
2544 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2545 return 0;
2546 }
2547 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2548 return 0;
2549 if (next2 != next)
2550 compiler_use_next_block(c, next2);
2551 return 1;
2552 }
2553 case IfExp_kind: {
2554 basicblock *end, *next2;
2555 end = compiler_new_block(c);
2556 if (end == NULL)
2557 return 0;
2558 next2 = compiler_new_block(c);
2559 if (next2 == NULL)
2560 return 0;
2561 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2562 return 0;
2563 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2564 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002565 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002566 compiler_use_next_block(c, next2);
2567 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2568 return 0;
2569 compiler_use_next_block(c, end);
2570 return 1;
2571 }
2572 case Compare_kind: {
2573 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2574 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002575 if (!check_compare(c, e)) {
2576 return 0;
2577 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002578 basicblock *cleanup = compiler_new_block(c);
2579 if (cleanup == NULL)
2580 return 0;
2581 VISIT(c, expr, e->v.Compare.left);
2582 for (i = 0; i < n; i++) {
2583 VISIT(c, expr,
2584 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2585 ADDOP(c, DUP_TOP);
2586 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002587 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002588 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002589 NEXT_BLOCK(c);
2590 }
2591 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002592 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002593 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002594 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002595 basicblock *end = compiler_new_block(c);
2596 if (end == NULL)
2597 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002598 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002599 compiler_use_next_block(c, cleanup);
2600 ADDOP(c, POP_TOP);
2601 if (!cond) {
Mark Shannon127dde52021-01-04 18:06:55 +00002602 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002603 }
2604 compiler_use_next_block(c, end);
2605 return 1;
2606 }
2607 /* fallback to general implementation */
2608 break;
2609 }
2610 default:
2611 /* fallback to general implementation */
2612 break;
2613 }
2614
2615 /* general implementation */
2616 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002617 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002618 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002619 return 1;
2620}
2621
2622static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002623compiler_ifexp(struct compiler *c, expr_ty e)
2624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 basicblock *end, *next;
2626
2627 assert(e->kind == IfExp_kind);
2628 end = compiler_new_block(c);
2629 if (end == NULL)
2630 return 0;
2631 next = compiler_new_block(c);
2632 if (next == NULL)
2633 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002634 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2635 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon127dde52021-01-04 18:06:55 +00002637 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 compiler_use_next_block(c, next);
2639 VISIT(c, expr, e->v.IfExp.orelse);
2640 compiler_use_next_block(c, end);
2641 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002642}
2643
2644static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645compiler_lambda(struct compiler *c, expr_ty e)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002648 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002650 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 arguments_ty args = e->v.Lambda.args;
2652 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002653
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002654 if (!compiler_check_debug_args(c, args))
2655 return 0;
2656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (!name) {
2658 name = PyUnicode_InternFromString("<lambda>");
2659 if (!name)
2660 return 0;
2661 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002662
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002663 funcflags = compiler_default_arguments(c, args);
2664 if (funcflags == -1) {
2665 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002667
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002668 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002669 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 /* Make None the first constant, so the lambda can't have a
2673 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002674 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002678 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2680 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2681 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002682 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 }
2684 else {
2685 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002686 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002688 qualname = c->u->u_qualname;
2689 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002691 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002694 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002695 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 Py_DECREF(co);
2697
2698 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002699}
2700
2701static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002702compiler_if(struct compiler *c, stmt_ty s)
2703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 assert(s->kind == If_kind);
2706 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002707 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002709 }
2710 if (asdl_seq_LEN(s->v.If.orelse)) {
2711 next = compiler_new_block(c);
2712 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002713 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002714 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002715 }
2716 else {
2717 next = end;
2718 }
2719 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2720 return 0;
2721 }
2722 VISIT_SEQ(c, stmt, s->v.If.body);
2723 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon127dde52021-01-04 18:06:55 +00002724 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Mark Shannon8473cf82020-12-15 11:07:50 +00002725 compiler_use_next_block(c, next);
2726 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 }
2728 compiler_use_next_block(c, end);
2729 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730}
2731
2732static int
2733compiler_for(struct compiler *c, stmt_ty s)
2734{
Mark Shannon5977a792020-12-02 13:31:40 +00002735 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002738 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 cleanup = compiler_new_block(c);
2740 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002741 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002743 }
2744 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002746 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 VISIT(c, expr, s->v.For.iter);
2748 ADDOP(c, GET_ITER);
2749 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002750 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002751 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 VISIT(c, expr, s->v.For.target);
2753 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002754 /* Mark jump as artificial */
2755 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002756 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002758
2759 compiler_pop_fblock(c, FOR_LOOP, start);
2760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 VISIT_SEQ(c, stmt, s->v.For.orelse);
2762 compiler_use_next_block(c, end);
2763 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002764}
2765
Yury Selivanov75445082015-05-11 22:57:16 -04002766
2767static int
2768compiler_async_for(struct compiler *c, stmt_ty s)
2769{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002770 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002771 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002772 c->u->u_ste->ste_coroutine = 1;
2773 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002774 return compiler_error(c, "'async for' outside async function");
2775 }
2776
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002777 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002778 except = compiler_new_block(c);
2779 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002780
Mark Shannonfee55262019-11-21 09:11:43 +00002781 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002782 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002783 }
Yury Selivanov75445082015-05-11 22:57:16 -04002784 VISIT(c, expr, s->v.AsyncFor.iter);
2785 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002786
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002787 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002788 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002789 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002790 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002791 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002792 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002793 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002794 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002795 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002796 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002797
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002798 /* Success block for __anext__ */
2799 VISIT(c, expr, s->v.AsyncFor.target);
2800 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002801 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002802
2803 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002804
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002805 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002806 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002807
2808 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002809 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002810
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002811 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002812 VISIT_SEQ(c, stmt, s->v.For.orelse);
2813
2814 compiler_use_next_block(c, end);
2815
2816 return 1;
2817}
2818
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002819static int
2820compiler_while(struct compiler *c, stmt_ty s)
2821{
Mark Shannon266b4622020-11-17 19:30:14 +00002822 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002824 body = compiler_new_block(c);
2825 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002827 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002831 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002834 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2835 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002836 }
2837
2838 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002840 SET_LOC(c, s);
2841 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2842 return 0;
2843 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002845 compiler_pop_fblock(c, WHILE_LOOP, loop);
2846
Mark Shannon266b4622020-11-17 19:30:14 +00002847 compiler_use_next_block(c, anchor);
2848 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002850 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002854}
2855
2856static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002857compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002859 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002860 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002861 if (c->u->u_ste->ste_type != FunctionBlock)
2862 return compiler_error(c, "'return' outside function");
2863 if (s->v.Return.value != NULL &&
2864 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2865 {
2866 return compiler_error(
2867 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002869 if (preserve_tos) {
2870 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002871 } else {
2872 /* Emit instruction with line number for expression */
2873 if (s->v.Return.value != NULL) {
2874 SET_LOC(c, s->v.Return.value);
2875 ADDOP(c, NOP);
2876 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002877 }
Mark Shannonfee55262019-11-21 09:11:43 +00002878 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2879 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002880 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002881 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002882 }
2883 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00002884 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002885 }
2886 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002887 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890}
2891
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002892static int
2893compiler_break(struct compiler *c)
2894{
Mark Shannonfee55262019-11-21 09:11:43 +00002895 struct fblockinfo *loop = NULL;
2896 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2897 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002898 }
Mark Shannonfee55262019-11-21 09:11:43 +00002899 if (loop == NULL) {
2900 return compiler_error(c, "'break' outside loop");
2901 }
2902 if (!compiler_unwind_fblock(c, loop, 0)) {
2903 return 0;
2904 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002905 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002906 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002907 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002908}
2909
2910static int
2911compiler_continue(struct compiler *c)
2912{
Mark Shannonfee55262019-11-21 09:11:43 +00002913 struct fblockinfo *loop = NULL;
2914 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2915 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002916 }
Mark Shannonfee55262019-11-21 09:11:43 +00002917 if (loop == NULL) {
2918 return compiler_error(c, "'continue' not properly in loop");
2919 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002920 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002921 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002922 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002923}
2924
2925
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002926/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927
2928 SETUP_FINALLY L
2929 <code for body>
2930 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002931 <code for finalbody>
2932 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002933 L:
2934 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002935 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002936
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002937 The special instructions use the block stack. Each block
2938 stack entry contains the instruction that created it (here
2939 SETUP_FINALLY), the level of the value stack at the time the
2940 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002943 Pushes the current value stack level and the label
2944 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002946 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002947
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002948 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002949 when a SETUP_FINALLY entry is found, the raised and the caught
2950 exceptions are pushed onto the value stack (and the exception
2951 condition is cleared), and the interpreter jumps to the label
2952 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953*/
2954
2955static int
2956compiler_try_finally(struct compiler *c, stmt_ty s)
2957{
Mark Shannonfee55262019-11-21 09:11:43 +00002958 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 body = compiler_new_block(c);
2961 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002962 exit = compiler_new_block(c);
2963 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002965
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002966 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002967 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002969 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002971 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2972 if (!compiler_try_except(c, s))
2973 return 0;
2974 }
2975 else {
2976 VISIT_SEQ(c, stmt, s->v.Try.body);
2977 }
Mark Shannon3bd60352021-01-13 12:05:43 +00002978 ADDOP_NOLINE(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002979 compiler_pop_fblock(c, FINALLY_TRY, body);
2980 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon127dde52021-01-04 18:06:55 +00002981 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00002982 /* `finally` block */
2983 compiler_use_next_block(c, end);
2984 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2985 return 0;
2986 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2987 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00002988 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00002989 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991}
2992
2993/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002994 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995 (The contents of the value stack is shown in [], with the top
2996 at the right; 'tb' is trace-back info, 'val' the exception's
2997 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998
2999 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003000 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 [] <code for S>
3002 [] POP_BLOCK
3003 [] JUMP_FORWARD L0
3004
3005 [tb, val, exc] L1: DUP )
3006 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003007 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 [tb, val, exc] POP
3009 [tb, val] <assign to V1> (or POP if no V1)
3010 [tb] POP
3011 [] <code for S1>
3012 JUMP_FORWARD L0
3013
3014 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015 .............................etc.......................
3016
Mark Shannonfee55262019-11-21 09:11:43 +00003017 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018
3019 [] L0: <next statement>
3020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 Of course, parts are not generated if Vi or Ei is not present.
3022*/
3023static int
3024compiler_try_except(struct compiler *c, stmt_ty s)
3025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003027 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 body = compiler_new_block(c);
3030 except = compiler_new_block(c);
3031 orelse = compiler_new_block(c);
3032 end = compiler_new_block(c);
3033 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3034 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003035 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003037 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003039 VISIT_SEQ(c, stmt, s->v.Try.body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003040 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon3bd60352021-01-13 12:05:43 +00003041 ADDOP_NOLINE(c, POP_BLOCK);
3042 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003043 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003045 /* Runtime will push a block here, so we need to account for that */
3046 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3047 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 for (i = 0; i < n; i++) {
3049 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003050 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 if (!handler->v.ExceptHandler.type && i < n-1)
3052 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003053 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 except = compiler_new_block(c);
3055 if (except == NULL)
3056 return 0;
3057 if (handler->v.ExceptHandler.type) {
3058 ADDOP(c, DUP_TOP);
3059 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003060 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003061 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 }
3063 ADDOP(c, POP_TOP);
3064 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003065 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003066
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003067 cleanup_end = compiler_new_block(c);
3068 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003069 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003070 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003071 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003072
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003073 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3074 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003076 /*
3077 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003078 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003080 try:
3081 # body
3082 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003083 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003084 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003088 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003090 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003091 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003093 /* second # body */
3094 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003095 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003096 ADDOP(c, POP_BLOCK);
3097 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003098 /* name = None; del name; # Mark as artificial */
3099 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003100 ADDOP_LOAD_CONST(c, Py_None);
3101 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3102 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003103 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104
Mark Shannonfee55262019-11-21 09:11:43 +00003105 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003106 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107
Mark Shannon877df852020-11-12 09:43:29 +00003108 /* name = None; del name; # Mark as artificial */
3109 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003110 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003112 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113
Mark Shannonbf353f32020-12-17 13:55:28 +00003114 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 }
3116 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003117 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003120 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003121 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122
Guido van Rossumb940e112007-01-10 16:19:56 +00003123 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003124 ADDOP(c, POP_TOP);
3125 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003126 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003127 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003129 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannon127dde52021-01-04 18:06:55 +00003130 /* name = None; del name; # Mark as artificial */
3131 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003132 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003133 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 compiler_use_next_block(c, except);
3136 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003137 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003138 /* Mark as artificial */
3139 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003140 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003142 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 compiler_use_next_block(c, end);
3144 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003145}
3146
3147static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003148compiler_try(struct compiler *c, stmt_ty s) {
3149 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3150 return compiler_try_finally(c, s);
3151 else
3152 return compiler_try_except(c, s);
3153}
3154
3155
3156static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003157compiler_import_as(struct compiler *c, identifier name, identifier asname)
3158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003159 /* The IMPORT_NAME opcode was already generated. This function
3160 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003163 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003165 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3166 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003167 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003168 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003169 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003171 while (1) {
3172 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003173 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003174 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003175 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003176 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003177 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003178 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003179 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003180 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003181 if (dot == -1) {
3182 break;
3183 }
3184 ADDOP(c, ROT_TWO);
3185 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003187 if (!compiler_nameop(c, asname, Store)) {
3188 return 0;
3189 }
3190 ADDOP(c, POP_TOP);
3191 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 }
3193 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194}
3195
3196static int
3197compiler_import(struct compiler *c, stmt_ty s)
3198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 /* The Import node stores a module name like a.b.c as a single
3200 string. This is convenient for all cases except
3201 import a.b.c as d
3202 where we need to parse that string to extract the individual
3203 module names.
3204 XXX Perhaps change the representation to make this case simpler?
3205 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003206 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003207
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003208 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 for (i = 0; i < n; i++) {
3210 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3211 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003212
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003213 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003214 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 if (alias->asname) {
3218 r = compiler_import_as(c, alias->name, alias->asname);
3219 if (!r)
3220 return r;
3221 }
3222 else {
3223 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003224 Py_ssize_t dot = PyUnicode_FindChar(
3225 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003226 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003227 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003228 if (tmp == NULL)
3229 return 0;
3230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003232 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 Py_DECREF(tmp);
3234 }
3235 if (!r)
3236 return r;
3237 }
3238 }
3239 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240}
3241
3242static int
3243compiler_from_import(struct compiler *c, stmt_ty s)
3244{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003245 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003246 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003249 if (!empty_string) {
3250 empty_string = PyUnicode_FromString("");
3251 if (!empty_string)
3252 return 0;
3253 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003255 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003256
3257 names = PyTuple_New(n);
3258 if (!names)
3259 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 /* build up the names */
3262 for (i = 0; i < n; i++) {
3263 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3264 Py_INCREF(alias->name);
3265 PyTuple_SET_ITEM(names, i, alias->name);
3266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003269 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 Py_DECREF(names);
3271 return compiler_error(c, "from __future__ imports must occur "
3272 "at the beginning of the file");
3273 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003274 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 if (s->v.ImportFrom.module) {
3277 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3278 }
3279 else {
3280 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3281 }
3282 for (i = 0; i < n; i++) {
3283 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3284 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003286 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 assert(n == 1);
3288 ADDOP(c, IMPORT_STAR);
3289 return 1;
3290 }
3291
3292 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3293 store_name = alias->name;
3294 if (alias->asname)
3295 store_name = alias->asname;
3296
3297 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 return 0;
3299 }
3300 }
3301 /* remove imported module */
3302 ADDOP(c, POP_TOP);
3303 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304}
3305
3306static int
3307compiler_assert(struct compiler *c, stmt_ty s)
3308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003309 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003310
Georg Brandl8334fd92010-12-04 10:26:46 +00003311 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003312 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003314 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3315 {
3316 if (!compiler_warn(c, "assertion is always true, "
3317 "perhaps remove parentheses?"))
3318 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003319 return 0;
3320 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003321 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 end = compiler_new_block(c);
3323 if (end == NULL)
3324 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003325 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3326 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003327 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003328 if (s->v.Assert.msg) {
3329 VISIT(c, expr, s->v.Assert.msg);
3330 ADDOP_I(c, CALL_FUNCTION, 1);
3331 }
3332 ADDOP_I(c, RAISE_VARARGS, 1);
3333 compiler_use_next_block(c, end);
3334 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003335}
3336
3337static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003338compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3339{
3340 if (c->c_interactive && c->c_nestlevel <= 1) {
3341 VISIT(c, expr, value);
3342 ADDOP(c, PRINT_EXPR);
3343 return 1;
3344 }
3345
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003346 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003347 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003348 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003349 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003350 }
3351
3352 VISIT(c, expr, value);
3353 ADDOP(c, POP_TOP);
3354 return 1;
3355}
3356
3357static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003358compiler_visit_stmt(struct compiler *c, stmt_ty s)
3359{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003360 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003363 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003365 switch (s->kind) {
3366 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003367 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003368 case ClassDef_kind:
3369 return compiler_class(c, s);
3370 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003371 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 case Delete_kind:
3373 VISIT_SEQ(c, expr, s->v.Delete.targets)
3374 break;
3375 case Assign_kind:
3376 n = asdl_seq_LEN(s->v.Assign.targets);
3377 VISIT(c, expr, s->v.Assign.value);
3378 for (i = 0; i < n; i++) {
3379 if (i < n - 1)
3380 ADDOP(c, DUP_TOP);
3381 VISIT(c, expr,
3382 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3383 }
3384 break;
3385 case AugAssign_kind:
3386 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003387 case AnnAssign_kind:
3388 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 case For_kind:
3390 return compiler_for(c, s);
3391 case While_kind:
3392 return compiler_while(c, s);
3393 case If_kind:
3394 return compiler_if(c, s);
3395 case Raise_kind:
3396 n = 0;
3397 if (s->v.Raise.exc) {
3398 VISIT(c, expr, s->v.Raise.exc);
3399 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003400 if (s->v.Raise.cause) {
3401 VISIT(c, expr, s->v.Raise.cause);
3402 n++;
3403 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003405 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003406 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003407 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003408 case Try_kind:
3409 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003410 case Assert_kind:
3411 return compiler_assert(c, s);
3412 case Import_kind:
3413 return compiler_import(c, s);
3414 case ImportFrom_kind:
3415 return compiler_from_import(c, s);
3416 case Global_kind:
3417 case Nonlocal_kind:
3418 break;
3419 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003420 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003422 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003423 break;
3424 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003425 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 case Continue_kind:
3427 return compiler_continue(c);
3428 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003429 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003430 case AsyncFunctionDef_kind:
3431 return compiler_function(c, s, 1);
3432 case AsyncWith_kind:
3433 return compiler_async_with(c, s, 0);
3434 case AsyncFor_kind:
3435 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 }
Yury Selivanov75445082015-05-11 22:57:16 -04003437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003439}
3440
3441static int
3442unaryop(unaryop_ty op)
3443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 switch (op) {
3445 case Invert:
3446 return UNARY_INVERT;
3447 case Not:
3448 return UNARY_NOT;
3449 case UAdd:
3450 return UNARY_POSITIVE;
3451 case USub:
3452 return UNARY_NEGATIVE;
3453 default:
3454 PyErr_Format(PyExc_SystemError,
3455 "unary op %d should not be possible", op);
3456 return 0;
3457 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003458}
3459
3460static int
Andy Lester76d58772020-03-10 21:18:12 -05003461binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003463 switch (op) {
3464 case Add:
3465 return BINARY_ADD;
3466 case Sub:
3467 return BINARY_SUBTRACT;
3468 case Mult:
3469 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003470 case MatMult:
3471 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 case Div:
3473 return BINARY_TRUE_DIVIDE;
3474 case Mod:
3475 return BINARY_MODULO;
3476 case Pow:
3477 return BINARY_POWER;
3478 case LShift:
3479 return BINARY_LSHIFT;
3480 case RShift:
3481 return BINARY_RSHIFT;
3482 case BitOr:
3483 return BINARY_OR;
3484 case BitXor:
3485 return BINARY_XOR;
3486 case BitAnd:
3487 return BINARY_AND;
3488 case FloorDiv:
3489 return BINARY_FLOOR_DIVIDE;
3490 default:
3491 PyErr_Format(PyExc_SystemError,
3492 "binary op %d should not be possible", op);
3493 return 0;
3494 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003495}
3496
3497static int
Andy Lester76d58772020-03-10 21:18:12 -05003498inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 switch (op) {
3501 case Add:
3502 return INPLACE_ADD;
3503 case Sub:
3504 return INPLACE_SUBTRACT;
3505 case Mult:
3506 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003507 case MatMult:
3508 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003509 case Div:
3510 return INPLACE_TRUE_DIVIDE;
3511 case Mod:
3512 return INPLACE_MODULO;
3513 case Pow:
3514 return INPLACE_POWER;
3515 case LShift:
3516 return INPLACE_LSHIFT;
3517 case RShift:
3518 return INPLACE_RSHIFT;
3519 case BitOr:
3520 return INPLACE_OR;
3521 case BitXor:
3522 return INPLACE_XOR;
3523 case BitAnd:
3524 return INPLACE_AND;
3525 case FloorDiv:
3526 return INPLACE_FLOOR_DIVIDE;
3527 default:
3528 PyErr_Format(PyExc_SystemError,
3529 "inplace binary op %d should not be possible", op);
3530 return 0;
3531 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003532}
3533
3534static int
3535compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3536{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003537 int op, scope;
3538 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003541 PyObject *dict = c->u->u_names;
3542 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003543
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003544 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3545 !_PyUnicode_EqualToASCIIString(name, "True") &&
3546 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003547
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003548 if (forbidden_name(c, name, ctx))
3549 return 0;
3550
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003551 mangled = _Py_Mangle(c->u->u_private, name);
3552 if (!mangled)
3553 return 0;
3554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 op = 0;
3556 optype = OP_NAME;
3557 scope = PyST_GetScope(c->u->u_ste, mangled);
3558 switch (scope) {
3559 case FREE:
3560 dict = c->u->u_freevars;
3561 optype = OP_DEREF;
3562 break;
3563 case CELL:
3564 dict = c->u->u_cellvars;
3565 optype = OP_DEREF;
3566 break;
3567 case LOCAL:
3568 if (c->u->u_ste->ste_type == FunctionBlock)
3569 optype = OP_FAST;
3570 break;
3571 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003572 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003573 optype = OP_GLOBAL;
3574 break;
3575 case GLOBAL_EXPLICIT:
3576 optype = OP_GLOBAL;
3577 break;
3578 default:
3579 /* scope can be 0 */
3580 break;
3581 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003584 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003586 switch (optype) {
3587 case OP_DEREF:
3588 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003589 case Load:
3590 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3591 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003592 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003593 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 }
3595 break;
3596 case OP_FAST:
3597 switch (ctx) {
3598 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003599 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003600 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003602 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 return 1;
3604 case OP_GLOBAL:
3605 switch (ctx) {
3606 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003607 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003608 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 }
3610 break;
3611 case OP_NAME:
3612 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003613 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003614 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003615 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 }
3617 break;
3618 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003621 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 Py_DECREF(mangled);
3623 if (arg < 0)
3624 return 0;
3625 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003626}
3627
3628static int
3629compiler_boolop(struct compiler *c, expr_ty e)
3630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003632 int jumpi;
3633 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003634 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 assert(e->kind == BoolOp_kind);
3637 if (e->v.BoolOp.op == And)
3638 jumpi = JUMP_IF_FALSE_OR_POP;
3639 else
3640 jumpi = JUMP_IF_TRUE_OR_POP;
3641 end = compiler_new_block(c);
3642 if (end == NULL)
3643 return 0;
3644 s = e->v.BoolOp.values;
3645 n = asdl_seq_LEN(s) - 1;
3646 assert(n >= 0);
3647 for (i = 0; i < n; ++i) {
3648 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003649 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003650 basicblock *next = compiler_new_block(c);
3651 if (next == NULL) {
3652 return 0;
3653 }
3654 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003655 }
3656 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3657 compiler_use_next_block(c, end);
3658 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003659}
3660
3661static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003662starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003663 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003664{
3665 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003666 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003667 if (n > 2 && are_all_items_const(elts, 0, n)) {
3668 PyObject *folded = PyTuple_New(n);
3669 if (folded == NULL) {
3670 return 0;
3671 }
3672 PyObject *val;
3673 for (i = 0; i < n; i++) {
3674 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3675 Py_INCREF(val);
3676 PyTuple_SET_ITEM(folded, i, val);
3677 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003678 if (tuple) {
3679 ADDOP_LOAD_CONST_NEW(c, folded);
3680 } else {
3681 if (add == SET_ADD) {
3682 Py_SETREF(folded, PyFrozenSet_New(folded));
3683 if (folded == NULL) {
3684 return 0;
3685 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003686 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003687 ADDOP_I(c, build, pushed);
3688 ADDOP_LOAD_CONST_NEW(c, folded);
3689 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003690 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003691 return 1;
3692 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003693
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003694 for (i = 0; i < n; i++) {
3695 expr_ty elt = asdl_seq_GET(elts, i);
3696 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003697 seen_star = 1;
3698 }
3699 }
3700 if (seen_star) {
3701 seen_star = 0;
3702 for (i = 0; i < n; i++) {
3703 expr_ty elt = asdl_seq_GET(elts, i);
3704 if (elt->kind == Starred_kind) {
3705 if (seen_star == 0) {
3706 ADDOP_I(c, build, i+pushed);
3707 seen_star = 1;
3708 }
3709 VISIT(c, expr, elt->v.Starred.value);
3710 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003711 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003712 else {
3713 VISIT(c, expr, elt);
3714 if (seen_star) {
3715 ADDOP_I(c, add, 1);
3716 }
3717 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003718 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003719 assert(seen_star);
3720 if (tuple) {
3721 ADDOP(c, LIST_TO_TUPLE);
3722 }
3723 }
3724 else {
3725 for (i = 0; i < n; i++) {
3726 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003727 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003728 }
3729 if (tuple) {
3730 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3731 } else {
3732 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003733 }
3734 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003735 return 1;
3736}
3737
3738static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003739assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003740{
3741 Py_ssize_t n = asdl_seq_LEN(elts);
3742 Py_ssize_t i;
3743 int seen_star = 0;
3744 for (i = 0; i < n; i++) {
3745 expr_ty elt = asdl_seq_GET(elts, i);
3746 if (elt->kind == Starred_kind && !seen_star) {
3747 if ((i >= (1 << 8)) ||
3748 (n-i-1 >= (INT_MAX >> 8)))
3749 return compiler_error(c,
3750 "too many expressions in "
3751 "star-unpacking assignment");
3752 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3753 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003754 }
3755 else if (elt->kind == Starred_kind) {
3756 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003757 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003758 }
3759 }
3760 if (!seen_star) {
3761 ADDOP_I(c, UNPACK_SEQUENCE, n);
3762 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003763 for (i = 0; i < n; i++) {
3764 expr_ty elt = asdl_seq_GET(elts, i);
3765 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3766 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003767 return 1;
3768}
3769
3770static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003771compiler_list(struct compiler *c, expr_ty e)
3772{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003773 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003774 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003775 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003776 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003777 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003778 return starunpack_helper(c, elts, 0, BUILD_LIST,
3779 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003781 else
3782 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003783 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003784}
3785
3786static int
3787compiler_tuple(struct compiler *c, expr_ty e)
3788{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003789 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003790 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003791 return assignment_helper(c, elts);
3792 }
3793 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003794 return starunpack_helper(c, elts, 0, BUILD_LIST,
3795 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003796 }
3797 else
3798 VISIT_SEQ(c, expr, elts);
3799 return 1;
3800}
3801
3802static int
3803compiler_set(struct compiler *c, expr_ty e)
3804{
Mark Shannon13bc1392020-01-23 09:25:17 +00003805 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3806 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003807}
3808
3809static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003810are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003811{
3812 Py_ssize_t i;
3813 for (i = begin; i < end; i++) {
3814 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003815 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003816 return 0;
3817 }
3818 return 1;
3819}
3820
3821static int
3822compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3823{
3824 Py_ssize_t i, n = end - begin;
3825 PyObject *keys, *key;
3826 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3827 for (i = begin; i < end; i++) {
3828 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3829 }
3830 keys = PyTuple_New(n);
3831 if (keys == NULL) {
3832 return 0;
3833 }
3834 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003835 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003836 Py_INCREF(key);
3837 PyTuple_SET_ITEM(keys, i - begin, key);
3838 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003839 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003840 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3841 }
3842 else {
3843 for (i = begin; i < end; i++) {
3844 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3845 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3846 }
3847 ADDOP_I(c, BUILD_MAP, n);
3848 }
3849 return 1;
3850}
3851
3852static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003853compiler_dict(struct compiler *c, expr_ty e)
3854{
Victor Stinner976bb402016-03-23 11:36:19 +01003855 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003856 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003857 int is_unpacking = 0;
3858 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003859 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003860 elements = 0;
3861 for (i = 0; i < n; i++) {
3862 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003863 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003864 if (elements) {
3865 if (!compiler_subdict(c, e, i - elements, i)) {
3866 return 0;
3867 }
3868 if (have_dict) {
3869 ADDOP_I(c, DICT_UPDATE, 1);
3870 }
3871 have_dict = 1;
3872 elements = 0;
3873 }
3874 if (have_dict == 0) {
3875 ADDOP_I(c, BUILD_MAP, 0);
3876 have_dict = 1;
3877 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003878 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003879 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003880 }
3881 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003882 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003883 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003884 return 0;
3885 }
3886 if (have_dict) {
3887 ADDOP_I(c, DICT_UPDATE, 1);
3888 }
3889 have_dict = 1;
3890 elements = 0;
3891 }
3892 else {
3893 elements++;
3894 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003895 }
3896 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003897 if (elements) {
3898 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003899 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003900 }
3901 if (have_dict) {
3902 ADDOP_I(c, DICT_UPDATE, 1);
3903 }
3904 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003905 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003906 if (!have_dict) {
3907 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003908 }
3909 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910}
3911
3912static int
3913compiler_compare(struct compiler *c, expr_ty e)
3914{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003915 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003916
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003917 if (!check_compare(c, e)) {
3918 return 0;
3919 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003920 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003921 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3922 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3923 if (n == 0) {
3924 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003925 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003926 }
3927 else {
3928 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003929 if (cleanup == NULL)
3930 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003931 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003932 VISIT(c, expr,
3933 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003934 ADDOP(c, DUP_TOP);
3935 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003936 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003937 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003938 NEXT_BLOCK(c);
3939 }
3940 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003941 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003942 basicblock *end = compiler_new_block(c);
3943 if (end == NULL)
3944 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00003945 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 compiler_use_next_block(c, cleanup);
3947 ADDOP(c, ROT_TWO);
3948 ADDOP(c, POP_TOP);
3949 compiler_use_next_block(c, end);
3950 }
3951 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003952}
3953
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003954static PyTypeObject *
3955infer_type(expr_ty e)
3956{
3957 switch (e->kind) {
3958 case Tuple_kind:
3959 return &PyTuple_Type;
3960 case List_kind:
3961 case ListComp_kind:
3962 return &PyList_Type;
3963 case Dict_kind:
3964 case DictComp_kind:
3965 return &PyDict_Type;
3966 case Set_kind:
3967 case SetComp_kind:
3968 return &PySet_Type;
3969 case GeneratorExp_kind:
3970 return &PyGen_Type;
3971 case Lambda_kind:
3972 return &PyFunction_Type;
3973 case JoinedStr_kind:
3974 case FormattedValue_kind:
3975 return &PyUnicode_Type;
3976 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003977 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003978 default:
3979 return NULL;
3980 }
3981}
3982
3983static int
3984check_caller(struct compiler *c, expr_ty e)
3985{
3986 switch (e->kind) {
3987 case Constant_kind:
3988 case Tuple_kind:
3989 case List_kind:
3990 case ListComp_kind:
3991 case Dict_kind:
3992 case DictComp_kind:
3993 case Set_kind:
3994 case SetComp_kind:
3995 case GeneratorExp_kind:
3996 case JoinedStr_kind:
3997 case FormattedValue_kind:
3998 return compiler_warn(c, "'%.200s' object is not callable; "
3999 "perhaps you missed a comma?",
4000 infer_type(e)->tp_name);
4001 default:
4002 return 1;
4003 }
4004}
4005
4006static int
4007check_subscripter(struct compiler *c, expr_ty e)
4008{
4009 PyObject *v;
4010
4011 switch (e->kind) {
4012 case Constant_kind:
4013 v = e->v.Constant.value;
4014 if (!(v == Py_None || v == Py_Ellipsis ||
4015 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4016 PyAnySet_Check(v)))
4017 {
4018 return 1;
4019 }
4020 /* fall through */
4021 case Set_kind:
4022 case SetComp_kind:
4023 case GeneratorExp_kind:
4024 case Lambda_kind:
4025 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4026 "perhaps you missed a comma?",
4027 infer_type(e)->tp_name);
4028 default:
4029 return 1;
4030 }
4031}
4032
4033static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004034check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004035{
4036 PyObject *v;
4037
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004038 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004039 if (index_type == NULL
4040 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4041 || index_type == &PySlice_Type) {
4042 return 1;
4043 }
4044
4045 switch (e->kind) {
4046 case Constant_kind:
4047 v = e->v.Constant.value;
4048 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4049 return 1;
4050 }
4051 /* fall through */
4052 case Tuple_kind:
4053 case List_kind:
4054 case ListComp_kind:
4055 case JoinedStr_kind:
4056 case FormattedValue_kind:
4057 return compiler_warn(c, "%.200s indices must be integers or slices, "
4058 "not %.200s; "
4059 "perhaps you missed a comma?",
4060 infer_type(e)->tp_name,
4061 index_type->tp_name);
4062 default:
4063 return 1;
4064 }
4065}
4066
Zackery Spytz97f5de02019-03-22 01:30:32 -06004067// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004068static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004069maybe_optimize_method_call(struct compiler *c, expr_ty e)
4070{
4071 Py_ssize_t argsl, i;
4072 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004073 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004074
4075 /* Check that the call node is an attribute access, and that
4076 the call doesn't have keyword parameters. */
4077 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4078 asdl_seq_LEN(e->v.Call.keywords))
4079 return -1;
4080
4081 /* Check that there are no *varargs types of arguments. */
4082 argsl = asdl_seq_LEN(args);
4083 for (i = 0; i < argsl; i++) {
4084 expr_ty elt = asdl_seq_GET(args, i);
4085 if (elt->kind == Starred_kind) {
4086 return -1;
4087 }
4088 }
4089
4090 /* Alright, we can optimize the code. */
4091 VISIT(c, expr, meth->v.Attribute.value);
4092 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4093 VISIT_SEQ(c, expr, e->v.Call.args);
4094 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4095 return 1;
4096}
4097
4098static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004099validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004100{
4101 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4102 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004103 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4104 if (key->arg == NULL) {
4105 continue;
4106 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004107 if (forbidden_name(c, key->arg, Store)) {
4108 return -1;
4109 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004110 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004111 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4112 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4113 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4114 if (msg == NULL) {
4115 return -1;
4116 }
4117 c->u->u_col_offset = other->col_offset;
4118 compiler_error(c, PyUnicode_AsUTF8(msg));
4119 Py_DECREF(msg);
4120 return -1;
4121 }
4122 }
4123 }
4124 return 0;
4125}
4126
4127static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004128compiler_call(struct compiler *c, expr_ty e)
4129{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004130 int ret = maybe_optimize_method_call(c, e);
4131 if (ret >= 0) {
4132 return ret;
4133 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004134 if (!check_caller(c, e->v.Call.func)) {
4135 return 0;
4136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004137 VISIT(c, expr, e->v.Call.func);
4138 return compiler_call_helper(c, 0,
4139 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004140 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004141}
4142
Eric V. Smith235a6f02015-09-19 14:51:32 -04004143static int
4144compiler_joined_str(struct compiler *c, expr_ty e)
4145{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004146 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004147 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4148 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004149 return 1;
4150}
4151
Eric V. Smitha78c7952015-11-03 12:45:05 -05004152/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004153static int
4154compiler_formatted_value(struct compiler *c, expr_ty e)
4155{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004156 /* Our oparg encodes 2 pieces of information: the conversion
4157 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004158
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004159 Convert the conversion char to 3 bits:
4160 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004161 !s : 001 0x1 FVC_STR
4162 !r : 010 0x2 FVC_REPR
4163 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004164
Eric V. Smitha78c7952015-11-03 12:45:05 -05004165 next bit is whether or not we have a format spec:
4166 yes : 100 0x4
4167 no : 000 0x0
4168 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004169
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004170 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004171 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004172
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004173 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004174 VISIT(c, expr, e->v.FormattedValue.value);
4175
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004176 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004177 case 's': oparg = FVC_STR; break;
4178 case 'r': oparg = FVC_REPR; break;
4179 case 'a': oparg = FVC_ASCII; break;
4180 case -1: oparg = FVC_NONE; break;
4181 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004182 PyErr_Format(PyExc_SystemError,
4183 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004184 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004185 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004186 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004187 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004188 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004189 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004190 }
4191
Eric V. Smitha78c7952015-11-03 12:45:05 -05004192 /* And push our opcode and oparg */
4193 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004194
Eric V. Smith235a6f02015-09-19 14:51:32 -04004195 return 1;
4196}
4197
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004198static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004199compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004200{
4201 Py_ssize_t i, n = end - begin;
4202 keyword_ty kw;
4203 PyObject *keys, *key;
4204 assert(n > 0);
4205 if (n > 1) {
4206 for (i = begin; i < end; i++) {
4207 kw = asdl_seq_GET(keywords, i);
4208 VISIT(c, expr, kw->value);
4209 }
4210 keys = PyTuple_New(n);
4211 if (keys == NULL) {
4212 return 0;
4213 }
4214 for (i = begin; i < end; i++) {
4215 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4216 Py_INCREF(key);
4217 PyTuple_SET_ITEM(keys, i - begin, key);
4218 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004219 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004220 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4221 }
4222 else {
4223 /* a for loop only executes once */
4224 for (i = begin; i < end; i++) {
4225 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004226 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004227 VISIT(c, expr, kw->value);
4228 }
4229 ADDOP_I(c, BUILD_MAP, n);
4230 }
4231 return 1;
4232}
4233
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004234/* shared code between compiler_call and compiler_class */
4235static int
4236compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004237 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004238 asdl_expr_seq *args,
4239 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004240{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004241 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004242
Pablo Galindo254ec782020-04-03 20:37:13 +01004243 if (validate_keywords(c, keywords) == -1) {
4244 return 0;
4245 }
4246
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004247 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004248 nkwelts = asdl_seq_LEN(keywords);
4249
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004250 for (i = 0; i < nelts; i++) {
4251 expr_ty elt = asdl_seq_GET(args, i);
4252 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004253 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004254 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004255 }
4256 for (i = 0; i < nkwelts; i++) {
4257 keyword_ty kw = asdl_seq_GET(keywords, i);
4258 if (kw->arg == NULL) {
4259 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004260 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004261 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004262
Mark Shannon13bc1392020-01-23 09:25:17 +00004263 /* No * or ** args, so can use faster calling sequence */
4264 for (i = 0; i < nelts; i++) {
4265 expr_ty elt = asdl_seq_GET(args, i);
4266 assert(elt->kind != Starred_kind);
4267 VISIT(c, expr, elt);
4268 }
4269 if (nkwelts) {
4270 PyObject *names;
4271 VISIT_SEQ(c, keyword, keywords);
4272 names = PyTuple_New(nkwelts);
4273 if (names == NULL) {
4274 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004275 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004276 for (i = 0; i < nkwelts; i++) {
4277 keyword_ty kw = asdl_seq_GET(keywords, i);
4278 Py_INCREF(kw->arg);
4279 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004280 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004281 ADDOP_LOAD_CONST_NEW(c, names);
4282 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4283 return 1;
4284 }
4285 else {
4286 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4287 return 1;
4288 }
4289
4290ex_call:
4291
4292 /* Do positional arguments. */
4293 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4294 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4295 }
4296 else if (starunpack_helper(c, args, n, BUILD_LIST,
4297 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4298 return 0;
4299 }
4300 /* Then keyword arguments */
4301 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004302 /* Has a new dict been pushed */
4303 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004304
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004305 nseen = 0; /* the number of keyword arguments on the stack following */
4306 for (i = 0; i < nkwelts; i++) {
4307 keyword_ty kw = asdl_seq_GET(keywords, i);
4308 if (kw->arg == NULL) {
4309 /* A keyword argument unpacking. */
4310 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004311 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004312 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004313 }
Mark Shannondb64f122020-06-01 10:42:42 +01004314 if (have_dict) {
4315 ADDOP_I(c, DICT_MERGE, 1);
4316 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004317 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004318 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004319 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004320 if (!have_dict) {
4321 ADDOP_I(c, BUILD_MAP, 0);
4322 have_dict = 1;
4323 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004324 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004325 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004326 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004327 else {
4328 nseen++;
4329 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004330 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004331 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004332 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004333 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004334 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004335 }
4336 if (have_dict) {
4337 ADDOP_I(c, DICT_MERGE, 1);
4338 }
4339 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004340 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004341 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004342 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004343 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4344 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004345}
4346
Nick Coghlan650f0d02007-04-15 12:05:43 +00004347
4348/* List and set comprehensions and generator expressions work by creating a
4349 nested function to perform the actual iteration. This means that the
4350 iteration variables don't leak into the current scope.
4351 The defined function is called immediately following its definition, with the
4352 result of that call being the result of the expression.
4353 The LC/SC version returns the populated container, while the GE version is
4354 flagged in symtable.c as a generator, so it returns the generator object
4355 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004356
4357 Possible cleanups:
4358 - iterate over the generator sequence instead of using recursion
4359*/
4360
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004361
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004362static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004363compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004364 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004365 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004366 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004367{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004368 comprehension_ty gen;
4369 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4370 if (gen->is_async) {
4371 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004372 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004373 } else {
4374 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004375 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004376 }
4377}
4378
4379static int
4380compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004381 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004382 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004383 expr_ty elt, expr_ty val, int type)
4384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 /* generate code for the iterator, then each of the ifs,
4386 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004388 comprehension_ty gen;
4389 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004390 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 start = compiler_new_block(c);
4393 skip = compiler_new_block(c);
4394 if_cleanup = compiler_new_block(c);
4395 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4398 anchor == NULL)
4399 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004403 if (gen_index == 0) {
4404 /* Receive outermost iter as an implicit argument */
4405 c->u->u_argcount = 1;
4406 ADDOP_I(c, LOAD_FAST, 0);
4407 }
4408 else {
4409 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004410 /* Fast path for the temporary variable assignment idiom:
4411 for y in [f(x)]
4412 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004413 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004414 switch (gen->iter->kind) {
4415 case List_kind:
4416 elts = gen->iter->v.List.elts;
4417 break;
4418 case Tuple_kind:
4419 elts = gen->iter->v.Tuple.elts;
4420 break;
4421 default:
4422 elts = NULL;
4423 }
4424 if (asdl_seq_LEN(elts) == 1) {
4425 expr_ty elt = asdl_seq_GET(elts, 0);
4426 if (elt->kind != Starred_kind) {
4427 VISIT(c, expr, elt);
4428 start = NULL;
4429 }
4430 }
4431 if (start) {
4432 VISIT(c, expr, gen->iter);
4433 ADDOP(c, GET_ITER);
4434 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004436 if (start) {
4437 depth++;
4438 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004439 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004440 NEXT_BLOCK(c);
4441 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 /* XXX this needs to be cleaned up...a lot! */
4445 n = asdl_seq_LEN(gen->ifs);
4446 for (i = 0; i < n; i++) {
4447 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004448 if (!compiler_jump_if(c, e, if_cleanup, 0))
4449 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 NEXT_BLOCK(c);
4451 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 if (++gen_index < asdl_seq_LEN(generators))
4454 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004455 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004456 elt, val, type))
4457 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004459 /* only append after the last for generator */
4460 if (gen_index >= asdl_seq_LEN(generators)) {
4461 /* comprehension specific code */
4462 switch (type) {
4463 case COMP_GENEXP:
4464 VISIT(c, expr, elt);
4465 ADDOP(c, YIELD_VALUE);
4466 ADDOP(c, POP_TOP);
4467 break;
4468 case COMP_LISTCOMP:
4469 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004470 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004471 break;
4472 case COMP_SETCOMP:
4473 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004474 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 break;
4476 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004477 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004480 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004481 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 break;
4483 default:
4484 return 0;
4485 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 compiler_use_next_block(c, skip);
4488 }
4489 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004490 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004491 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004492 compiler_use_next_block(c, anchor);
4493 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494
4495 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004496}
4497
4498static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004499compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004500 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004501 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004502 expr_ty elt, expr_ty val, int type)
4503{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004504 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004505 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004506 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004507 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004509 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004510
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004511 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512 return 0;
4513 }
4514
4515 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4516
4517 if (gen_index == 0) {
4518 /* Receive outermost iter as an implicit argument */
4519 c->u->u_argcount = 1;
4520 ADDOP_I(c, LOAD_FAST, 0);
4521 }
4522 else {
4523 /* Sub-iter - calculate on the fly */
4524 VISIT(c, expr, gen->iter);
4525 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004526 }
4527
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004528 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529
Mark Shannon582aaf12020-08-04 17:30:11 +01004530 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004532 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004533 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004534 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004535 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004536
4537 n = asdl_seq_LEN(gen->ifs);
4538 for (i = 0; i < n; i++) {
4539 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004540 if (!compiler_jump_if(c, e, if_cleanup, 0))
4541 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004542 NEXT_BLOCK(c);
4543 }
4544
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004545 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546 if (++gen_index < asdl_seq_LEN(generators))
4547 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004548 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004549 elt, val, type))
4550 return 0;
4551
4552 /* only append after the last for generator */
4553 if (gen_index >= asdl_seq_LEN(generators)) {
4554 /* comprehension specific code */
4555 switch (type) {
4556 case COMP_GENEXP:
4557 VISIT(c, expr, elt);
4558 ADDOP(c, YIELD_VALUE);
4559 ADDOP(c, POP_TOP);
4560 break;
4561 case COMP_LISTCOMP:
4562 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004563 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004564 break;
4565 case COMP_SETCOMP:
4566 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004567 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004568 break;
4569 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004570 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004571 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004572 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004573 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004574 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004575 break;
4576 default:
4577 return 0;
4578 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004579 }
4580 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004581 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004582
4583 compiler_use_next_block(c, except);
4584 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004585
4586 return 1;
4587}
4588
4589static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004590compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004591 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004592 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004594 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004595 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004596 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004597 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004598 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004599
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004600
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004601 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004602
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004603 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004604 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4605 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004606 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004607 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004608 }
4609
4610 is_async_generator = c->u->u_ste->ste_coroutine;
4611
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004612 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004613 compiler_error(c, "asynchronous comprehension outside of "
4614 "an asynchronous function");
4615 goto error_in_scope;
4616 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 if (type != COMP_GENEXP) {
4619 int op;
4620 switch (type) {
4621 case COMP_LISTCOMP:
4622 op = BUILD_LIST;
4623 break;
4624 case COMP_SETCOMP:
4625 op = BUILD_SET;
4626 break;
4627 case COMP_DICTCOMP:
4628 op = BUILD_MAP;
4629 break;
4630 default:
4631 PyErr_Format(PyExc_SystemError,
4632 "unknown comprehension type %d", type);
4633 goto error_in_scope;
4634 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004636 ADDOP_I(c, op, 0);
4637 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004638
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004639 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 val, type))
4641 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004643 if (type != COMP_GENEXP) {
4644 ADDOP(c, RETURN_VALUE);
4645 }
4646
4647 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004648 qualname = c->u->u_qualname;
4649 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004650 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004651 if (top_level_await && is_async_generator){
4652 c->u->u_ste->ste_coroutine = 1;
4653 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004654 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004655 goto error;
4656
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004657 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004659 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 Py_DECREF(co);
4661
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004662 VISIT(c, expr, outermost->iter);
4663
4664 if (outermost->is_async) {
4665 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004666 } else {
4667 ADDOP(c, GET_ITER);
4668 }
4669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004671
4672 if (is_async_generator && type != COMP_GENEXP) {
4673 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004674 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004675 ADDOP(c, YIELD_FROM);
4676 }
4677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004679error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004681error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004682 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 Py_XDECREF(co);
4684 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004685}
4686
4687static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004688compiler_genexp(struct compiler *c, expr_ty e)
4689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 static identifier name;
4691 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004692 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 if (!name)
4694 return 0;
4695 }
4696 assert(e->kind == GeneratorExp_kind);
4697 return compiler_comprehension(c, e, COMP_GENEXP, name,
4698 e->v.GeneratorExp.generators,
4699 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004700}
4701
4702static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004703compiler_listcomp(struct compiler *c, expr_ty e)
4704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 static identifier name;
4706 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004707 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 if (!name)
4709 return 0;
4710 }
4711 assert(e->kind == ListComp_kind);
4712 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4713 e->v.ListComp.generators,
4714 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004715}
4716
4717static int
4718compiler_setcomp(struct compiler *c, expr_ty e)
4719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004720 static identifier name;
4721 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004722 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004723 if (!name)
4724 return 0;
4725 }
4726 assert(e->kind == SetComp_kind);
4727 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4728 e->v.SetComp.generators,
4729 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004730}
4731
4732
4733static int
4734compiler_dictcomp(struct compiler *c, expr_ty e)
4735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 static identifier name;
4737 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004738 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004739 if (!name)
4740 return 0;
4741 }
4742 assert(e->kind == DictComp_kind);
4743 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4744 e->v.DictComp.generators,
4745 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004746}
4747
4748
4749static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004750compiler_visit_keyword(struct compiler *c, keyword_ty k)
4751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004752 VISIT(c, expr, k->value);
4753 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004754}
4755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004757 whether they are true or false.
4758
4759 Return values: 1 for true, 0 for false, -1 for non-constant.
4760 */
4761
4762static int
Mark Shannonfee55262019-11-21 09:11:43 +00004763compiler_with_except_finish(struct compiler *c) {
4764 basicblock *exit;
4765 exit = compiler_new_block(c);
4766 if (exit == NULL)
4767 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004768 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004769 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004770 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004771 compiler_use_next_block(c, exit);
4772 ADDOP(c, POP_TOP);
4773 ADDOP(c, POP_TOP);
4774 ADDOP(c, POP_TOP);
4775 ADDOP(c, POP_EXCEPT);
4776 ADDOP(c, POP_TOP);
4777 return 1;
4778}
Yury Selivanov75445082015-05-11 22:57:16 -04004779
4780/*
4781 Implements the async with statement.
4782
4783 The semantics outlined in that PEP are as follows:
4784
4785 async with EXPR as VAR:
4786 BLOCK
4787
4788 It is implemented roughly as:
4789
4790 context = EXPR
4791 exit = context.__aexit__ # not calling it
4792 value = await context.__aenter__()
4793 try:
4794 VAR = value # if VAR present in the syntax
4795 BLOCK
4796 finally:
4797 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004798 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004799 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004800 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004801 if not (await exit(*exc)):
4802 raise
4803 */
4804static int
4805compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4806{
Mark Shannonfee55262019-11-21 09:11:43 +00004807 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004808 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4809
4810 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004811 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004812 c->u->u_ste->ste_coroutine = 1;
4813 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004814 return compiler_error(c, "'async with' outside async function");
4815 }
Yury Selivanov75445082015-05-11 22:57:16 -04004816
4817 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004818 final = compiler_new_block(c);
4819 exit = compiler_new_block(c);
4820 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004821 return 0;
4822
4823 /* Evaluate EXPR */
4824 VISIT(c, expr, item->context_expr);
4825
4826 ADDOP(c, BEFORE_ASYNC_WITH);
4827 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004828 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004829 ADDOP(c, YIELD_FROM);
4830
Mark Shannon582aaf12020-08-04 17:30:11 +01004831 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004832
4833 /* SETUP_ASYNC_WITH pushes a finally block. */
4834 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004835 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004836 return 0;
4837 }
4838
4839 if (item->optional_vars) {
4840 VISIT(c, expr, item->optional_vars);
4841 }
4842 else {
4843 /* Discard result from context.__aenter__() */
4844 ADDOP(c, POP_TOP);
4845 }
4846
4847 pos++;
4848 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4849 /* BLOCK code */
4850 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4851 else if (!compiler_async_with(c, s, pos))
4852 return 0;
4853
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004854 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004855 ADDOP(c, POP_BLOCK);
4856 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004857
Mark Shannonfee55262019-11-21 09:11:43 +00004858 /* For successful outcome:
4859 * call __exit__(None, None, None)
4860 */
4861 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004862 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004863 ADDOP(c, GET_AWAITABLE);
4864 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4865 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004866
Mark Shannonfee55262019-11-21 09:11:43 +00004867 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004868
Mark Shannon582aaf12020-08-04 17:30:11 +01004869 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004870
4871 /* For exceptional outcome: */
4872 compiler_use_next_block(c, final);
4873
4874 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004875 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004876 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004877 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004878 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004879
Mark Shannonfee55262019-11-21 09:11:43 +00004880compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004881 return 1;
4882}
4883
4884
Guido van Rossumc2e20742006-02-27 22:32:47 +00004885/*
4886 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004887 with EXPR as VAR:
4888 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004889 is implemented as:
4890 <code for EXPR>
4891 SETUP_WITH E
4892 <code to store to VAR> or POP_TOP
4893 <code for BLOCK>
4894 LOAD_CONST (None, None, None)
4895 CALL_FUNCTION_EX 0
4896 JUMP_FORWARD EXIT
4897 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4898 POP_JUMP_IF_TRUE T:
4899 RERAISE
4900 T: POP_TOP * 3 (remove exception from stack)
4901 POP_EXCEPT
4902 POP_TOP
4903 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004904 */
Mark Shannonfee55262019-11-21 09:11:43 +00004905
Guido van Rossumc2e20742006-02-27 22:32:47 +00004906static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004907compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004908{
Mark Shannonfee55262019-11-21 09:11:43 +00004909 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004910 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004911
4912 assert(s->kind == With_kind);
4913
Guido van Rossumc2e20742006-02-27 22:32:47 +00004914 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004915 final = compiler_new_block(c);
4916 exit = compiler_new_block(c);
4917 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004918 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004919
Thomas Wouters477c8d52006-05-27 19:21:47 +00004920 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004921 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004922 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004923 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004924
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004925 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004926 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004927 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004928 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004929 }
4930
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004931 if (item->optional_vars) {
4932 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004933 }
4934 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004935 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004936 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004937 }
4938
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004939 pos++;
4940 if (pos == asdl_seq_LEN(s->v.With.items))
4941 /* BLOCK code */
4942 VISIT_SEQ(c, stmt, s->v.With.body)
4943 else if (!compiler_with(c, s, pos))
4944 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004945
Mark Shannon3bd60352021-01-13 12:05:43 +00004946
4947 /* Mark all following code as artificial */
4948 c->u->u_lineno = -1;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004949 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004950 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004951
Mark Shannonfee55262019-11-21 09:11:43 +00004952 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004953
Mark Shannonfee55262019-11-21 09:11:43 +00004954 /* For successful outcome:
4955 * call __exit__(None, None, None)
4956 */
4957 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004958 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004959 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004960 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004961
Mark Shannonfee55262019-11-21 09:11:43 +00004962 /* For exceptional outcome: */
4963 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004964
Mark Shannonfee55262019-11-21 09:11:43 +00004965 ADDOP(c, WITH_EXCEPT_START);
4966 compiler_with_except_finish(c);
4967
4968 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004969 return 1;
4970}
4971
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004972static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004973compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004975 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004976 case NamedExpr_kind:
4977 VISIT(c, expr, e->v.NamedExpr.value);
4978 ADDOP(c, DUP_TOP);
4979 VISIT(c, expr, e->v.NamedExpr.target);
4980 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004981 case BoolOp_kind:
4982 return compiler_boolop(c, e);
4983 case BinOp_kind:
4984 VISIT(c, expr, e->v.BinOp.left);
4985 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004986 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004987 break;
4988 case UnaryOp_kind:
4989 VISIT(c, expr, e->v.UnaryOp.operand);
4990 ADDOP(c, unaryop(e->v.UnaryOp.op));
4991 break;
4992 case Lambda_kind:
4993 return compiler_lambda(c, e);
4994 case IfExp_kind:
4995 return compiler_ifexp(c, e);
4996 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004997 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004998 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004999 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005000 case GeneratorExp_kind:
5001 return compiler_genexp(c, e);
5002 case ListComp_kind:
5003 return compiler_listcomp(c, e);
5004 case SetComp_kind:
5005 return compiler_setcomp(c, e);
5006 case DictComp_kind:
5007 return compiler_dictcomp(c, e);
5008 case Yield_kind:
5009 if (c->u->u_ste->ste_type != FunctionBlock)
5010 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005011 if (e->v.Yield.value) {
5012 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 }
5014 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005015 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005016 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005017 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005018 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005019 case YieldFrom_kind:
5020 if (c->u->u_ste->ste_type != FunctionBlock)
5021 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005022
5023 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5024 return compiler_error(c, "'yield from' inside async function");
5025
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005026 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005027 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005028 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005029 ADDOP(c, YIELD_FROM);
5030 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005031 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005032 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005033 if (c->u->u_ste->ste_type != FunctionBlock){
5034 return compiler_error(c, "'await' outside function");
5035 }
Yury Selivanov75445082015-05-11 22:57:16 -04005036
Victor Stinner331a6a52019-05-27 16:39:22 +02005037 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005038 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5039 return compiler_error(c, "'await' outside async function");
5040 }
5041 }
Yury Selivanov75445082015-05-11 22:57:16 -04005042
5043 VISIT(c, expr, e->v.Await.value);
5044 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005045 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005046 ADDOP(c, YIELD_FROM);
5047 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 case Compare_kind:
5049 return compiler_compare(c, e);
5050 case Call_kind:
5051 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005052 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005053 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005054 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005055 case JoinedStr_kind:
5056 return compiler_joined_str(c, e);
5057 case FormattedValue_kind:
5058 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005059 /* The following exprs can be assignment targets. */
5060 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005061 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005062 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005063 case Load:
5064 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5065 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005066 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005067 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5068 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5070 break;
5071 case Del:
5072 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5073 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 }
5075 break;
5076 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005077 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005078 case Starred_kind:
5079 switch (e->v.Starred.ctx) {
5080 case Store:
5081 /* In all legitimate cases, the Starred node was already replaced
5082 * by compiler_list/compiler_tuple. XXX: is that okay? */
5083 return compiler_error(c,
5084 "starred assignment target must be in a list or tuple");
5085 default:
5086 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005087 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005089 break;
5090 case Slice_kind:
5091 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 case Name_kind:
5093 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5094 /* child nodes of List and Tuple will have expr_context set */
5095 case List_kind:
5096 return compiler_list(c, e);
5097 case Tuple_kind:
5098 return compiler_tuple(c, e);
5099 }
5100 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005101}
5102
5103static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005104compiler_visit_expr(struct compiler *c, expr_ty e)
5105{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005106 int old_lineno = c->u->u_lineno;
5107 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005108 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005109 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005110 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005111 c->u->u_col_offset = old_col_offset;
5112 return res;
5113}
5114
5115static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005116compiler_augassign(struct compiler *c, stmt_ty s)
5117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005119 expr_ty e = s->v.AugAssign.target;
5120
5121 int old_lineno = c->u->u_lineno;
5122 int old_col_offset = c->u->u_col_offset;
5123 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 switch (e->kind) {
5126 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005127 VISIT(c, expr, e->v.Attribute.value);
5128 ADDOP(c, DUP_TOP);
5129 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005130 break;
5131 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005132 VISIT(c, expr, e->v.Subscript.value);
5133 VISIT(c, expr, e->v.Subscript.slice);
5134 ADDOP(c, DUP_TOP_TWO);
5135 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 break;
5137 case Name_kind:
5138 if (!compiler_nameop(c, e->v.Name.id, Load))
5139 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005140 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005141 default:
5142 PyErr_Format(PyExc_SystemError,
5143 "invalid node type (%d) for augmented assignment",
5144 e->kind);
5145 return 0;
5146 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005147
5148 c->u->u_lineno = old_lineno;
5149 c->u->u_col_offset = old_col_offset;
5150
5151 VISIT(c, expr, s->v.AugAssign.value);
5152 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5153
5154 SET_LOC(c, e);
5155
5156 switch (e->kind) {
5157 case Attribute_kind:
5158 ADDOP(c, ROT_TWO);
5159 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5160 break;
5161 case Subscript_kind:
5162 ADDOP(c, ROT_THREE);
5163 ADDOP(c, STORE_SUBSCR);
5164 break;
5165 case Name_kind:
5166 return compiler_nameop(c, e->v.Name.id, Store);
5167 default:
5168 Py_UNREACHABLE();
5169 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005171}
5172
5173static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005174check_ann_expr(struct compiler *c, expr_ty e)
5175{
5176 VISIT(c, expr, e);
5177 ADDOP(c, POP_TOP);
5178 return 1;
5179}
5180
5181static int
5182check_annotation(struct compiler *c, stmt_ty s)
5183{
5184 /* Annotations are only evaluated in a module or class. */
5185 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5186 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5187 return check_ann_expr(c, s->v.AnnAssign.annotation);
5188 }
5189 return 1;
5190}
5191
5192static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005193check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005194{
5195 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005196 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005197 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005198 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005199 return 0;
5200 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005201 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5202 return 0;
5203 }
5204 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5205 return 0;
5206 }
5207 return 1;
5208 case Tuple_kind: {
5209 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005210 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005211 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005212 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005213 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005214 return 0;
5215 }
5216 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005217 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005218 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005219 default:
5220 return check_ann_expr(c, e);
5221 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005222}
5223
5224static int
5225compiler_annassign(struct compiler *c, stmt_ty s)
5226{
5227 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005228 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005229
5230 assert(s->kind == AnnAssign_kind);
5231
5232 /* We perform the actual assignment first. */
5233 if (s->v.AnnAssign.value) {
5234 VISIT(c, expr, s->v.AnnAssign.value);
5235 VISIT(c, expr, targ);
5236 }
5237 switch (targ->kind) {
5238 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005239 if (forbidden_name(c, targ->v.Name.id, Store))
5240 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005241 /* If we have a simple name in a module or class, store annotation. */
5242 if (s->v.AnnAssign.simple &&
5243 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5244 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005245 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005246 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005247 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005248 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005249 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005250 }
5251 break;
5252 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005253 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5254 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005255 if (!s->v.AnnAssign.value &&
5256 !check_ann_expr(c, targ->v.Attribute.value)) {
5257 return 0;
5258 }
5259 break;
5260 case Subscript_kind:
5261 if (!s->v.AnnAssign.value &&
5262 (!check_ann_expr(c, targ->v.Subscript.value) ||
5263 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5264 return 0;
5265 }
5266 break;
5267 default:
5268 PyErr_Format(PyExc_SystemError,
5269 "invalid node type (%d) for annotated assignment",
5270 targ->kind);
5271 return 0;
5272 }
5273 /* Annotation is evaluated last. */
5274 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5275 return 0;
5276 }
5277 return 1;
5278}
5279
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005280/* Raises a SyntaxError and returns 0.
5281 If something goes wrong, a different exception may be raised.
5282*/
5283
5284static int
5285compiler_error(struct compiler *c, const char *errstr)
5286{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005287 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005289
Victor Stinner14e461d2013-08-26 22:28:21 +02005290 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005291 if (!loc) {
5292 Py_INCREF(Py_None);
5293 loc = Py_None;
5294 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005295 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005296 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005297 if (!u)
5298 goto exit;
5299 v = Py_BuildValue("(zO)", errstr, u);
5300 if (!v)
5301 goto exit;
5302 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005303 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005304 Py_DECREF(loc);
5305 Py_XDECREF(u);
5306 Py_XDECREF(v);
5307 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005308}
5309
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005310/* Emits a SyntaxWarning and returns 1 on success.
5311 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5312 and returns 0.
5313*/
5314static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005315compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005316{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005317 va_list vargs;
5318#ifdef HAVE_STDARG_PROTOTYPES
5319 va_start(vargs, format);
5320#else
5321 va_start(vargs);
5322#endif
5323 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5324 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005325 if (msg == NULL) {
5326 return 0;
5327 }
5328 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5329 c->u->u_lineno, NULL, NULL) < 0)
5330 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005331 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005332 /* Replace the SyntaxWarning exception with a SyntaxError
5333 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005334 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005335 assert(PyUnicode_AsUTF8(msg) != NULL);
5336 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005337 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005338 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005339 return 0;
5340 }
5341 Py_DECREF(msg);
5342 return 1;
5343}
5344
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005345static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005346compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005347{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005348 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005349 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005350
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005351 if (ctx == Load) {
5352 if (!check_subscripter(c, e->v.Subscript.value)) {
5353 return 0;
5354 }
5355 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5356 return 0;
5357 }
5358 }
5359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005360 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005361 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005362 case Store: op = STORE_SUBSCR; break;
5363 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005364 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005365 assert(op);
5366 VISIT(c, expr, e->v.Subscript.value);
5367 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005368 ADDOP(c, op);
5369 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005370}
5371
5372static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005373compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 int n = 2;
5376 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 /* only handles the cases where BUILD_SLICE is emitted */
5379 if (s->v.Slice.lower) {
5380 VISIT(c, expr, s->v.Slice.lower);
5381 }
5382 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005383 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005384 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 if (s->v.Slice.upper) {
5387 VISIT(c, expr, s->v.Slice.upper);
5388 }
5389 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005390 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005391 }
5392
5393 if (s->v.Slice.step) {
5394 n++;
5395 VISIT(c, expr, s->v.Slice.step);
5396 }
5397 ADDOP_I(c, BUILD_SLICE, n);
5398 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005399}
5400
Thomas Wouters89f507f2006-12-13 04:49:30 +00005401/* End of the compiler section, beginning of the assembler section */
5402
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005403/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005404 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005405
5406 XXX must handle implicit jumps from one block to next
5407*/
5408
Thomas Wouters89f507f2006-12-13 04:49:30 +00005409struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 PyObject *a_bytecode; /* string containing bytecode */
5411 int a_offset; /* offset into bytecode */
5412 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005413 PyObject *a_lnotab; /* string containing lnotab */
5414 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005415 int a_prevlineno; /* lineno of last emitted line in line table */
5416 int a_lineno; /* lineno of last emitted instruction */
5417 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005418 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005419};
5420
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005421Py_LOCAL_INLINE(void)
5422stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005423{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005424 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005425 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005426 assert(b->b_startdepth < 0);
5427 b->b_startdepth = depth;
5428 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005429 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005430}
5431
5432/* Find the flow path that needs the largest stack. We assume that
5433 * cycles in the flow graph have no net effect on the stack depth.
5434 */
5435static int
5436stackdepth(struct compiler *c)
5437{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005438 basicblock *b, *entryblock = NULL;
5439 basicblock **stack, **sp;
5440 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005442 b->b_startdepth = INT_MIN;
5443 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005444 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005445 }
5446 if (!entryblock)
5447 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005448 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5449 if (!stack) {
5450 PyErr_NoMemory();
5451 return -1;
5452 }
5453
5454 sp = stack;
5455 stackdepth_push(&sp, entryblock, 0);
5456 while (sp != stack) {
5457 b = *--sp;
5458 int depth = b->b_startdepth;
5459 assert(depth >= 0);
5460 basicblock *next = b->b_next;
5461 for (int i = 0; i < b->b_iused; i++) {
5462 struct instr *instr = &b->b_instr[i];
5463 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5464 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005465 _Py_FatalErrorFormat(__func__,
5466 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005467 }
5468 int new_depth = depth + effect;
5469 if (new_depth > maxdepth) {
5470 maxdepth = new_depth;
5471 }
5472 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005473 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005474 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5475 assert(effect != PY_INVALID_STACK_EFFECT);
5476 int target_depth = depth + effect;
5477 if (target_depth > maxdepth) {
5478 maxdepth = target_depth;
5479 }
5480 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005481 stackdepth_push(&sp, instr->i_target, target_depth);
5482 }
5483 depth = new_depth;
5484 if (instr->i_opcode == JUMP_ABSOLUTE ||
5485 instr->i_opcode == JUMP_FORWARD ||
5486 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005487 instr->i_opcode == RAISE_VARARGS ||
5488 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005489 {
5490 /* remaining code is dead */
5491 next = NULL;
5492 break;
5493 }
5494 }
5495 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005496 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005497 stackdepth_push(&sp, next, depth);
5498 }
5499 }
5500 PyObject_Free(stack);
5501 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005502}
5503
5504static int
5505assemble_init(struct assembler *a, int nblocks, int firstlineno)
5506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005507 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005508 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005509 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005511 if (a->a_bytecode == NULL) {
5512 goto error;
5513 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005515 if (a->a_lnotab == NULL) {
5516 goto error;
5517 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005518 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005519 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005520 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005522 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005523error:
5524 Py_XDECREF(a->a_bytecode);
5525 Py_XDECREF(a->a_lnotab);
5526 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005527}
5528
5529static void
5530assemble_free(struct assembler *a)
5531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 Py_XDECREF(a->a_bytecode);
5533 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005534}
5535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005536static int
5537blocksize(basicblock *b)
5538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 int i;
5540 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005543 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005545}
5546
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005547static int
Mark Shannon877df852020-11-12 09:43:29 +00005548assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005549{
Mark Shannon877df852020-11-12 09:43:29 +00005550 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 if (a->a_lnotab_off + 2 >= len) {
5552 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5553 return 0;
5554 }
Mark Shannon877df852020-11-12 09:43:29 +00005555 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005559 *lnotab++ = bdelta;
5560 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005562}
5563
Mark Shannon877df852020-11-12 09:43:29 +00005564/* Appends a range to the end of the line number table. See
5565 * Objects/lnotab_notes.txt for the description of the line number table. */
5566
5567static int
5568assemble_line_range(struct assembler *a)
5569{
5570 int ldelta, bdelta;
5571 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5572 if (bdelta == 0) {
5573 return 1;
5574 }
5575 if (a->a_lineno < 0) {
5576 ldelta = -128;
5577 }
5578 else {
5579 ldelta = a->a_lineno - a->a_prevlineno;
5580 a->a_prevlineno = a->a_lineno;
5581 while (ldelta > 127) {
5582 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5583 return 0;
5584 }
5585 ldelta -= 127;
5586 }
5587 while (ldelta < -127) {
5588 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5589 return 0;
5590 }
5591 ldelta += 127;
5592 }
5593 }
5594 assert(-128 <= ldelta && ldelta < 128);
5595 while (bdelta > 254) {
5596 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5597 return 0;
5598 }
5599 ldelta = a->a_lineno < 0 ? -128 : 0;
5600 bdelta -= 254;
5601 }
5602 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5603 return 0;
5604 }
5605 a->a_lineno_start = a->a_offset;
5606 return 1;
5607}
5608
5609static int
5610assemble_lnotab(struct assembler *a, struct instr *i)
5611{
5612 if (i->i_lineno == a->a_lineno) {
5613 return 1;
5614 }
5615 if (!assemble_line_range(a)) {
5616 return 0;
5617 }
5618 a->a_lineno = i->i_lineno;
5619 return 1;
5620}
5621
5622
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005623/* assemble_emit()
5624 Extend the bytecode with a new instruction.
5625 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005626*/
5627
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005628static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005629assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005630{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005631 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005632 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005633 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005634
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005635 arg = i->i_oparg;
5636 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 if (i->i_lineno && !assemble_lnotab(a, i))
5638 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005639 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005640 if (len > PY_SSIZE_T_MAX / 2)
5641 return 0;
5642 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5643 return 0;
5644 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005645 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005646 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005647 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005648 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005649}
5650
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005651static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005652assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005655 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 /* Compute the size of each block and fixup jump args.
5659 Replace block pointer with position in bytecode. */
5660 do {
5661 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005662 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 bsize = blocksize(b);
5664 b->b_offset = totsize;
5665 totsize += bsize;
5666 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005667 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5669 bsize = b->b_offset;
5670 for (i = 0; i < b->b_iused; i++) {
5671 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005672 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 /* Relative jumps are computed relative to
5674 the instruction pointer after fetching
5675 the jump instruction.
5676 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005677 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005678 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005680 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005681 instr->i_oparg -= bsize;
5682 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005683 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005684 if (instrsize(instr->i_oparg) != isize) {
5685 extended_arg_recompile = 1;
5686 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005687 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 }
5689 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 /* XXX: This is an awful hack that could hurt performance, but
5692 on the bright side it should work until we come up
5693 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 The issue is that in the first loop blocksize() is called
5696 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005697 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 So we loop until we stop seeing new EXTENDED_ARGs.
5701 The only EXTENDED_ARGs that could be popping up are
5702 ones in jump instructions. So this should converge
5703 fairly quickly.
5704 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005705 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005706}
5707
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005708static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005709dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005711 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005712 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 tuple = PyTuple_New(size);
5715 if (tuple == NULL)
5716 return NULL;
5717 while (PyDict_Next(dict, &pos, &k, &v)) {
5718 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005719 Py_INCREF(k);
5720 assert((i - offset) < size);
5721 assert((i - offset) >= 0);
5722 PyTuple_SET_ITEM(tuple, i - offset, k);
5723 }
5724 return tuple;
5725}
5726
5727static PyObject *
5728consts_dict_keys_inorder(PyObject *dict)
5729{
5730 PyObject *consts, *k, *v;
5731 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5732
5733 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5734 if (consts == NULL)
5735 return NULL;
5736 while (PyDict_Next(dict, &pos, &k, &v)) {
5737 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005738 /* The keys of the dictionary can be tuples wrapping a contant.
5739 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5740 * the object we want is always second. */
5741 if (PyTuple_CheckExact(k)) {
5742 k = PyTuple_GET_ITEM(k, 1);
5743 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005744 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005745 assert(i < size);
5746 assert(i >= 0);
5747 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005749 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005750}
5751
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005752static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005753compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005755 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005756 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005758 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005759 if (ste->ste_nested)
5760 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005761 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005762 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005763 if (!ste->ste_generator && ste->ste_coroutine)
5764 flags |= CO_COROUTINE;
5765 if (ste->ste_generator && ste->ste_coroutine)
5766 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005767 if (ste->ste_varargs)
5768 flags |= CO_VARARGS;
5769 if (ste->ste_varkeywords)
5770 flags |= CO_VARKEYWORDS;
5771 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 /* (Only) inherit compilerflags in PyCF_MASK */
5774 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005775
Pablo Galindo90235812020-03-15 04:29:22 +00005776 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005777 ste->ste_coroutine &&
5778 !ste->ste_generator) {
5779 flags |= CO_COROUTINE;
5780 }
5781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005782 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005783}
5784
INADA Naokic2e16072018-11-26 21:23:22 +09005785// Merge *tuple* with constant cache.
5786// Unlike merge_consts_recursive(), this function doesn't work recursively.
5787static int
5788merge_const_tuple(struct compiler *c, PyObject **tuple)
5789{
5790 assert(PyTuple_CheckExact(*tuple));
5791
5792 PyObject *key = _PyCode_ConstantKey(*tuple);
5793 if (key == NULL) {
5794 return 0;
5795 }
5796
5797 // t is borrowed reference
5798 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5799 Py_DECREF(key);
5800 if (t == NULL) {
5801 return 0;
5802 }
5803 if (t == key) { // tuple is new constant.
5804 return 1;
5805 }
5806
5807 PyObject *u = PyTuple_GET_ITEM(t, 1);
5808 Py_INCREF(u);
5809 Py_DECREF(*tuple);
5810 *tuple = u;
5811 return 1;
5812}
5813
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005814static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005815makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005817 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005818 PyObject *names = NULL;
5819 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005820 PyObject *name = NULL;
5821 PyObject *freevars = NULL;
5822 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005823 Py_ssize_t nlocals;
5824 int nlocals_int;
5825 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005826 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 names = dict_keys_inorder(c->u->u_names, 0);
5829 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005830 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005832 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005833 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5834 if (!cellvars)
5835 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005836 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 if (!freevars)
5838 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005839
INADA Naokic2e16072018-11-26 21:23:22 +09005840 if (!merge_const_tuple(c, &names) ||
5841 !merge_const_tuple(c, &varnames) ||
5842 !merge_const_tuple(c, &cellvars) ||
5843 !merge_const_tuple(c, &freevars))
5844 {
5845 goto error;
5846 }
5847
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005848 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005849 assert(nlocals < INT_MAX);
5850 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 flags = compute_code_flags(c);
5853 if (flags < 0)
5854 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005855
Mark Shannon6e8128f2020-07-30 10:03:00 +01005856 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5857 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005858 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005859 }
INADA Naokic2e16072018-11-26 21:23:22 +09005860 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005861 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005862 goto error;
5863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005865 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005866 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005867 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005868 maxdepth = stackdepth(c);
5869 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005870 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005871 goto error;
5872 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005873 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005874 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005875 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005876 varnames, freevars, cellvars, c->c_filename,
5877 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005878 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005879 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 Py_XDECREF(names);
5881 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005882 Py_XDECREF(name);
5883 Py_XDECREF(freevars);
5884 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005886}
5887
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005888
5889/* For debugging purposes only */
5890#if 0
5891static void
5892dump_instr(const struct instr *i)
5893{
Mark Shannon582aaf12020-08-04 17:30:11 +01005894 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5895 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005896 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005899 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005901 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005902 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5903 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005904}
5905
5906static void
5907dump_basicblock(const basicblock *b)
5908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005909 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005910 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5911 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005912 if (b->b_instr) {
5913 int i;
5914 for (i = 0; i < b->b_iused; i++) {
5915 fprintf(stderr, " [%02d] ", i);
5916 dump_instr(b->b_instr + i);
5917 }
5918 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005919}
5920#endif
5921
Mark Shannon5977a792020-12-02 13:31:40 +00005922
5923static int
5924normalize_basic_block(basicblock *bb);
5925
Mark Shannon6e8128f2020-07-30 10:03:00 +01005926static int
5927optimize_cfg(struct assembler *a, PyObject *consts);
5928
Mark Shannon5977a792020-12-02 13:31:40 +00005929static int
5930ensure_exits_have_lineno(struct compiler *c);
5931
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005932static PyCodeObject *
5933assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935 basicblock *b, *entryblock;
5936 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005937 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005939 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005941 /* Make sure every block that falls off the end returns None.
5942 XXX NEXT_BLOCK() isn't quite right, because if the last
5943 block ends with a jump or return b_next shouldn't set.
5944 */
5945 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005946 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005947 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005948 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005949 ADDOP(c, RETURN_VALUE);
5950 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005951
Mark Shannon5977a792020-12-02 13:31:40 +00005952 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
5953 if (normalize_basic_block(b)) {
5954 goto error;
5955 }
5956 }
5957
5958 if (ensure_exits_have_lineno(c)) {
5959 goto error;
5960 }
5961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 nblocks = 0;
5963 entryblock = NULL;
5964 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5965 nblocks++;
5966 entryblock = b;
5967 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 /* Set firstlineno if it wasn't explicitly set. */
5970 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005971 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005972 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005973 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 c->u->u_firstlineno = 1;
5975 }
Mark Shannon5977a792020-12-02 13:31:40 +00005976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005977 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5978 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005979 a.a_entry = entryblock;
5980 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005981
Mark Shannon6e8128f2020-07-30 10:03:00 +01005982 consts = consts_dict_keys_inorder(c->u->u_consts);
5983 if (consts == NULL) {
5984 goto error;
5985 }
5986 if (optimize_cfg(&a, consts)) {
5987 goto error;
5988 }
5989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 /* Can't modify the bytecode after computing jump offsets. */
5991 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005992
Mark Shannoncc75ab72020-11-12 19:49:33 +00005993 /* Emit code. */
5994 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005995 for (j = 0; j < b->b_iused; j++)
5996 if (!assemble_emit(&a, &b->b_instr[j]))
5997 goto error;
5998 }
Mark Shannon877df852020-11-12 09:43:29 +00005999 if (!assemble_line_range(&a)) {
6000 return 0;
6001 }
6002 /* Emit sentinel at end of line number table */
6003 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
6004 goto error;
6005 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6008 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006009 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006011
Mark Shannon6e8128f2020-07-30 10:03:00 +01006012 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006013 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006014 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006015 assemble_free(&a);
6016 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006017}
Georg Brandl8334fd92010-12-04 10:26:46 +00006018
6019#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006020PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006021PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6022 PyArena *arena)
6023{
6024 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6025}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006026
6027
6028/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6029 with LOAD_CONST (c1, c2, ... cn).
6030 The consts table must still be in list form so that the
6031 new constant (c1, c2, ... cn) can be appended.
6032 Called with codestr pointing to the first LOAD_CONST.
6033*/
6034static int
6035fold_tuple_on_constants(struct instr *inst,
6036 int n, PyObject *consts)
6037{
6038 /* Pre-conditions */
6039 assert(PyList_CheckExact(consts));
6040 assert(inst[n].i_opcode == BUILD_TUPLE);
6041 assert(inst[n].i_oparg == n);
6042
6043 for (int i = 0; i < n; i++) {
6044 if (inst[i].i_opcode != LOAD_CONST) {
6045 return 0;
6046 }
6047 }
6048
6049 /* Buildup new tuple of constants */
6050 PyObject *newconst = PyTuple_New(n);
6051 if (newconst == NULL) {
6052 return -1;
6053 }
6054 for (int i = 0; i < n; i++) {
6055 int arg = inst[i].i_oparg;
6056 PyObject *constant = PyList_GET_ITEM(consts, arg);
6057 Py_INCREF(constant);
6058 PyTuple_SET_ITEM(newconst, i, constant);
6059 }
6060 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006061 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006062 Py_DECREF(newconst);
6063 PyErr_SetString(PyExc_OverflowError, "too many constants");
6064 return -1;
6065 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006066 if (PyList_Append(consts, newconst)) {
6067 Py_DECREF(newconst);
6068 return -1;
6069 }
6070 Py_DECREF(newconst);
6071 for (int i = 0; i < n; i++) {
6072 inst[i].i_opcode = NOP;
6073 }
6074 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006075 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006076 return 0;
6077}
6078
Mark Shannon28b75c82020-12-23 11:43:10 +00006079
6080static int
6081eliminate_jump_to_jump(basicblock *bb, int opcode) {
6082 assert (bb->b_iused > 0);
6083 struct instr *inst = &bb->b_instr[bb->b_iused-1];
6084 assert (is_jump(inst));
6085 assert (inst->i_target->b_iused > 0);
6086 struct instr *target = &inst->i_target->b_instr[0];
6087 if (inst->i_target == target->i_target) {
6088 /* Nothing to do */
6089 return 0;
6090 }
6091 int lineno = target->i_lineno;
6092 if (add_jump_to_block(bb, opcode, lineno, target->i_target) == 0) {
6093 return -1;
6094 }
6095 assert (bb->b_iused >= 2);
6096 bb->b_instr[bb->b_iused-2].i_opcode = NOP;
6097 return 0;
6098}
6099
Mark Shannoncc75ab72020-11-12 19:49:33 +00006100/* Maximum size of basic block that should be copied in optimizer */
6101#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006102
6103/* Optimization */
6104static int
6105optimize_basic_block(basicblock *bb, PyObject *consts)
6106{
6107 assert(PyList_CheckExact(consts));
6108 struct instr nop;
6109 nop.i_opcode = NOP;
6110 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006111 for (int i = 0; i < bb->b_iused; i++) {
6112 struct instr *inst = &bb->b_instr[i];
6113 int oparg = inst->i_oparg;
6114 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006115 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006116 /* Skip over empty basic blocks. */
6117 while (inst->i_target->b_iused == 0) {
6118 inst->i_target = inst->i_target->b_next;
6119 }
6120 target = &inst->i_target->b_instr[0];
6121 }
6122 else {
6123 target = &nop;
6124 }
6125 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006126 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006127 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006128 {
6129 PyObject* cnt;
6130 int is_true;
6131 int jump_if_true;
6132 switch(nextop) {
6133 case POP_JUMP_IF_FALSE:
6134 case POP_JUMP_IF_TRUE:
6135 cnt = PyList_GET_ITEM(consts, oparg);
6136 is_true = PyObject_IsTrue(cnt);
6137 if (is_true == -1) {
6138 goto error;
6139 }
6140 inst->i_opcode = NOP;
6141 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6142 if (is_true == jump_if_true) {
6143 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6144 bb->b_nofallthrough = 1;
6145 }
6146 else {
6147 bb->b_instr[i+1].i_opcode = NOP;
6148 }
6149 break;
6150 case JUMP_IF_FALSE_OR_POP:
6151 case JUMP_IF_TRUE_OR_POP:
6152 cnt = PyList_GET_ITEM(consts, oparg);
6153 is_true = PyObject_IsTrue(cnt);
6154 if (is_true == -1) {
6155 goto error;
6156 }
6157 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6158 if (is_true == jump_if_true) {
6159 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6160 bb->b_nofallthrough = 1;
6161 }
6162 else {
6163 inst->i_opcode = NOP;
6164 bb->b_instr[i+1].i_opcode = NOP;
6165 }
6166 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006167 }
6168 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006169 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006170
6171 /* Try to fold tuples of constants.
6172 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6173 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6174 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6175 case BUILD_TUPLE:
6176 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6177 switch(oparg) {
6178 case 1:
6179 inst->i_opcode = NOP;
6180 bb->b_instr[i+1].i_opcode = NOP;
6181 break;
6182 case 2:
6183 inst->i_opcode = ROT_TWO;
6184 bb->b_instr[i+1].i_opcode = NOP;
6185 break;
6186 case 3:
6187 inst->i_opcode = ROT_THREE;
6188 bb->b_instr[i+1].i_opcode = ROT_TWO;
6189 }
6190 break;
6191 }
6192 if (i >= oparg) {
6193 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6194 goto error;
6195 }
6196 }
6197 break;
6198
6199 /* Simplify conditional jump to conditional jump where the
6200 result of the first test implies the success of a similar
6201 test or the failure of the opposite test.
6202 Arises in code like:
6203 "a and b or c"
6204 "(a and b) and c"
6205 "(a or b) or c"
6206 "(a or b) and c"
6207 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6208 --> x:JUMP_IF_FALSE_OR_POP z
6209 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6210 --> x:POP_JUMP_IF_FALSE y+1
6211 where y+1 is the instruction following the second test.
6212 */
6213 case JUMP_IF_FALSE_OR_POP:
6214 switch(target->i_opcode) {
6215 case POP_JUMP_IF_FALSE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006216 if (inst->i_lineno == target->i_lineno) {
6217 *inst = *target;
6218 i--;
6219 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006220 break;
6221 case JUMP_ABSOLUTE:
6222 case JUMP_FORWARD:
6223 case JUMP_IF_FALSE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006224 if (inst->i_lineno == target->i_lineno &&
6225 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006226 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006227 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006228 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006229 break;
6230 case JUMP_IF_TRUE_OR_POP:
6231 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006232 if (inst->i_lineno == target->i_lineno) {
6233 inst->i_opcode = POP_JUMP_IF_FALSE;
6234 inst->i_target = inst->i_target->b_next;
6235 --i;
6236 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006237 break;
6238 }
6239 break;
6240
6241 case JUMP_IF_TRUE_OR_POP:
6242 switch(target->i_opcode) {
6243 case POP_JUMP_IF_TRUE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006244 if (inst->i_lineno == target->i_lineno) {
6245 *inst = *target;
6246 i--;
6247 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006248 break;
6249 case JUMP_ABSOLUTE:
6250 case JUMP_FORWARD:
6251 case JUMP_IF_TRUE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006252 if (inst->i_lineno == target->i_lineno &&
6253 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006254 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006255 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006256 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006257 break;
6258 case JUMP_IF_FALSE_OR_POP:
6259 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006260 if (inst->i_lineno == target->i_lineno) {
6261 inst->i_opcode = POP_JUMP_IF_TRUE;
6262 inst->i_target = inst->i_target->b_next;
6263 --i;
6264 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006265 break;
6266 }
6267 break;
6268
6269 case POP_JUMP_IF_FALSE:
6270 switch(target->i_opcode) {
6271 case JUMP_ABSOLUTE:
6272 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006273 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006274 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006275 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006276 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006277 break;
6278 }
6279 break;
6280
6281 case POP_JUMP_IF_TRUE:
6282 switch(target->i_opcode) {
6283 case JUMP_ABSOLUTE:
6284 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006285 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006286 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006287 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006288 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006289 break;
6290 }
6291 break;
6292
6293 case JUMP_ABSOLUTE:
6294 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006295 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006296 switch(target->i_opcode) {
6297 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006298 if (eliminate_jump_to_jump(bb, inst->i_opcode)) {
6299 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006300 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006301 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006302
Mark Shannon6e8128f2020-07-30 10:03:00 +01006303 case JUMP_ABSOLUTE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006304 if (eliminate_jump_to_jump(bb, JUMP_ABSOLUTE)) {
6305 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006306 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006307 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006308 default:
6309 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6310 basicblock *to_copy = inst->i_target;
6311 inst->i_opcode = NOP;
6312 for (i = 0; i < to_copy->b_iused; i++) {
6313 int index = compiler_next_instr(bb);
6314 if (index < 0) {
6315 return -1;
6316 }
6317 bb->b_instr[index] = to_copy->b_instr[i];
6318 }
6319 bb->b_exit = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006320 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006321 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006322 }
6323 }
6324 return 0;
6325error:
6326 return -1;
6327}
6328
6329
6330static void
Mark Shannon1659ad12021-01-13 15:05:04 +00006331clean_basic_block(basicblock *bb, int prev_lineno) {
6332 /* Remove NOPs when legal to do so. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006333 int dest = 0;
6334 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006335 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006336 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006337 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006338 if (lineno < 0) {
6339 continue;
6340 }
Mark Shannon266b4622020-11-17 19:30:14 +00006341 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006342 if (prev_lineno == lineno) {
6343 continue;
6344 }
Mark Shannon266b4622020-11-17 19:30:14 +00006345 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006346 if (src < bb->b_iused - 1) {
6347 int next_lineno = bb->b_instr[src+1].i_lineno;
6348 if (next_lineno < 0 || next_lineno == lineno) {
6349 bb->b_instr[src+1].i_lineno = lineno;
6350 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006351 }
6352 }
Mark Shannon266b4622020-11-17 19:30:14 +00006353 else {
6354 basicblock* next = bb->b_next;
6355 while (next && next->b_iused == 0) {
6356 next = next->b_next;
6357 }
6358 /* or if last instruction in BB and next BB has same line number */
6359 if (next) {
6360 if (lineno == next->b_instr[0].i_lineno) {
6361 continue;
6362 }
6363 }
6364 }
6365
Mark Shannon6e8128f2020-07-30 10:03:00 +01006366 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006367 if (dest != src) {
6368 bb->b_instr[dest] = bb->b_instr[src];
6369 }
6370 dest++;
6371 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006372 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006373 assert(dest <= bb->b_iused);
6374 bb->b_iused = dest;
6375}
6376
Mark Shannon266b4622020-11-17 19:30:14 +00006377static int
6378normalize_basic_block(basicblock *bb) {
6379 /* Mark blocks as exit and/or nofallthrough.
6380 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006381 for (int i = 0; i < bb->b_iused; i++) {
6382 switch(bb->b_instr[i].i_opcode) {
6383 case RETURN_VALUE:
6384 case RAISE_VARARGS:
6385 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006386 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00006387 bb->b_nofallthrough = 1;
6388 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006389 case JUMP_ABSOLUTE:
6390 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006391 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006392 /* fall through */
6393 case POP_JUMP_IF_FALSE:
6394 case POP_JUMP_IF_TRUE:
6395 case JUMP_IF_FALSE_OR_POP:
6396 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00006397 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00006398 if (i != bb->b_iused-1) {
6399 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6400 return -1;
6401 }
Mark Shannon5977a792020-12-02 13:31:40 +00006402 /* Skip over empty basic blocks. */
6403 while (bb->b_instr[i].i_target->b_iused == 0) {
6404 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
6405 }
6406
Mark Shannoncc75ab72020-11-12 19:49:33 +00006407 }
6408 }
Mark Shannon266b4622020-11-17 19:30:14 +00006409 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006410}
6411
Mark Shannon6e8128f2020-07-30 10:03:00 +01006412static int
6413mark_reachable(struct assembler *a) {
6414 basicblock **stack, **sp;
6415 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6416 if (stack == NULL) {
6417 return -1;
6418 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006419 a->a_entry->b_predecessors = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006420 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006421 while (sp > stack) {
6422 basicblock *b = *(--sp);
Mark Shannon3bd60352021-01-13 12:05:43 +00006423 if (b->b_next && !b->b_nofallthrough) {
6424 if (b->b_next->b_predecessors == 0) {
6425 *sp++ = b->b_next;
6426 }
6427 b->b_next->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006428 }
6429 for (int i = 0; i < b->b_iused; i++) {
6430 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006431 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006432 target = b->b_instr[i].i_target;
Mark Shannon3bd60352021-01-13 12:05:43 +00006433 if (target->b_predecessors == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006434 *sp++ = target;
6435 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006436 target->b_predecessors++;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006437 }
6438 }
6439 }
6440 PyObject_Free(stack);
6441 return 0;
6442}
6443
Mark Shannon3bd60352021-01-13 12:05:43 +00006444static void
6445eliminate_empty_basic_blocks(basicblock *entry) {
6446 /* Eliminate empty blocks */
6447 for (basicblock *b = entry; b != NULL; b = b->b_next) {
6448 basicblock *next = b->b_next;
6449 if (next) {
6450 while (next->b_iused == 0 && next->b_next) {
6451 next = next->b_next;
6452 }
6453 b->b_next = next;
6454 }
6455 }
6456 for (basicblock *b = entry; b != NULL; b = b->b_next) {
6457 if (b->b_iused == 0) {
6458 continue;
6459 }
6460 if (is_jump(&b->b_instr[b->b_iused-1])) {
6461 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6462 while (target->b_iused == 0) {
6463 target = target->b_next;
6464 }
6465 b->b_instr[b->b_iused-1].i_target = target;
6466 }
6467 }
6468}
6469
6470
Mark Shannon5977a792020-12-02 13:31:40 +00006471/* If an instruction has no line number, but it's predecessor in the BB does,
Mark Shannon3bd60352021-01-13 12:05:43 +00006472 * then copy the line number. If a successor block has no line number, and only
6473 * one predecessor, then inherit the line number.
6474 * This ensures that all exit blocks (with one predecessor) receive a line number.
6475 * Also reduces the size of the line number table,
Mark Shannon5977a792020-12-02 13:31:40 +00006476 * but has no impact on the generated line number events.
6477 */
6478static void
Mark Shannon3bd60352021-01-13 12:05:43 +00006479propogate_line_numbers(struct assembler *a) {
Mark Shannon5977a792020-12-02 13:31:40 +00006480 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006481 if (b->b_iused == 0) {
6482 continue;
6483 }
Mark Shannon5977a792020-12-02 13:31:40 +00006484 int prev_lineno = -1;
6485 for (int i = 0; i < b->b_iused; i++) {
6486 if (b->b_instr[i].i_lineno < 0) {
6487 b->b_instr[i].i_lineno = prev_lineno;
6488 }
6489 else {
6490 prev_lineno = b->b_instr[i].i_lineno;
6491 }
6492 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006493 if (!b->b_nofallthrough && b->b_next->b_predecessors == 1) {
6494 assert(b->b_next->b_iused);
6495 if (b->b_next->b_instr[0].i_lineno < 0) {
6496 b->b_next->b_instr[0].i_lineno = prev_lineno;
6497 }
6498 }
6499 if (is_jump(&b->b_instr[b->b_iused-1])) {
6500 switch (b->b_instr[b->b_iused-1].i_opcode) {
6501 /* Note: Only actual jumps, not exception handlers */
6502 case SETUP_ASYNC_WITH:
6503 case SETUP_WITH:
6504 case SETUP_FINALLY:
6505 continue;
6506 }
6507 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6508 if (target->b_predecessors == 1) {
6509 if (target->b_instr[0].i_lineno < 0) {
6510 target->b_instr[0].i_lineno = prev_lineno;
6511 }
6512 }
6513 }
Mark Shannon5977a792020-12-02 13:31:40 +00006514 }
6515}
6516
6517/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01006518 The consts object should still be in list form to allow new constants
6519 to be appended.
6520
6521 All transformations keep the code size the same or smaller.
6522 For those that reduce size, the gaps are initially filled with
6523 NOPs. Later those NOPs are removed.
6524*/
6525
6526static int
6527optimize_cfg(struct assembler *a, PyObject *consts)
6528{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006529 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006530 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006531 return -1;
6532 }
Mark Shannon1659ad12021-01-13 15:05:04 +00006533 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00006534 assert(b->b_predecessors == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006535 }
6536 if (mark_reachable(a)) {
6537 return -1;
6538 }
6539 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006540 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006541 if (b->b_predecessors == 0) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006542 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05306543 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006544 }
6545 }
Mark Shannon1659ad12021-01-13 15:05:04 +00006546 basicblock *pred = NULL;
6547 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6548 int prev_lineno = -1;
6549 if (pred && pred->b_iused) {
6550 prev_lineno = pred->b_instr[pred->b_iused-1].i_lineno;
6551 }
6552 clean_basic_block(b, prev_lineno);
6553 pred = b->b_nofallthrough ? NULL : b;
6554 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006555 eliminate_empty_basic_blocks(a->a_entry);
Om Gc71581c2020-12-16 17:48:05 +05306556 /* Delete jump instructions made redundant by previous step. If a non-empty
6557 block ends with a jump instruction, check if the next non-empty block
6558 reached through normal flow control is the target of that jump. If it
6559 is, then the jump instruction is redundant and can be deleted.
6560 */
Mark Shannon3bd60352021-01-13 12:05:43 +00006561 int maybe_empty_blocks = 0;
Om Gc71581c2020-12-16 17:48:05 +05306562 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6563 if (b->b_iused > 0) {
6564 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
6565 if (b_last_instr->i_opcode == POP_JUMP_IF_FALSE ||
6566 b_last_instr->i_opcode == POP_JUMP_IF_TRUE ||
6567 b_last_instr->i_opcode == JUMP_ABSOLUTE ||
6568 b_last_instr->i_opcode == JUMP_FORWARD) {
Mark Shannon3bd60352021-01-13 12:05:43 +00006569 if (b_last_instr->i_target == b->b_next) {
6570 assert(b->b_next->b_iused);
Om Gc71581c2020-12-16 17:48:05 +05306571 b->b_nofallthrough = 0;
6572 switch(b_last_instr->i_opcode) {
6573 case POP_JUMP_IF_FALSE:
6574 case POP_JUMP_IF_TRUE:
6575 b_last_instr->i_opcode = POP_TOP;
6576 b_last_instr->i_target = NULL;
6577 b_last_instr->i_oparg = 0;
6578 break;
6579 case JUMP_ABSOLUTE:
6580 case JUMP_FORWARD:
6581 b_last_instr->i_opcode = NOP;
Mark Shannon1659ad12021-01-13 15:05:04 +00006582 clean_basic_block(b, -1);
Mark Shannon3bd60352021-01-13 12:05:43 +00006583 maybe_empty_blocks = 1;
Om Gc71581c2020-12-16 17:48:05 +05306584 break;
6585 }
Om Gc71581c2020-12-16 17:48:05 +05306586 }
6587 }
6588 }
6589 }
Mark Shannon3bd60352021-01-13 12:05:43 +00006590 if (maybe_empty_blocks) {
6591 eliminate_empty_basic_blocks(a->a_entry);
6592 }
6593 propogate_line_numbers(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006594 return 0;
6595}
6596
Mark Shannon5977a792020-12-02 13:31:40 +00006597static inline int
6598is_exit_without_lineno(basicblock *b) {
6599 return b->b_exit && b->b_instr[0].i_lineno < 0;
6600}
6601
6602/* PEP 626 mandates that the f_lineno of a frame is correct
6603 * after a frame terminates. It would be prohibitively expensive
6604 * to continuously update the f_lineno field at runtime,
6605 * so we make sure that all exiting instruction (raises and returns)
6606 * have a valid line number, allowing us to compute f_lineno lazily.
6607 * We can do this by duplicating the exit blocks without line number
6608 * so that none have more than one predecessor. We can then safely
6609 * copy the line number from the sole predecessor block.
6610 */
6611static int
6612ensure_exits_have_lineno(struct compiler *c)
6613{
Mark Shannoneaccc122020-12-04 15:22:12 +00006614 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006615 /* Copy all exit blocks without line number that are targets of a jump.
6616 */
6617 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6618 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
6619 switch (b->b_instr[b->b_iused-1].i_opcode) {
6620 /* Note: Only actual jumps, not exception handlers */
6621 case SETUP_ASYNC_WITH:
6622 case SETUP_WITH:
6623 case SETUP_FINALLY:
6624 continue;
6625 }
6626 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6627 if (is_exit_without_lineno(target)) {
6628 basicblock *new_target = compiler_copy_block(c, target);
6629 if (new_target == NULL) {
6630 return -1;
6631 }
6632 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6633 b->b_instr[b->b_iused-1].i_target = new_target;
6634 }
6635 }
Mark Shannoneaccc122020-12-04 15:22:12 +00006636 entry = b;
6637 }
6638 assert(entry != NULL);
6639 if (is_exit_without_lineno(entry)) {
6640 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00006641 }
Mark Shannonee9f98d2021-01-05 12:04:10 +00006642 /* Eliminate empty blocks */
6643 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6644 while (b->b_next && b->b_next->b_iused == 0) {
6645 b->b_next = b->b_next->b_next;
6646 }
6647 }
Mark Shannon5977a792020-12-02 13:31:40 +00006648 /* Any remaining reachable exit blocks without line number can only be reached by
6649 * fall through, and thus can only have a single predecessor */
6650 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6651 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
6652 if (is_exit_without_lineno(b->b_next)) {
6653 assert(b->b_next->b_iused > 0);
6654 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6655 }
6656 }
6657 }
6658 return 0;
6659}
6660
6661
Mark Shannon6e8128f2020-07-30 10:03:00 +01006662/* Retained for API compatibility.
6663 * Optimization is now done in optimize_cfg */
6664
6665PyObject *
6666PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6667 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6668{
6669 Py_INCREF(code);
6670 return code;
6671}
6672