blob: 6698b55000d9cf9810031b4f3f244f0f6bbbfd1d [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 Shannon6e8128f2020-07-30 10:03:00 +010098 unsigned b_reachable : 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +000099 /* Basic block has no fall through (it ends with a return, raise or jump) */
100 unsigned b_nofallthrough : 1;
101 /* Basic block exits scope (it ends with a return or raise) */
102 unsigned b_exit : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 /* depth of stack upon entry of block, computed by stackdepth() */
104 int b_startdepth;
105 /* instruction offset for block, computed by assemble_jump_offsets() */
106 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107} basicblock;
108
109/* fblockinfo tracks the current frame block.
110
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000111A frame block is used to handle loops, try/except, and try/finally.
112It's called a frame block to distinguish it from a basic block in the
113compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114*/
115
Mark Shannon02d126a2020-09-25 14:04:19 +0100116enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
117 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118
119struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 enum fblocktype fb_type;
121 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200122 /* (optional) type-specific exit or cleanup block */
123 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +0000124 /* (optional) additional information required for unwinding */
125 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126};
127
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100128enum {
129 COMPILER_SCOPE_MODULE,
130 COMPILER_SCOPE_CLASS,
131 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400132 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400133 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100134 COMPILER_SCOPE_COMPREHENSION,
135};
136
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137/* The following items change on entry and exit of code blocks.
138 They must be saved and restored when returning to a block.
139*/
140struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400144 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100145 int u_scope_type;
146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 /* The following fields are dicts that map objects to
148 the index of them in co_XXX. The index is used as
149 the argument for opcodes that refer to those collections.
150 */
151 PyObject *u_consts; /* all constants */
152 PyObject *u_names; /* all names */
153 PyObject *u_varnames; /* local variables */
154 PyObject *u_cellvars; /* cell variables */
155 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Victor Stinnerf8e32212013-11-19 23:56:34 +0100159 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100160 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100161 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* Pointer to the most recently allocated block. By following b_list
163 members, you can reach all early allocated blocks. */
164 basicblock *u_blocks;
165 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 int u_nfblocks;
168 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 int u_firstlineno; /* the first lineno of the block */
171 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000172 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173};
174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000177The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000179managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000180
181Note that we don't track recursion levels during compilation - the
182task of detecting and rejecting excessive levels of nesting is
183handled by the symbol analysis pass.
184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185*/
186
187struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200188 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 struct symtable *c_st;
190 PyFutureFeatures *c_future; /* pointer to module's __future__ */
191 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
Georg Brandl8334fd92010-12-04 10:26:46 +0000193 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 int c_interactive; /* true if in interactive mode */
195 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100196 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
197 if this value is different from zero.
198 This can be used to temporarily visit
199 nodes without emitting bytecode to
200 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201
INADA Naokic2e16072018-11-26 21:23:22 +0900202 PyObject *c_const_cache; /* Python dict holding all constants,
203 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 struct compiler_unit *u; /* compiler state for current block */
205 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
206 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207};
208
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100209static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210static void compiler_free(struct compiler *);
211static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500212static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100214static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100215static int compiler_addop_j(struct compiler *, int, basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200217static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
219
220static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
221static int compiler_visit_stmt(struct compiler *, stmt_ty);
222static int compiler_visit_keyword(struct compiler *, keyword_ty);
223static int compiler_visit_expr(struct compiler *, expr_ty);
224static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700225static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200226static int compiler_subscript(struct compiler *, expr_ty);
227static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228
Andy Lester76d58772020-03-10 21:18:12 -0500229static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100230static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Mark Shannon8473cf82020-12-15 11:07:50 +0000231
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500233static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400234static int compiler_async_with(struct compiler *, stmt_ty, int);
235static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100236static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100237 asdl_expr_seq *args,
238 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500239static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400240static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000241
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700242static int compiler_sync_comprehension_generator(
243 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100244 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200245 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700246 expr_ty elt, expr_ty val, int type);
247
248static int compiler_async_comprehension_generator(
249 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100250 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200251 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700252 expr_ty elt, expr_ty val, int type);
253
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000255static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400257#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000260_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* Name mangling: __private becomes _classname__private.
263 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 PyObject *result;
265 size_t nlen, plen, ipriv;
266 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200268 PyUnicode_READ_CHAR(ident, 0) != '_' ||
269 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 Py_INCREF(ident);
271 return ident;
272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200273 nlen = PyUnicode_GET_LENGTH(ident);
274 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 The only time a name with a dot can occur is when
278 we are compiling an import statement that has a
279 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 TODO(jhylton): Decide whether we want to support
282 mangling of the module name, e.g. __M.X.
283 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200284 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
285 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
286 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Py_INCREF(ident);
288 return ident; /* Don't mangle __whatever__ */
289 }
290 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200291 ipriv = 0;
292 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
293 ipriv++;
294 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_INCREF(ident);
296 return ident; /* Don't mangle if class is just underscores */
297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200298 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000299
Antoine Pitrou55bff892013-04-06 21:21:04 +0200300 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
301 PyErr_SetString(PyExc_OverflowError,
302 "private identifier too large to be mangled");
303 return NULL;
304 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200306 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
307 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
308 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
309
310 result = PyUnicode_New(1 + nlen + plen, maxchar);
311 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200313 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
314 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200315 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
316 Py_DECREF(result);
317 return NULL;
318 }
319 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
320 Py_DECREF(result);
321 return NULL;
322 }
Victor Stinner8f825062012-04-27 13:55:39 +0200323 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200324 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000325}
326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327static int
328compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000331
INADA Naokic2e16072018-11-26 21:23:22 +0900332 c->c_const_cache = PyDict_New();
333 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900335 }
336
337 c->c_stack = PyList_New(0);
338 if (!c->c_stack) {
339 Py_CLEAR(c->c_const_cache);
340 return 0;
341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344}
345
346PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200347PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
348 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 struct compiler c;
351 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200352 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (!__doc__) {
356 __doc__ = PyUnicode_InternFromString("__doc__");
357 if (!__doc__)
358 return NULL;
359 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000360 if (!__annotations__) {
361 __annotations__ = PyUnicode_InternFromString("__annotations__");
362 if (!__annotations__)
363 return NULL;
364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (!compiler_init(&c))
366 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200367 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 c.c_filename = filename;
369 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200370 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c.c_future == NULL)
372 goto finally;
373 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 flags = &local_flags;
375 }
376 merged = c.c_future->ff_features | flags->cf_flags;
377 c.c_future->ff_features = merged;
378 flags->cf_flags = merged;
379 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200380 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100382 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383
Pablo Galindod112c602020-03-18 23:02:09 +0000384 _PyASTOptimizeState state;
385 state.optimize = c.c_optimize;
386 state.ff_features = merged;
387
388 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900389 goto finally;
390 }
391
Victor Stinner14e461d2013-08-26 22:28:21 +0200392 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (c.c_st == NULL) {
394 if (!PyErr_Occurred())
395 PyErr_SetString(PyExc_SystemError, "no symtable");
396 goto finally;
397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400
Thomas Wouters1175c432006-02-27 22:49:54 +0000401 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 compiler_free(&c);
403 assert(co || PyErr_Occurred());
404 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405}
406
407PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200408PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
409 int optimize, PyArena *arena)
410{
411 PyObject *filename;
412 PyCodeObject *co;
413 filename = PyUnicode_DecodeFSDefault(filename_str);
414 if (filename == NULL)
415 return NULL;
416 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
417 Py_DECREF(filename);
418 return co;
419
420}
421
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000422static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (c->c_st)
426 PySymtable_Free(c->c_st);
427 if (c->c_future)
428 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200429 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900430 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000432}
433
Guido van Rossum79f25d91997-04-29 20:08:16 +0000434static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 Py_ssize_t i, n;
438 PyObject *v, *k;
439 PyObject *dict = PyDict_New();
440 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 n = PyList_Size(list);
443 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100444 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (!v) {
446 Py_DECREF(dict);
447 return NULL;
448 }
449 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300450 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 Py_DECREF(v);
452 Py_DECREF(dict);
453 return NULL;
454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(v);
456 }
457 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458}
459
460/* Return new dict containing names from src that match scope(s).
461
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000462src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464values are integers, starting at offset and increasing by one for
465each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466*/
467
468static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100469dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700471 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500473 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 assert(offset >= 0);
476 if (dest == NULL)
477 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478
Meador Inge2ca63152012-07-18 14:20:11 -0500479 /* Sort the keys so that we have a deterministic order on the indexes
480 saved in the returned dictionary. These indexes are used as indexes
481 into the free and cell var storage. Therefore if they aren't
482 deterministic, then the generated bytecode is not deterministic.
483 */
484 sorted_keys = PyDict_Keys(src);
485 if (sorted_keys == NULL)
486 return NULL;
487 if (PyList_Sort(sorted_keys) != 0) {
488 Py_DECREF(sorted_keys);
489 return NULL;
490 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500491 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500492
493 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* XXX this should probably be a macro in symtable.h */
495 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500496 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200497 v = PyDict_GetItemWithError(src, k);
498 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 vi = PyLong_AS_LONG(v);
500 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300503 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500505 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_DECREF(dest);
507 return NULL;
508 }
509 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300510 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500511 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_DECREF(item);
513 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return NULL;
515 }
516 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 }
518 }
Meador Inge2ca63152012-07-18 14:20:11 -0500519 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000521}
522
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523static void
524compiler_unit_check(struct compiler_unit *u)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 basicblock *block;
527 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700528 assert((uintptr_t)block != 0xcbcbcbcbU);
529 assert((uintptr_t)block != 0xfbfbfbfbU);
530 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (block->b_instr != NULL) {
532 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100533 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 assert(block->b_ialloc >= block->b_iused);
535 }
536 else {
537 assert (block->b_iused == 0);
538 assert (block->b_ialloc == 0);
539 }
540 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541}
542
543static void
544compiler_unit_free(struct compiler_unit *u)
545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 compiler_unit_check(u);
549 b = u->u_blocks;
550 while (b != NULL) {
551 if (b->b_instr)
552 PyObject_Free((void *)b->b_instr);
553 next = b->b_list;
554 PyObject_Free((void *)b);
555 b = next;
556 }
557 Py_CLEAR(u->u_ste);
558 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400559 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 Py_CLEAR(u->u_consts);
561 Py_CLEAR(u->u_names);
562 Py_CLEAR(u->u_varnames);
563 Py_CLEAR(u->u_freevars);
564 Py_CLEAR(u->u_cellvars);
565 Py_CLEAR(u->u_private);
566 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567}
568
569static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100570compiler_enter_scope(struct compiler *c, identifier name,
571 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100574 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575
Andy Lester7668a8b2020-03-24 23:26:44 -0500576 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 struct compiler_unit));
578 if (!u) {
579 PyErr_NoMemory();
580 return 0;
581 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100582 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100584 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 u->u_kwonlyargcount = 0;
586 u->u_ste = PySymtable_Lookup(c->c_st, key);
587 if (!u->u_ste) {
588 compiler_unit_free(u);
589 return 0;
590 }
591 Py_INCREF(name);
592 u->u_name = name;
593 u->u_varnames = list2dict(u->u_ste->ste_varnames);
594 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
595 if (!u->u_varnames || !u->u_cellvars) {
596 compiler_unit_free(u);
597 return 0;
598 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500599 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000600 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500601 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300602 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500603 int res;
604 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200605 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500606 name = _PyUnicode_FromId(&PyId___class__);
607 if (!name) {
608 compiler_unit_free(u);
609 return 0;
610 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100611 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500612 if (res < 0) {
613 compiler_unit_free(u);
614 return 0;
615 }
616 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200619 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (!u->u_freevars) {
621 compiler_unit_free(u);
622 return 0;
623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 u->u_blocks = NULL;
626 u->u_nfblocks = 0;
627 u->u_firstlineno = lineno;
628 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000629 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 u->u_consts = PyDict_New();
631 if (!u->u_consts) {
632 compiler_unit_free(u);
633 return 0;
634 }
635 u->u_names = PyDict_New();
636 if (!u->u_names) {
637 compiler_unit_free(u);
638 return 0;
639 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 /* Push the old compiler_unit on the stack. */
644 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400645 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
647 Py_XDECREF(capsule);
648 compiler_unit_free(u);
649 return 0;
650 }
651 Py_DECREF(capsule);
652 u->u_private = c->u->u_private;
653 Py_XINCREF(u->u_private);
654 }
655 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100658
659 block = compiler_new_block(c);
660 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100662 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400664 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
665 if (!compiler_set_qualname(c))
666 return 0;
667 }
668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000672static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673compiler_exit_scope(struct compiler *c)
674{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100675 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 c->c_nestlevel--;
679 compiler_unit_free(c->u);
680 /* Restore c->u to the parent unit. */
681 n = PyList_GET_SIZE(c->c_stack) - 1;
682 if (n >= 0) {
683 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400684 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 assert(c->u);
686 /* we are deleting from a list so this really shouldn't fail */
687 if (PySequence_DelItem(c->c_stack, n) < 0)
688 Py_FatalError("compiler_exit_scope()");
689 compiler_unit_check(c->u);
690 }
691 else
692 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000693
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694}
695
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696static int
697compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100699 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400700 _Py_static_string(dot_locals, ".<locals>");
701 Py_ssize_t stack_size;
702 struct compiler_unit *u = c->u;
703 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100704
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400707 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400708 if (stack_size > 1) {
709 int scope, force_global = 0;
710 struct compiler_unit *parent;
711 PyObject *mangled, *capsule;
712
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400713 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400714 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400715 assert(parent);
716
Yury Selivanov75445082015-05-11 22:57:16 -0400717 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
718 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
719 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 assert(u->u_name);
721 mangled = _Py_Mangle(parent->u_private, u->u_name);
722 if (!mangled)
723 return 0;
724 scope = PyST_GetScope(parent->u_ste, mangled);
725 Py_DECREF(mangled);
726 assert(scope != GLOBAL_IMPLICIT);
727 if (scope == GLOBAL_EXPLICIT)
728 force_global = 1;
729 }
730
731 if (!force_global) {
732 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400733 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400734 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
735 dot_locals_str = _PyUnicode_FromId(&dot_locals);
736 if (dot_locals_str == NULL)
737 return 0;
738 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
739 if (base == NULL)
740 return 0;
741 }
742 else {
743 Py_INCREF(parent->u_qualname);
744 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400745 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100746 }
747 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400748
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400749 if (base != NULL) {
750 dot_str = _PyUnicode_FromId(&dot);
751 if (dot_str == NULL) {
752 Py_DECREF(base);
753 return 0;
754 }
755 name = PyUnicode_Concat(base, dot_str);
756 Py_DECREF(base);
757 if (name == NULL)
758 return 0;
759 PyUnicode_Append(&name, u->u_name);
760 if (name == NULL)
761 return 0;
762 }
763 else {
764 Py_INCREF(u->u_name);
765 name = u->u_name;
766 }
767 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100768
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400769 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100770}
771
Eric V. Smith235a6f02015-09-19 14:51:32 -0400772
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773/* Allocate a new block and return a pointer to it.
774 Returns NULL on error.
775*/
776
777static basicblock *
778compiler_new_block(struct compiler *c)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 basicblock *b;
781 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500784 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (b == NULL) {
786 PyErr_NoMemory();
787 return NULL;
788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 /* Extend the singly linked list of blocks with new block. */
790 b->b_list = u->u_blocks;
791 u->u_blocks = b;
792 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796compiler_next_block(struct compiler *c)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 basicblock *block = compiler_new_block(c);
799 if (block == NULL)
800 return NULL;
801 c->u->u_curblock->b_next = block;
802 c->u->u_curblock = block;
803 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000804}
805
806static basicblock *
807compiler_use_next_block(struct compiler *c, basicblock *block)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(block != NULL);
810 c->u->u_curblock->b_next = block;
811 c->u->u_curblock = block;
812 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813}
814
Mark Shannon5977a792020-12-02 13:31:40 +0000815static basicblock *
816compiler_copy_block(struct compiler *c, basicblock *block)
817{
818 /* Cannot copy a block if it has a fallthrough, since
819 * a block can only have one fallthrough predecessor.
820 */
821 assert(block->b_nofallthrough);
822 basicblock *result = compiler_next_block(c);
823 if (result == NULL) {
824 return NULL;
825 }
826 for (int i = 0; i < block->b_iused; i++) {
827 int n = compiler_next_instr(result);
828 if (n < 0) {
829 return NULL;
830 }
831 result->b_instr[n] = block->b_instr[i];
832 }
833 result->b_exit = block->b_exit;
834 return result;
835}
836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837/* Returns the offset of the next instruction in the current block's
838 b_instr array. Resizes the b_instr as necessary.
839 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000840*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841
842static int
Andy Lester76d58772020-03-10 21:18:12 -0500843compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 assert(b != NULL);
846 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500847 b->b_instr = (struct instr *)PyObject_Calloc(
848 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (b->b_instr == NULL) {
850 PyErr_NoMemory();
851 return -1;
852 }
853 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 }
855 else if (b->b_iused == b->b_ialloc) {
856 struct instr *tmp;
857 size_t oldsize, newsize;
858 oldsize = b->b_ialloc * sizeof(struct instr);
859 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000860
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700861 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyErr_NoMemory();
863 return -1;
864 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (newsize == 0) {
867 PyErr_NoMemory();
868 return -1;
869 }
870 b->b_ialloc <<= 1;
871 tmp = (struct instr *)PyObject_Realloc(
872 (void *)b->b_instr, newsize);
873 if (tmp == NULL) {
874 PyErr_NoMemory();
875 return -1;
876 }
877 b->b_instr = tmp;
878 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
879 }
880 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000881}
882
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200883/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000884
Christian Heimes2202f872008-02-06 14:31:34 +0000885 The line number is reset in the following cases:
886 - when entering a new scope
887 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200888 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200889 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200892#define SET_LOC(c, x) \
893 (c)->u->u_lineno = (x)->lineno; \
894 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200896/* Return the stack effect of opcode with argument oparg.
897
898 Some opcodes have different stack effect when jump to the target and
899 when not jump. The 'jump' parameter specifies the case:
900
901 * 0 -- when not jump
902 * 1 -- when jump
903 * -1 -- maximal
904 */
905/* XXX Make the stack effect of WITH_CLEANUP_START and
906 WITH_CLEANUP_FINISH deterministic. */
907static int
908stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300911 case NOP:
912 case EXTENDED_ARG:
913 return 0;
914
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200915 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case POP_TOP:
917 return -1;
918 case ROT_TWO:
919 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200920 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 return 0;
922 case DUP_TOP:
923 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000924 case DUP_TOP_TWO:
925 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200927 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case UNARY_POSITIVE:
929 case UNARY_NEGATIVE:
930 case UNARY_NOT:
931 case UNARY_INVERT:
932 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case SET_ADD:
935 case LIST_APPEND:
936 return -1;
937 case MAP_ADD:
938 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000939
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200940 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case BINARY_POWER:
942 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400943 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 case BINARY_MODULO:
945 case BINARY_ADD:
946 case BINARY_SUBTRACT:
947 case BINARY_SUBSCR:
948 case BINARY_FLOOR_DIVIDE:
949 case BINARY_TRUE_DIVIDE:
950 return -1;
951 case INPLACE_FLOOR_DIVIDE:
952 case INPLACE_TRUE_DIVIDE:
953 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 case INPLACE_ADD:
956 case INPLACE_SUBTRACT:
957 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400958 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 case INPLACE_MODULO:
960 return -1;
961 case STORE_SUBSCR:
962 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 case DELETE_SUBSCR:
964 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case BINARY_LSHIFT:
967 case BINARY_RSHIFT:
968 case BINARY_AND:
969 case BINARY_XOR:
970 case BINARY_OR:
971 return -1;
972 case INPLACE_POWER:
973 return -1;
974 case GET_ITER:
975 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case PRINT_EXPR:
978 return -1;
979 case LOAD_BUILD_CLASS:
980 return 1;
981 case INPLACE_LSHIFT:
982 case INPLACE_RSHIFT:
983 case INPLACE_AND:
984 case INPLACE_XOR:
985 case INPLACE_OR:
986 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200989 /* 1 in the normal flow.
990 * Restore the stack position and push 6 values before jumping to
991 * the handler if an exception be raised. */
992 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case RETURN_VALUE:
994 return -1;
995 case IMPORT_STAR:
996 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700997 case SETUP_ANNOTATIONS:
998 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case YIELD_VALUE:
1000 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05001001 case YIELD_FROM:
1002 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 case POP_BLOCK:
1004 return 0;
1005 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001006 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case STORE_NAME:
1009 return -1;
1010 case DELETE_NAME:
1011 return 0;
1012 case UNPACK_SEQUENCE:
1013 return oparg-1;
1014 case UNPACK_EX:
1015 return (oparg&0xFF) + (oparg>>8);
1016 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001017 /* -1 at end of iterator, 1 if continue iterating. */
1018 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case STORE_ATTR:
1021 return -2;
1022 case DELETE_ATTR:
1023 return -1;
1024 case STORE_GLOBAL:
1025 return -1;
1026 case DELETE_GLOBAL:
1027 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case LOAD_CONST:
1029 return 1;
1030 case LOAD_NAME:
1031 return 1;
1032 case BUILD_TUPLE:
1033 case BUILD_LIST:
1034 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001035 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 return 1-oparg;
1037 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001038 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001039 case BUILD_CONST_KEY_MAP:
1040 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case LOAD_ATTR:
1042 return 0;
1043 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001044 case IS_OP:
1045 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001047 case JUMP_IF_NOT_EXC_MATCH:
1048 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case IMPORT_NAME:
1050 return -1;
1051 case IMPORT_FROM:
1052 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001053
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001054 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 case JUMP_ABSOLUTE:
1057 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001059 case JUMP_IF_TRUE_OR_POP:
1060 case JUMP_IF_FALSE_OR_POP:
1061 return jump ? 0 : -1;
1062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 case POP_JUMP_IF_FALSE:
1064 case POP_JUMP_IF_TRUE:
1065 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case LOAD_GLOBAL:
1068 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001070 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001072 /* 0 in the normal flow.
1073 * Restore the stack position and push 6 values before jumping to
1074 * the handler if an exception be raised. */
1075 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001076 case RERAISE:
1077 return -3;
1078
1079 case WITH_EXCEPT_START:
1080 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 case LOAD_FAST:
1083 return 1;
1084 case STORE_FAST:
1085 return -1;
1086 case DELETE_FAST:
1087 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 case RAISE_VARARGS:
1090 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001091
1092 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001094 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001095 case CALL_METHOD:
1096 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001098 return -oparg-1;
1099 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001100 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001101 case MAKE_FUNCTION:
1102 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1103 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 case BUILD_SLICE:
1105 if (oparg == 3)
1106 return -2;
1107 else
1108 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001110 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 case LOAD_CLOSURE:
1112 return 1;
1113 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001114 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 return 1;
1116 case STORE_DEREF:
1117 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001118 case DELETE_DEREF:
1119 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001120
1121 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001122 case GET_AWAITABLE:
1123 return 0;
1124 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001125 /* 0 in the normal flow.
1126 * Restore the stack position to the position before the result
1127 * of __aenter__ and push 6 values before jumping to the handler
1128 * if an exception be raised. */
1129 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001130 case BEFORE_ASYNC_WITH:
1131 return 1;
1132 case GET_AITER:
1133 return 0;
1134 case GET_ANEXT:
1135 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001136 case GET_YIELD_FROM_ITER:
1137 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001138 case END_ASYNC_FOR:
1139 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001140 case FORMAT_VALUE:
1141 /* If there's a fmt_spec on the stack, we go from 2->1,
1142 else 1->1. */
1143 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001144 case LOAD_METHOD:
1145 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001146 case LOAD_ASSERTION_ERROR:
1147 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001148 case LIST_TO_TUPLE:
1149 return 0;
1150 case LIST_EXTEND:
1151 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001152 case DICT_MERGE:
1153 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001154 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001156 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 }
Larry Hastings3a907972013-11-23 14:49:22 -08001158 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159}
1160
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001161int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001162PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1163{
1164 return stack_effect(opcode, oparg, jump);
1165}
1166
1167int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001168PyCompile_OpcodeStackEffect(int opcode, int oparg)
1169{
1170 return stack_effect(opcode, oparg, -1);
1171}
1172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173/* Add an opcode with no argument.
1174 Returns 0 on failure, 1 on success.
1175*/
1176
1177static int
1178compiler_addop(struct compiler *c, int opcode)
1179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 basicblock *b;
1181 struct instr *i;
1182 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001183 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001184 if (c->c_do_not_emit_bytecode) {
1185 return 1;
1186 }
Andy Lester76d58772020-03-10 21:18:12 -05001187 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (off < 0)
1189 return 0;
1190 b = c->u->u_curblock;
1191 i = &b->b_instr[off];
1192 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001193 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (opcode == RETURN_VALUE)
1195 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001196 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198}
1199
Victor Stinnerf8e32212013-11-19 23:56:34 +01001200static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001201compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001203 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001206 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001208 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001210 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001211 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001212 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return -1;
1215 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001216 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 Py_DECREF(v);
1218 return -1;
1219 }
1220 Py_DECREF(v);
1221 }
1222 else
1223 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001224 return arg;
1225}
1226
INADA Naokic2e16072018-11-26 21:23:22 +09001227// Merge const *o* recursively and return constant key object.
1228static PyObject*
1229merge_consts_recursive(struct compiler *c, PyObject *o)
1230{
1231 // None and Ellipsis are singleton, and key is the singleton.
1232 // No need to merge object and key.
1233 if (o == Py_None || o == Py_Ellipsis) {
1234 Py_INCREF(o);
1235 return o;
1236 }
1237
1238 PyObject *key = _PyCode_ConstantKey(o);
1239 if (key == NULL) {
1240 return NULL;
1241 }
1242
1243 // t is borrowed reference
1244 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1245 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001246 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001247 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001248 Py_DECREF(key);
1249 return t;
1250 }
1251
INADA Naokif7e4d362018-11-29 00:58:46 +09001252 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001253 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001254 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001255 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001256 Py_ssize_t len = PyTuple_GET_SIZE(o);
1257 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001258 PyObject *item = PyTuple_GET_ITEM(o, i);
1259 PyObject *u = merge_consts_recursive(c, item);
1260 if (u == NULL) {
1261 Py_DECREF(key);
1262 return NULL;
1263 }
1264
1265 // See _PyCode_ConstantKey()
1266 PyObject *v; // borrowed
1267 if (PyTuple_CheckExact(u)) {
1268 v = PyTuple_GET_ITEM(u, 1);
1269 }
1270 else {
1271 v = u;
1272 }
1273 if (v != item) {
1274 Py_INCREF(v);
1275 PyTuple_SET_ITEM(o, i, v);
1276 Py_DECREF(item);
1277 }
1278
1279 Py_DECREF(u);
1280 }
1281 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001282 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001283 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001284 // constant keys.
1285 // See _PyCode_ConstantKey() for detail.
1286 assert(PyTuple_CheckExact(key));
1287 assert(PyTuple_GET_SIZE(key) == 2);
1288
1289 Py_ssize_t len = PySet_GET_SIZE(o);
1290 if (len == 0) { // empty frozenset should not be re-created.
1291 return key;
1292 }
1293 PyObject *tuple = PyTuple_New(len);
1294 if (tuple == NULL) {
1295 Py_DECREF(key);
1296 return NULL;
1297 }
1298 Py_ssize_t i = 0, pos = 0;
1299 PyObject *item;
1300 Py_hash_t hash;
1301 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1302 PyObject *k = merge_consts_recursive(c, item);
1303 if (k == NULL) {
1304 Py_DECREF(tuple);
1305 Py_DECREF(key);
1306 return NULL;
1307 }
1308 PyObject *u;
1309 if (PyTuple_CheckExact(k)) {
1310 u = PyTuple_GET_ITEM(k, 1);
1311 Py_INCREF(u);
1312 Py_DECREF(k);
1313 }
1314 else {
1315 u = k;
1316 }
1317 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1318 i++;
1319 }
1320
1321 // Instead of rewriting o, we create new frozenset and embed in the
1322 // key tuple. Caller should get merged frozenset from the key tuple.
1323 PyObject *new = PyFrozenSet_New(tuple);
1324 Py_DECREF(tuple);
1325 if (new == NULL) {
1326 Py_DECREF(key);
1327 return NULL;
1328 }
1329 assert(PyTuple_GET_ITEM(key, 1) == o);
1330 Py_DECREF(o);
1331 PyTuple_SET_ITEM(key, 1, new);
1332 }
INADA Naokic2e16072018-11-26 21:23:22 +09001333
1334 return key;
1335}
1336
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001337static Py_ssize_t
1338compiler_add_const(struct compiler *c, PyObject *o)
1339{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001340 if (c->c_do_not_emit_bytecode) {
1341 return 0;
1342 }
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{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001357 if (c->c_do_not_emit_bytecode) {
1358 return 1;
1359 }
1360
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001361 Py_ssize_t arg = compiler_add_const(c, o);
1362 if (arg < 0)
1363 return 0;
1364 return compiler_addop_i(c, LOAD_CONST, arg);
1365}
1366
1367static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001371 if (c->c_do_not_emit_bytecode) {
1372 return 1;
1373 }
1374
Andy Lester76d58772020-03-10 21:18:12 -05001375 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001377 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378 return compiler_addop_i(c, opcode, arg);
1379}
1380
1381static int
1382compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001385 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001386
1387 if (c->c_do_not_emit_bytecode) {
1388 return 1;
1389 }
1390
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1392 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001393 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001394 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395 Py_DECREF(mangled);
1396 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001397 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 return compiler_addop_i(c, opcode, arg);
1399}
1400
1401/* Add an opcode with an integer argument.
1402 Returns 0 on failure, 1 on success.
1403*/
1404
1405static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001406compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 struct instr *i;
1409 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001410
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001411 if (c->c_do_not_emit_bytecode) {
1412 return 1;
1413 }
1414
Victor Stinner2ad474b2016-03-01 23:34:47 +01001415 /* oparg value is unsigned, but a signed C int is usually used to store
1416 it in the C code (like Python/ceval.c).
1417
1418 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1419
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001420 The argument of a concrete bytecode instruction is limited to 8-bit.
1421 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1422 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001423 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001424
Andy Lester76d58772020-03-10 21:18:12 -05001425 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (off < 0)
1427 return 0;
1428 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001429 i->i_opcode = opcode;
1430 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001431 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433}
1434
1435static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001436compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 struct instr *i;
1439 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001441 if (c->c_do_not_emit_bytecode) {
1442 return 1;
1443 }
1444
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001445 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001447 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (off < 0)
1449 return 0;
1450 i = &c->u->u_curblock->b_instr[off];
1451 i->i_opcode = opcode;
1452 i->i_target = b;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001453 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001455}
1456
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001457/* NEXT_BLOCK() creates an implicit jump from the current block
1458 to the new block.
1459
1460 The returns inside this macro make it impossible to decref objects
1461 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 if (compiler_next_block((C)) == NULL) \
1465 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466}
1467
1468#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (!compiler_addop((C), (OP))) \
1470 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471}
1472
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001473#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (!compiler_addop((C), (OP))) { \
1475 compiler_exit_scope(c); \
1476 return 0; \
1477 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001478}
1479
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001480#define ADDOP_LOAD_CONST(C, O) { \
1481 if (!compiler_addop_load_const((C), (O))) \
1482 return 0; \
1483}
1484
1485/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1486#define ADDOP_LOAD_CONST_NEW(C, O) { \
1487 PyObject *__new_const = (O); \
1488 if (__new_const == NULL) { \
1489 return 0; \
1490 } \
1491 if (!compiler_addop_load_const((C), __new_const)) { \
1492 Py_DECREF(__new_const); \
1493 return 0; \
1494 } \
1495 Py_DECREF(__new_const); \
1496}
1497
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1500 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501}
1502
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001503/* Same as ADDOP_O, but steals a reference. */
1504#define ADDOP_N(C, OP, O, TYPE) { \
1505 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1506 Py_DECREF((O)); \
1507 return 0; \
1508 } \
1509 Py_DECREF((O)); \
1510}
1511
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1514 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515}
1516
1517#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (!compiler_addop_i((C), (OP), (O))) \
1519 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
Mark Shannon582aaf12020-08-04 17:30:11 +01001522#define ADDOP_JUMP(C, OP, O) { \
1523 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525}
1526
Mark Shannon9af0e472020-01-14 10:12:45 +00001527#define ADDOP_COMPARE(C, CMP) { \
1528 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1529 return 0; \
1530}
1531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1533 the ASDL name to synthesize the name of the C type and the visit function.
1534*/
1535
1536#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (!compiler_visit_ ## TYPE((C), (V))) \
1538 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539}
1540
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001541#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 if (!compiler_visit_ ## TYPE((C), (V))) { \
1543 compiler_exit_scope(c); \
1544 return 0; \
1545 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546}
1547
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (!compiler_visit_slice((C), (V), (CTX))) \
1550 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001551}
1552
1553#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001555 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1557 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1558 if (!compiler_visit_ ## TYPE((C), elt)) \
1559 return 0; \
1560 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561}
1562
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001563#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001565 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1567 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1568 if (!compiler_visit_ ## TYPE((C), elt)) { \
1569 compiler_exit_scope(c); \
1570 return 0; \
1571 } \
1572 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001573}
1574
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001575/* Search if variable annotations are present statically in a block. */
1576
1577static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001578find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001579{
1580 int i, j, res = 0;
1581 stmt_ty st;
1582
1583 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1584 st = (stmt_ty)asdl_seq_GET(stmts, i);
1585 switch (st->kind) {
1586 case AnnAssign_kind:
1587 return 1;
1588 case For_kind:
1589 res = find_ann(st->v.For.body) ||
1590 find_ann(st->v.For.orelse);
1591 break;
1592 case AsyncFor_kind:
1593 res = find_ann(st->v.AsyncFor.body) ||
1594 find_ann(st->v.AsyncFor.orelse);
1595 break;
1596 case While_kind:
1597 res = find_ann(st->v.While.body) ||
1598 find_ann(st->v.While.orelse);
1599 break;
1600 case If_kind:
1601 res = find_ann(st->v.If.body) ||
1602 find_ann(st->v.If.orelse);
1603 break;
1604 case With_kind:
1605 res = find_ann(st->v.With.body);
1606 break;
1607 case AsyncWith_kind:
1608 res = find_ann(st->v.AsyncWith.body);
1609 break;
1610 case Try_kind:
1611 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1612 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1613 st->v.Try.handlers, j);
1614 if (find_ann(handler->v.ExceptHandler.body)) {
1615 return 1;
1616 }
1617 }
1618 res = find_ann(st->v.Try.body) ||
1619 find_ann(st->v.Try.finalbody) ||
1620 find_ann(st->v.Try.orelse);
1621 break;
1622 default:
1623 res = 0;
1624 }
1625 if (res) {
1626 break;
1627 }
1628 }
1629 return res;
1630}
1631
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001632/*
1633 * Frame block handling functions
1634 */
1635
1636static int
1637compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001638 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001639{
1640 struct fblockinfo *f;
1641 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001642 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001643 }
1644 f = &c->u->u_fblock[c->u->u_nfblocks++];
1645 f->fb_type = t;
1646 f->fb_block = b;
1647 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001648 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001649 return 1;
1650}
1651
1652static void
1653compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1654{
1655 struct compiler_unit *u = c->u;
1656 assert(u->u_nfblocks > 0);
1657 u->u_nfblocks--;
1658 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1659 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1660}
1661
Mark Shannonfee55262019-11-21 09:11:43 +00001662static int
1663compiler_call_exit_with_nones(struct compiler *c) {
1664 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1665 ADDOP(c, DUP_TOP);
1666 ADDOP(c, DUP_TOP);
1667 ADDOP_I(c, CALL_FUNCTION, 3);
1668 return 1;
1669}
1670
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001671/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001672 * popping the blocks will be restored afterwards, unless another
1673 * return, break or continue is found. In which case, the TOS will
1674 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001675 */
1676static int
1677compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1678 int preserve_tos)
1679{
1680 switch (info->fb_type) {
1681 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001682 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001683 return 1;
1684
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001685 case FOR_LOOP:
1686 /* Pop the iterator */
1687 if (preserve_tos) {
1688 ADDOP(c, ROT_TWO);
1689 }
1690 ADDOP(c, POP_TOP);
1691 return 1;
1692
Mark Shannon02d126a2020-09-25 14:04:19 +01001693 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001694 ADDOP(c, POP_BLOCK);
1695 return 1;
1696
1697 case FINALLY_TRY:
Mark Shannon5274b682020-12-16 13:07:01 +00001698 /* This POP_BLOCK gets the line number of the unwinding statement */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001699 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001700 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001701 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1702 return 0;
1703 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001704 }
Mark Shannon5274b682020-12-16 13:07:01 +00001705 /* Emit the finally block */
Mark Shannonfee55262019-11-21 09:11:43 +00001706 VISIT_SEQ(c, stmt, info->fb_datum);
1707 if (preserve_tos) {
1708 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001709 }
Mark Shannon5274b682020-12-16 13:07:01 +00001710 /* The finally block should appear to execute after the
1711 * statement causing the unwinding, so make the unwinding
1712 * instruction artificial */
1713 c->u->u_lineno = -1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001714 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001715
Mark Shannonfee55262019-11-21 09:11:43 +00001716 case FINALLY_END:
1717 if (preserve_tos) {
1718 ADDOP(c, ROT_FOUR);
1719 }
1720 ADDOP(c, POP_TOP);
1721 ADDOP(c, POP_TOP);
1722 ADDOP(c, POP_TOP);
1723 if (preserve_tos) {
1724 ADDOP(c, ROT_FOUR);
1725 }
1726 ADDOP(c, POP_EXCEPT);
1727 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001728
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001729 case WITH:
1730 case ASYNC_WITH:
1731 ADDOP(c, POP_BLOCK);
1732 if (preserve_tos) {
1733 ADDOP(c, ROT_TWO);
1734 }
Mark Shannonfee55262019-11-21 09:11:43 +00001735 if(!compiler_call_exit_with_nones(c)) {
1736 return 0;
1737 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001738 if (info->fb_type == ASYNC_WITH) {
1739 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001740 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001741 ADDOP(c, YIELD_FROM);
1742 }
Mark Shannonfee55262019-11-21 09:11:43 +00001743 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001744 return 1;
1745
1746 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001747 if (info->fb_datum) {
1748 ADDOP(c, POP_BLOCK);
1749 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001750 if (preserve_tos) {
1751 ADDOP(c, ROT_FOUR);
1752 }
Mark Shannonfee55262019-11-21 09:11:43 +00001753 ADDOP(c, POP_EXCEPT);
1754 if (info->fb_datum) {
1755 ADDOP_LOAD_CONST(c, Py_None);
1756 compiler_nameop(c, info->fb_datum, Store);
1757 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001758 }
Mark Shannonfee55262019-11-21 09:11:43 +00001759 return 1;
1760
1761 case POP_VALUE:
1762 if (preserve_tos) {
1763 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001764 }
Mark Shannonfee55262019-11-21 09:11:43 +00001765 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001766 return 1;
1767 }
1768 Py_UNREACHABLE();
1769}
1770
Mark Shannonfee55262019-11-21 09:11:43 +00001771/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1772static int
1773compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1774 if (c->u->u_nfblocks == 0) {
1775 return 1;
1776 }
1777 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1778 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1779 *loop = top;
1780 return 1;
1781 }
1782 struct fblockinfo copy = *top;
1783 c->u->u_nfblocks--;
1784 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1785 return 0;
1786 }
1787 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1788 return 0;
1789 }
1790 c->u->u_fblock[c->u->u_nfblocks] = copy;
1791 c->u->u_nfblocks++;
1792 return 1;
1793}
1794
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001795/* Compile a sequence of statements, checking for a docstring
1796 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797
1798static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001799compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001801 int i = 0;
1802 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001803 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001804
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001805 /* Set current line number to the line number of first statement.
1806 This way line number for SETUP_ANNOTATIONS will always
1807 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301808 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001809 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001810 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001811 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001812 }
1813 /* Every annotated class and module should have __annotations__. */
1814 if (find_ann(stmts)) {
1815 ADDOP(c, SETUP_ANNOTATIONS);
1816 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001817 if (!asdl_seq_LEN(stmts))
1818 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001819 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001820 if (c->c_optimize < 2) {
1821 docstring = _PyAST_GetDocString(stmts);
1822 if (docstring) {
1823 i = 1;
1824 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1825 assert(st->kind == Expr_kind);
1826 VISIT(c, expr, st->v.Expr.value);
1827 if (!compiler_nameop(c, __doc__, Store))
1828 return 0;
1829 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001831 for (; i < asdl_seq_LEN(stmts); i++)
1832 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834}
1835
1836static PyCodeObject *
1837compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 PyCodeObject *co;
1840 int addNone = 1;
1841 static PyObject *module;
1842 if (!module) {
1843 module = PyUnicode_InternFromString("<module>");
1844 if (!module)
1845 return NULL;
1846 }
1847 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001848 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 return NULL;
1850 switch (mod->kind) {
1851 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001852 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 compiler_exit_scope(c);
1854 return 0;
1855 }
1856 break;
1857 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001858 if (find_ann(mod->v.Interactive.body)) {
1859 ADDOP(c, SETUP_ANNOTATIONS);
1860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001862 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 break;
1864 case Expression_kind:
1865 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1866 addNone = 0;
1867 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 default:
1869 PyErr_Format(PyExc_SystemError,
1870 "module kind %d should not be possible",
1871 mod->kind);
1872 return 0;
1873 }
1874 co = assemble(c, addNone);
1875 compiler_exit_scope(c);
1876 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001877}
1878
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879/* The test for LOCAL must come before the test for FREE in order to
1880 handle classes where name is both local and free. The local var is
1881 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001882*/
1883
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884static int
1885get_ref_type(struct compiler *c, PyObject *name)
1886{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001887 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001888 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001889 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001890 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001891 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001893 _Py_FatalErrorFormat(__func__,
1894 "unknown scope for %.100s in %.100s(%s)\n"
1895 "symbols: %s\nlocals: %s\nglobals: %s",
1896 PyUnicode_AsUTF8(name),
1897 PyUnicode_AsUTF8(c->u->u_name),
1898 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1899 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1900 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1901 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905}
1906
1907static int
1908compiler_lookup_arg(PyObject *dict, PyObject *name)
1909{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001910 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001911 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001913 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001914 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001915}
1916
1917static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001918compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001920 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001921 if (qualname == NULL)
1922 qualname = co->co_name;
1923
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001924 if (free) {
1925 for (i = 0; i < free; ++i) {
1926 /* Bypass com_addop_varname because it will generate
1927 LOAD_DEREF but LOAD_CLOSURE is needed.
1928 */
1929 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1930 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001932 /* Special case: If a class contains a method with a
1933 free variable that has the same name as a method,
1934 the name will be considered free *and* local in the
1935 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001936 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001937 */
1938 reftype = get_ref_type(c, name);
1939 if (reftype == CELL)
1940 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1941 else /* (reftype == FREE) */
1942 arg = compiler_lookup_arg(c->u->u_freevars, name);
1943 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001944 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001945 "lookup %s in %s %d %d\n"
1946 "freevars of %s: %s\n",
1947 PyUnicode_AsUTF8(PyObject_Repr(name)),
1948 PyUnicode_AsUTF8(c->u->u_name),
1949 reftype, arg,
1950 PyUnicode_AsUTF8(co->co_name),
1951 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001952 }
1953 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001955 flags |= 0x08;
1956 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001958 ADDOP_LOAD_CONST(c, (PyObject*)co);
1959 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001960 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962}
1963
1964static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001965compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 if (!decos)
1970 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1973 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1974 }
1975 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976}
1977
1978static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001979compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1980 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001981{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001982 /* Push a dict of keyword-only default values.
1983
1984 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1985 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001986 int i;
1987 PyObject *keys = NULL;
1988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1990 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1991 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1992 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001993 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001994 if (!mangled) {
1995 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001997 if (keys == NULL) {
1998 keys = PyList_New(1);
1999 if (keys == NULL) {
2000 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002001 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002002 }
2003 PyList_SET_ITEM(keys, 0, mangled);
2004 }
2005 else {
2006 int res = PyList_Append(keys, mangled);
2007 Py_DECREF(mangled);
2008 if (res == -1) {
2009 goto error;
2010 }
2011 }
2012 if (!compiler_visit_expr(c, default_)) {
2013 goto error;
2014 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 }
2016 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002017 if (keys != NULL) {
2018 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2019 PyObject *keys_tuple = PyList_AsTuple(keys);
2020 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002021 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002022 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002023 assert(default_count > 0);
2024 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002025 }
2026 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002027 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002028 }
2029
2030error:
2031 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002032 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002033}
2034
2035static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002036compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2037{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002038 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002039 return 1;
2040}
2041
2042static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002043compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002044 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002047 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002048 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002049 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002050
2051 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002052 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002053 VISIT(c, annexpr, annotation);
2054 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002056 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002057}
2058
2059static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002060compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002061 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002062{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002063 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 for (i = 0; i < asdl_seq_LEN(args); i++) {
2065 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002066 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 c,
2068 arg->arg,
2069 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002070 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002071 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002073 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002074}
2075
2076static int
2077compiler_visit_annotations(struct compiler *c, arguments_ty args,
2078 expr_ty returns)
2079{
Yurii Karabas73019792020-11-25 12:43:18 +02002080 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002081 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002082
Yurii Karabas73019792020-11-25 12:43:18 +02002083 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 */
2085 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002086 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002087
Yurii Karabas73019792020-11-25 12:43:18 +02002088 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2089 return 0;
2090 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2091 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002092 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002093 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002094 args->vararg->annotation, &annotations_len))
2095 return 0;
2096 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2097 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002098 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002099 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002100 args->kwarg->annotation, &annotations_len))
2101 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 if (!return_str) {
2104 return_str = PyUnicode_InternFromString("return");
2105 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002106 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 }
Yurii Karabas73019792020-11-25 12:43:18 +02002108 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2109 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 }
2111
Yurii Karabas73019792020-11-25 12:43:18 +02002112 if (annotations_len) {
2113 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002114 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002116
Yurii Karabas73019792020-11-25 12:43:18 +02002117 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002118}
2119
2120static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002121compiler_visit_defaults(struct compiler *c, arguments_ty args)
2122{
2123 VISIT_SEQ(c, expr, args->defaults);
2124 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2125 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002126}
2127
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002128static Py_ssize_t
2129compiler_default_arguments(struct compiler *c, arguments_ty args)
2130{
2131 Py_ssize_t funcflags = 0;
2132 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002133 if (!compiler_visit_defaults(c, args))
2134 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002135 funcflags |= 0x01;
2136 }
2137 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002138 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002139 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002140 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002141 return -1;
2142 }
2143 else if (res > 0) {
2144 funcflags |= 0x02;
2145 }
2146 }
2147 return funcflags;
2148}
2149
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002151forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2152{
2153
2154 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2155 compiler_error(c, "cannot assign to __debug__");
2156 return 1;
2157 }
2158 return 0;
2159}
2160
2161static int
2162compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2163{
2164 if (arg != NULL) {
2165 if (forbidden_name(c, arg->arg, Store))
2166 return 0;
2167 }
2168 return 1;
2169}
2170
2171static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002172compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002173{
2174 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002175 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002176 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2177 return 0;
2178 }
2179 }
2180 return 1;
2181}
2182
2183static int
2184compiler_check_debug_args(struct compiler *c, arguments_ty args)
2185{
2186 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2187 return 0;
2188 if (!compiler_check_debug_args_seq(c, args->args))
2189 return 0;
2190 if (!compiler_check_debug_one_arg(c, args->vararg))
2191 return 0;
2192 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2193 return 0;
2194 if (!compiler_check_debug_one_arg(c, args->kwarg))
2195 return 0;
2196 return 1;
2197}
2198
2199static int
Yury Selivanov75445082015-05-11 22:57:16 -04002200compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002203 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002204 arguments_ty args;
2205 expr_ty returns;
2206 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002207 asdl_expr_seq* decos;
2208 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002209 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002210 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002211 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002212 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213
Yury Selivanov75445082015-05-11 22:57:16 -04002214 if (is_async) {
2215 assert(s->kind == AsyncFunctionDef_kind);
2216
2217 args = s->v.AsyncFunctionDef.args;
2218 returns = s->v.AsyncFunctionDef.returns;
2219 decos = s->v.AsyncFunctionDef.decorator_list;
2220 name = s->v.AsyncFunctionDef.name;
2221 body = s->v.AsyncFunctionDef.body;
2222
2223 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2224 } else {
2225 assert(s->kind == FunctionDef_kind);
2226
2227 args = s->v.FunctionDef.args;
2228 returns = s->v.FunctionDef.returns;
2229 decos = s->v.FunctionDef.decorator_list;
2230 name = s->v.FunctionDef.name;
2231 body = s->v.FunctionDef.body;
2232
2233 scope_type = COMPILER_SCOPE_FUNCTION;
2234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002235
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002236 if (!compiler_check_debug_args(c, args))
2237 return 0;
2238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (!compiler_decorators(c, decos))
2240 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002241
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002242 firstlineno = s->lineno;
2243 if (asdl_seq_LEN(decos)) {
2244 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2245 }
2246
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002247 funcflags = compiler_default_arguments(c, args);
2248 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002250 }
2251
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002252 annotations = compiler_visit_annotations(c, args, returns);
2253 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002254 return 0;
2255 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002256 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002257 funcflags |= 0x04;
2258 }
2259
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002260 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002261 return 0;
2262 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002263
INADA Naokicb41b272017-02-23 00:31:59 +09002264 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002265 if (c->c_optimize < 2) {
2266 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002267 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002268 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 compiler_exit_scope(c);
2270 return 0;
2271 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002274 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002276 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002277 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002278 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002280 qualname = c->u->u_qualname;
2281 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002283 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002284 Py_XDECREF(qualname);
2285 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002287 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002289 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002290 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 /* decorators */
2294 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2295 ADDOP_I(c, CALL_FUNCTION, 1);
2296 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002297
Yury Selivanov75445082015-05-11 22:57:16 -04002298 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299}
2300
2301static int
2302compiler_class(struct compiler *c, stmt_ty s)
2303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 PyCodeObject *co;
2305 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002306 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002307 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 if (!compiler_decorators(c, decos))
2310 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002311
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002312 firstlineno = s->lineno;
2313 if (asdl_seq_LEN(decos)) {
2314 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2315 }
2316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 /* ultimately generate code for:
2318 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2319 where:
2320 <func> is a function/closure created from the class body;
2321 it has a single argument (__locals__) where the dict
2322 (or MutableSequence) representing the locals is passed
2323 <name> is the class name
2324 <bases> is the positional arguments and *varargs argument
2325 <keywords> is the keyword arguments and **kwds argument
2326 This borrows from compiler_call.
2327 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002330 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002331 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 return 0;
2333 /* this block represents what we do in the new scope */
2334 {
2335 /* use the class name for name mangling */
2336 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002337 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 /* load (global) __name__ ... */
2339 str = PyUnicode_InternFromString("__name__");
2340 if (!str || !compiler_nameop(c, str, Load)) {
2341 Py_XDECREF(str);
2342 compiler_exit_scope(c);
2343 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002344 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 Py_DECREF(str);
2346 /* ... and store it as __module__ */
2347 str = PyUnicode_InternFromString("__module__");
2348 if (!str || !compiler_nameop(c, str, Store)) {
2349 Py_XDECREF(str);
2350 compiler_exit_scope(c);
2351 return 0;
2352 }
2353 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002354 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002355 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002356 str = PyUnicode_InternFromString("__qualname__");
2357 if (!str || !compiler_nameop(c, str, Store)) {
2358 Py_XDECREF(str);
2359 compiler_exit_scope(c);
2360 return 0;
2361 }
2362 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002364 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 compiler_exit_scope(c);
2366 return 0;
2367 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002368 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002369 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002370 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002371 str = PyUnicode_InternFromString("__class__");
2372 if (str == NULL) {
2373 compiler_exit_scope(c);
2374 return 0;
2375 }
2376 i = compiler_lookup_arg(c->u->u_cellvars, str);
2377 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002378 if (i < 0) {
2379 compiler_exit_scope(c);
2380 return 0;
2381 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002382 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002385 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002386 str = PyUnicode_InternFromString("__classcell__");
2387 if (!str || !compiler_nameop(c, str, Store)) {
2388 Py_XDECREF(str);
2389 compiler_exit_scope(c);
2390 return 0;
2391 }
2392 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002394 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002395 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002396 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002397 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002398 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002399 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* create the code object */
2401 co = assemble(c, 1);
2402 }
2403 /* leave the new scope */
2404 compiler_exit_scope(c);
2405 if (co == NULL)
2406 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 /* 2. load the 'build_class' function */
2409 ADDOP(c, LOAD_BUILD_CLASS);
2410
2411 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002412 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 Py_DECREF(co);
2414
2415 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002416 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417
2418 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002419 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return 0;
2421
2422 /* 6. apply decorators */
2423 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2424 ADDOP_I(c, CALL_FUNCTION, 1);
2425 }
2426
2427 /* 7. store into <name> */
2428 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2429 return 0;
2430 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002431}
2432
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002433/* Return 0 if the expression is a constant value except named singletons.
2434 Return 1 otherwise. */
2435static int
2436check_is_arg(expr_ty e)
2437{
2438 if (e->kind != Constant_kind) {
2439 return 1;
2440 }
2441 PyObject *value = e->v.Constant.value;
2442 return (value == Py_None
2443 || value == Py_False
2444 || value == Py_True
2445 || value == Py_Ellipsis);
2446}
2447
2448/* Check operands of identity chacks ("is" and "is not").
2449 Emit a warning if any operand is a constant except named singletons.
2450 Return 0 on error.
2451 */
2452static int
2453check_compare(struct compiler *c, expr_ty e)
2454{
2455 Py_ssize_t i, n;
2456 int left = check_is_arg(e->v.Compare.left);
2457 n = asdl_seq_LEN(e->v.Compare.ops);
2458 for (i = 0; i < n; i++) {
2459 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2460 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2461 if (op == Is || op == IsNot) {
2462 if (!right || !left) {
2463 const char *msg = (op == Is)
2464 ? "\"is\" with a literal. Did you mean \"==\"?"
2465 : "\"is not\" with a literal. Did you mean \"!=\"?";
2466 return compiler_warn(c, msg);
2467 }
2468 }
2469 left = right;
2470 }
2471 return 1;
2472}
2473
Mark Shannon9af0e472020-01-14 10:12:45 +00002474static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002475{
Mark Shannon9af0e472020-01-14 10:12:45 +00002476 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002477 switch (op) {
2478 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002479 cmp = Py_EQ;
2480 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002481 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002482 cmp = Py_NE;
2483 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002484 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002485 cmp = Py_LT;
2486 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002487 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002488 cmp = Py_LE;
2489 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002490 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002491 cmp = Py_GT;
2492 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002493 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002494 cmp = Py_GE;
2495 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002496 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002497 ADDOP_I(c, IS_OP, 0);
2498 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002499 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002500 ADDOP_I(c, IS_OP, 1);
2501 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002502 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002503 ADDOP_I(c, CONTAINS_OP, 0);
2504 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002505 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002506 ADDOP_I(c, CONTAINS_OP, 1);
2507 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002508 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002509 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002510 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002511 ADDOP_I(c, COMPARE_OP, cmp);
2512 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002513}
2514
Mark Shannon9af0e472020-01-14 10:12:45 +00002515
2516
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002517static int
2518compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2519{
2520 switch (e->kind) {
2521 case UnaryOp_kind:
2522 if (e->v.UnaryOp.op == Not)
2523 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2524 /* fallback to general implementation */
2525 break;
2526 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002527 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002528 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2529 assert(n >= 0);
2530 int cond2 = e->v.BoolOp.op == Or;
2531 basicblock *next2 = next;
2532 if (!cond2 != !cond) {
2533 next2 = compiler_new_block(c);
2534 if (next2 == NULL)
2535 return 0;
2536 }
2537 for (i = 0; i < n; ++i) {
2538 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2539 return 0;
2540 }
2541 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2542 return 0;
2543 if (next2 != next)
2544 compiler_use_next_block(c, next2);
2545 return 1;
2546 }
2547 case IfExp_kind: {
2548 basicblock *end, *next2;
2549 end = compiler_new_block(c);
2550 if (end == NULL)
2551 return 0;
2552 next2 = compiler_new_block(c);
2553 if (next2 == NULL)
2554 return 0;
2555 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2556 return 0;
2557 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2558 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002559 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002560 compiler_use_next_block(c, next2);
2561 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2562 return 0;
2563 compiler_use_next_block(c, end);
2564 return 1;
2565 }
2566 case Compare_kind: {
2567 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2568 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002569 if (!check_compare(c, e)) {
2570 return 0;
2571 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002572 basicblock *cleanup = compiler_new_block(c);
2573 if (cleanup == NULL)
2574 return 0;
2575 VISIT(c, expr, e->v.Compare.left);
2576 for (i = 0; i < n; i++) {
2577 VISIT(c, expr,
2578 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2579 ADDOP(c, DUP_TOP);
2580 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002581 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002582 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002583 NEXT_BLOCK(c);
2584 }
2585 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002586 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002587 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002588 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002589 basicblock *end = compiler_new_block(c);
2590 if (end == NULL)
2591 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002592 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002593 compiler_use_next_block(c, cleanup);
2594 ADDOP(c, POP_TOP);
2595 if (!cond) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002596 ADDOP_JUMP(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002597 }
2598 compiler_use_next_block(c, end);
2599 return 1;
2600 }
2601 /* fallback to general implementation */
2602 break;
2603 }
2604 default:
2605 /* fallback to general implementation */
2606 break;
2607 }
2608
2609 /* general implementation */
2610 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002611 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002612 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002613 return 1;
2614}
2615
2616static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002617compiler_ifexp(struct compiler *c, expr_ty e)
2618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 basicblock *end, *next;
2620
2621 assert(e->kind == IfExp_kind);
2622 end = compiler_new_block(c);
2623 if (end == NULL)
2624 return 0;
2625 next = compiler_new_block(c);
2626 if (next == NULL)
2627 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002628 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2629 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002631 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 compiler_use_next_block(c, next);
2633 VISIT(c, expr, e->v.IfExp.orelse);
2634 compiler_use_next_block(c, end);
2635 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002636}
2637
2638static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639compiler_lambda(struct compiler *c, expr_ty e)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002642 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002644 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 arguments_ty args = e->v.Lambda.args;
2646 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002648 if (!compiler_check_debug_args(c, args))
2649 return 0;
2650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 if (!name) {
2652 name = PyUnicode_InternFromString("<lambda>");
2653 if (!name)
2654 return 0;
2655 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002657 funcflags = compiler_default_arguments(c, args);
2658 if (funcflags == -1) {
2659 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002661
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002662 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002663 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 /* Make None the first constant, so the lambda can't have a
2667 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002668 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002672 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2674 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2675 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002676 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 }
2678 else {
2679 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002680 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002682 qualname = c->u->u_qualname;
2683 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002685 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002688 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002689 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 Py_DECREF(co);
2691
2692 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693}
2694
2695static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696compiler_if(struct compiler *c, stmt_ty s)
2697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 assert(s->kind == If_kind);
2700 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002701 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002703 }
2704 if (asdl_seq_LEN(s->v.If.orelse)) {
2705 next = compiler_new_block(c);
2706 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002707 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002708 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002709 }
2710 else {
2711 next = end;
2712 }
2713 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2714 return 0;
2715 }
2716 VISIT_SEQ(c, stmt, s->v.If.body);
2717 if (asdl_seq_LEN(s->v.If.orelse)) {
2718 ADDOP_JUMP(c, JUMP_FORWARD, end);
2719 compiler_use_next_block(c, next);
2720 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 }
2722 compiler_use_next_block(c, end);
2723 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002724}
2725
2726static int
2727compiler_for(struct compiler *c, stmt_ty s)
2728{
Mark Shannon5977a792020-12-02 13:31:40 +00002729 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002732 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 cleanup = compiler_new_block(c);
2734 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002735 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002737 }
2738 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002740 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 VISIT(c, expr, s->v.For.iter);
2742 ADDOP(c, GET_ITER);
2743 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002744 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002745 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 VISIT(c, expr, s->v.For.target);
2747 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002748 /* Mark jump as artificial */
2749 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002750 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002752
2753 compiler_pop_fblock(c, FOR_LOOP, start);
2754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 VISIT_SEQ(c, stmt, s->v.For.orelse);
2756 compiler_use_next_block(c, end);
2757 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758}
2759
Yury Selivanov75445082015-05-11 22:57:16 -04002760
2761static int
2762compiler_async_for(struct compiler *c, stmt_ty s)
2763{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002764 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002765 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002766 c->u->u_ste->ste_coroutine = 1;
2767 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002768 return compiler_error(c, "'async for' outside async function");
2769 }
2770
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002771 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002772 except = compiler_new_block(c);
2773 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002774
Mark Shannonfee55262019-11-21 09:11:43 +00002775 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002776 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002777 }
Yury Selivanov75445082015-05-11 22:57:16 -04002778 VISIT(c, expr, s->v.AsyncFor.iter);
2779 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002780
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002781 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002782 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002783 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002784 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002785 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002786 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002787 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002788 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002789 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002790 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002791
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002792 /* Success block for __anext__ */
2793 VISIT(c, expr, s->v.AsyncFor.target);
2794 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002795 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002796
2797 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002798
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002799 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002800 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002801
2802 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002803 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002804
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002805 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002806 VISIT_SEQ(c, stmt, s->v.For.orelse);
2807
2808 compiler_use_next_block(c, end);
2809
2810 return 1;
2811}
2812
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002813static int
2814compiler_while(struct compiler *c, stmt_ty s)
2815{
Mark Shannon266b4622020-11-17 19:30:14 +00002816 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002818 body = compiler_new_block(c);
2819 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002821 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002822 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002825 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002828 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2829 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002830 }
2831
2832 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002834 SET_LOC(c, s);
2835 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2836 return 0;
2837 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002839 compiler_pop_fblock(c, WHILE_LOOP, loop);
2840
Mark Shannon266b4622020-11-17 19:30:14 +00002841 compiler_use_next_block(c, anchor);
2842 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848}
2849
2850static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002851compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002853 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002854 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002855 if (c->u->u_ste->ste_type != FunctionBlock)
2856 return compiler_error(c, "'return' outside function");
2857 if (s->v.Return.value != NULL &&
2858 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2859 {
2860 return compiler_error(
2861 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002862 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002863 if (preserve_tos) {
2864 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002865 } else {
2866 /* Emit instruction with line number for expression */
2867 if (s->v.Return.value != NULL) {
2868 SET_LOC(c, s->v.Return.value);
2869 ADDOP(c, NOP);
2870 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002871 }
Mark Shannonfee55262019-11-21 09:11:43 +00002872 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2873 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002874 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002875 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002876 }
2877 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00002878 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002879 }
2880 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002881 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884}
2885
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002886static int
2887compiler_break(struct compiler *c)
2888{
Mark Shannonfee55262019-11-21 09:11:43 +00002889 struct fblockinfo *loop = NULL;
2890 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2891 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002892 }
Mark Shannonfee55262019-11-21 09:11:43 +00002893 if (loop == NULL) {
2894 return compiler_error(c, "'break' outside loop");
2895 }
2896 if (!compiler_unwind_fblock(c, loop, 0)) {
2897 return 0;
2898 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002899 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002900 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002901 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002902}
2903
2904static int
2905compiler_continue(struct compiler *c)
2906{
Mark Shannonfee55262019-11-21 09:11:43 +00002907 struct fblockinfo *loop = NULL;
2908 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2909 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002910 }
Mark Shannonfee55262019-11-21 09:11:43 +00002911 if (loop == NULL) {
2912 return compiler_error(c, "'continue' not properly in loop");
2913 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002914 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002915 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002916 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002917}
2918
2919
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921
2922 SETUP_FINALLY L
2923 <code for body>
2924 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002925 <code for finalbody>
2926 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002927 L:
2928 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002929 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002931 The special instructions use the block stack. Each block
2932 stack entry contains the instruction that created it (here
2933 SETUP_FINALLY), the level of the value stack at the time the
2934 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002936 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 Pushes the current value stack level and the label
2938 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002939 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002940 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002942 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002943 when a SETUP_FINALLY entry is found, the raised and the caught
2944 exceptions are pushed onto the value stack (and the exception
2945 condition is cleared), and the interpreter jumps to the label
2946 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002947*/
2948
2949static int
2950compiler_try_finally(struct compiler *c, stmt_ty s)
2951{
Mark Shannonfee55262019-11-21 09:11:43 +00002952 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002954 body = compiler_new_block(c);
2955 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002956 exit = compiler_new_block(c);
2957 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002959
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002960 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002961 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002963 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002964 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002965 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2966 if (!compiler_try_except(c, s))
2967 return 0;
2968 }
2969 else {
2970 VISIT_SEQ(c, stmt, s->v.Try.body);
2971 }
Mark Shannon56aa20f2020-12-14 10:19:10 +00002972 /* Mark code as artificial */
2973 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002974 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002975 compiler_pop_fblock(c, FINALLY_TRY, body);
2976 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon582aaf12020-08-04 17:30:11 +01002977 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00002978 /* `finally` block */
2979 compiler_use_next_block(c, end);
2980 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2981 return 0;
2982 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2983 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00002984 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00002985 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002987}
2988
2989/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002990 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991 (The contents of the value stack is shown in [], with the top
2992 at the right; 'tb' is trace-back info, 'val' the exception's
2993 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994
2995 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002996 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 [] <code for S>
2998 [] POP_BLOCK
2999 [] JUMP_FORWARD L0
3000
3001 [tb, val, exc] L1: DUP )
3002 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003003 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 [tb, val, exc] POP
3005 [tb, val] <assign to V1> (or POP if no V1)
3006 [tb] POP
3007 [] <code for S1>
3008 JUMP_FORWARD L0
3009
3010 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003011 .............................etc.......................
3012
Mark Shannonfee55262019-11-21 09:11:43 +00003013 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014
3015 [] L0: <next statement>
3016
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003017 Of course, parts are not generated if Vi or Ei is not present.
3018*/
3019static int
3020compiler_try_except(struct compiler *c, stmt_ty s)
3021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003023 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 body = compiler_new_block(c);
3026 except = compiler_new_block(c);
3027 orelse = compiler_new_block(c);
3028 end = compiler_new_block(c);
3029 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3030 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003031 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003033 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003035 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 ADDOP(c, POP_BLOCK);
Mark Shannon02d126a2020-09-25 14:04:19 +01003037 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon582aaf12020-08-04 17:30:11 +01003038 ADDOP_JUMP(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003039 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003041 /* Runtime will push a block here, so we need to account for that */
3042 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3043 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 for (i = 0; i < n; i++) {
3045 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003046 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047 if (!handler->v.ExceptHandler.type && i < n-1)
3048 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003049 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 except = compiler_new_block(c);
3051 if (except == NULL)
3052 return 0;
3053 if (handler->v.ExceptHandler.type) {
3054 ADDOP(c, DUP_TOP);
3055 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003056 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003057 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 }
3059 ADDOP(c, POP_TOP);
3060 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003061 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003062
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003063 cleanup_end = compiler_new_block(c);
3064 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003065 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003066 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003067 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003068
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003069 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3070 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003072 /*
3073 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003074 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003075 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003076 try:
3077 # body
3078 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003079 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003080 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003081 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003082
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003083 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003084 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003086 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003088
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 /* second # body */
3090 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003091 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003092 ADDOP(c, POP_BLOCK);
3093 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003094 /* name = None; del name; # Mark as artificial */
3095 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003096 ADDOP_LOAD_CONST(c, Py_None);
3097 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3098 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003099 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100
Mark Shannonfee55262019-11-21 09:11:43 +00003101 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003102 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103
Mark Shannon877df852020-11-12 09:43:29 +00003104 /* name = None; del name; # Mark as artificial */
3105 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003106 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003107 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003108 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109
Mark Shannonbf353f32020-12-17 13:55:28 +00003110 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003111 }
3112 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003113 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003116 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003117 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118
Guido van Rossumb940e112007-01-10 16:19:56 +00003119 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003120 ADDOP(c, POP_TOP);
3121 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003122 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003123 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003125 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003126 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003127 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 compiler_use_next_block(c, except);
3130 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003131 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003132 /* Mark as artificial */
3133 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003134 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003136 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137 compiler_use_next_block(c, end);
3138 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139}
3140
3141static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003142compiler_try(struct compiler *c, stmt_ty s) {
3143 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3144 return compiler_try_finally(c, s);
3145 else
3146 return compiler_try_except(c, s);
3147}
3148
3149
3150static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003151compiler_import_as(struct compiler *c, identifier name, identifier asname)
3152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003153 /* The IMPORT_NAME opcode was already generated. This function
3154 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003157 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003159 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3160 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003161 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003162 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003163 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003165 while (1) {
3166 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003168 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003169 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003170 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003171 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003172 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003173 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003174 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003175 if (dot == -1) {
3176 break;
3177 }
3178 ADDOP(c, ROT_TWO);
3179 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003180 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003181 if (!compiler_nameop(c, asname, Store)) {
3182 return 0;
3183 }
3184 ADDOP(c, POP_TOP);
3185 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 }
3187 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003188}
3189
3190static int
3191compiler_import(struct compiler *c, stmt_ty s)
3192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 /* The Import node stores a module name like a.b.c as a single
3194 string. This is convenient for all cases except
3195 import a.b.c as d
3196 where we need to parse that string to extract the individual
3197 module names.
3198 XXX Perhaps change the representation to make this case simpler?
3199 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003200 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003201
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003202 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 for (i = 0; i < n; i++) {
3204 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3205 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003206
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003207 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003208 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 if (alias->asname) {
3212 r = compiler_import_as(c, alias->name, alias->asname);
3213 if (!r)
3214 return r;
3215 }
3216 else {
3217 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003218 Py_ssize_t dot = PyUnicode_FindChar(
3219 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003220 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003221 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003222 if (tmp == NULL)
3223 return 0;
3224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003225 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003226 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 Py_DECREF(tmp);
3228 }
3229 if (!r)
3230 return r;
3231 }
3232 }
3233 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003234}
3235
3236static int
3237compiler_from_import(struct compiler *c, stmt_ty s)
3238{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003239 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003240 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 if (!empty_string) {
3244 empty_string = PyUnicode_FromString("");
3245 if (!empty_string)
3246 return 0;
3247 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003248
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003249 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003250
3251 names = PyTuple_New(n);
3252 if (!names)
3253 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 /* build up the names */
3256 for (i = 0; i < n; i++) {
3257 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3258 Py_INCREF(alias->name);
3259 PyTuple_SET_ITEM(names, i, alias->name);
3260 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003263 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 Py_DECREF(names);
3265 return compiler_error(c, "from __future__ imports must occur "
3266 "at the beginning of the file");
3267 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003268 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 if (s->v.ImportFrom.module) {
3271 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3272 }
3273 else {
3274 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3275 }
3276 for (i = 0; i < n; i++) {
3277 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3278 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003280 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 assert(n == 1);
3282 ADDOP(c, IMPORT_STAR);
3283 return 1;
3284 }
3285
3286 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3287 store_name = alias->name;
3288 if (alias->asname)
3289 store_name = alias->asname;
3290
3291 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 return 0;
3293 }
3294 }
3295 /* remove imported module */
3296 ADDOP(c, POP_TOP);
3297 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003298}
3299
3300static int
3301compiler_assert(struct compiler *c, stmt_ty s)
3302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003304
Georg Brandl8334fd92010-12-04 10:26:46 +00003305 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003308 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3309 {
3310 if (!compiler_warn(c, "assertion is always true, "
3311 "perhaps remove parentheses?"))
3312 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003313 return 0;
3314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 end = compiler_new_block(c);
3317 if (end == NULL)
3318 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003319 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3320 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003321 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 if (s->v.Assert.msg) {
3323 VISIT(c, expr, s->v.Assert.msg);
3324 ADDOP_I(c, CALL_FUNCTION, 1);
3325 }
3326 ADDOP_I(c, RAISE_VARARGS, 1);
3327 compiler_use_next_block(c, end);
3328 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003329}
3330
3331static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003332compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3333{
3334 if (c->c_interactive && c->c_nestlevel <= 1) {
3335 VISIT(c, expr, value);
3336 ADDOP(c, PRINT_EXPR);
3337 return 1;
3338 }
3339
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003340 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003341 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003342 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003343 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003344 }
3345
3346 VISIT(c, expr, value);
3347 ADDOP(c, POP_TOP);
3348 return 1;
3349}
3350
3351static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003352compiler_visit_stmt(struct compiler *c, stmt_ty s)
3353{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003354 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003357 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003359 switch (s->kind) {
3360 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003361 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003362 case ClassDef_kind:
3363 return compiler_class(c, s);
3364 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003365 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 case Delete_kind:
3367 VISIT_SEQ(c, expr, s->v.Delete.targets)
3368 break;
3369 case Assign_kind:
3370 n = asdl_seq_LEN(s->v.Assign.targets);
3371 VISIT(c, expr, s->v.Assign.value);
3372 for (i = 0; i < n; i++) {
3373 if (i < n - 1)
3374 ADDOP(c, DUP_TOP);
3375 VISIT(c, expr,
3376 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3377 }
3378 break;
3379 case AugAssign_kind:
3380 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003381 case AnnAssign_kind:
3382 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003383 case For_kind:
3384 return compiler_for(c, s);
3385 case While_kind:
3386 return compiler_while(c, s);
3387 case If_kind:
3388 return compiler_if(c, s);
3389 case Raise_kind:
3390 n = 0;
3391 if (s->v.Raise.exc) {
3392 VISIT(c, expr, s->v.Raise.exc);
3393 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003394 if (s->v.Raise.cause) {
3395 VISIT(c, expr, s->v.Raise.cause);
3396 n++;
3397 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003398 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003399 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003400 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003401 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003402 case Try_kind:
3403 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003404 case Assert_kind:
3405 return compiler_assert(c, s);
3406 case Import_kind:
3407 return compiler_import(c, s);
3408 case ImportFrom_kind:
3409 return compiler_from_import(c, s);
3410 case Global_kind:
3411 case Nonlocal_kind:
3412 break;
3413 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003414 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003415 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003416 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 break;
3418 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003419 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 case Continue_kind:
3421 return compiler_continue(c);
3422 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003423 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003424 case AsyncFunctionDef_kind:
3425 return compiler_function(c, s, 1);
3426 case AsyncWith_kind:
3427 return compiler_async_with(c, s, 0);
3428 case AsyncFor_kind:
3429 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 }
Yury Selivanov75445082015-05-11 22:57:16 -04003431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003433}
3434
3435static int
3436unaryop(unaryop_ty op)
3437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 switch (op) {
3439 case Invert:
3440 return UNARY_INVERT;
3441 case Not:
3442 return UNARY_NOT;
3443 case UAdd:
3444 return UNARY_POSITIVE;
3445 case USub:
3446 return UNARY_NEGATIVE;
3447 default:
3448 PyErr_Format(PyExc_SystemError,
3449 "unary op %d should not be possible", op);
3450 return 0;
3451 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003452}
3453
3454static int
Andy Lester76d58772020-03-10 21:18:12 -05003455binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003457 switch (op) {
3458 case Add:
3459 return BINARY_ADD;
3460 case Sub:
3461 return BINARY_SUBTRACT;
3462 case Mult:
3463 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003464 case MatMult:
3465 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 case Div:
3467 return BINARY_TRUE_DIVIDE;
3468 case Mod:
3469 return BINARY_MODULO;
3470 case Pow:
3471 return BINARY_POWER;
3472 case LShift:
3473 return BINARY_LSHIFT;
3474 case RShift:
3475 return BINARY_RSHIFT;
3476 case BitOr:
3477 return BINARY_OR;
3478 case BitXor:
3479 return BINARY_XOR;
3480 case BitAnd:
3481 return BINARY_AND;
3482 case FloorDiv:
3483 return BINARY_FLOOR_DIVIDE;
3484 default:
3485 PyErr_Format(PyExc_SystemError,
3486 "binary op %d should not be possible", op);
3487 return 0;
3488 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003489}
3490
3491static int
Andy Lester76d58772020-03-10 21:18:12 -05003492inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003494 switch (op) {
3495 case Add:
3496 return INPLACE_ADD;
3497 case Sub:
3498 return INPLACE_SUBTRACT;
3499 case Mult:
3500 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003501 case MatMult:
3502 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003503 case Div:
3504 return INPLACE_TRUE_DIVIDE;
3505 case Mod:
3506 return INPLACE_MODULO;
3507 case Pow:
3508 return INPLACE_POWER;
3509 case LShift:
3510 return INPLACE_LSHIFT;
3511 case RShift:
3512 return INPLACE_RSHIFT;
3513 case BitOr:
3514 return INPLACE_OR;
3515 case BitXor:
3516 return INPLACE_XOR;
3517 case BitAnd:
3518 return INPLACE_AND;
3519 case FloorDiv:
3520 return INPLACE_FLOOR_DIVIDE;
3521 default:
3522 PyErr_Format(PyExc_SystemError,
3523 "inplace binary op %d should not be possible", op);
3524 return 0;
3525 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003526}
3527
3528static int
3529compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3530{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003531 int op, scope;
3532 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003533 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003535 PyObject *dict = c->u->u_names;
3536 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003537
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003538 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3539 !_PyUnicode_EqualToASCIIString(name, "True") &&
3540 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003541
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003542 if (forbidden_name(c, name, ctx))
3543 return 0;
3544
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003545 mangled = _Py_Mangle(c->u->u_private, name);
3546 if (!mangled)
3547 return 0;
3548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003549 op = 0;
3550 optype = OP_NAME;
3551 scope = PyST_GetScope(c->u->u_ste, mangled);
3552 switch (scope) {
3553 case FREE:
3554 dict = c->u->u_freevars;
3555 optype = OP_DEREF;
3556 break;
3557 case CELL:
3558 dict = c->u->u_cellvars;
3559 optype = OP_DEREF;
3560 break;
3561 case LOCAL:
3562 if (c->u->u_ste->ste_type == FunctionBlock)
3563 optype = OP_FAST;
3564 break;
3565 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003566 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 optype = OP_GLOBAL;
3568 break;
3569 case GLOBAL_EXPLICIT:
3570 optype = OP_GLOBAL;
3571 break;
3572 default:
3573 /* scope can be 0 */
3574 break;
3575 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003578 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003580 switch (optype) {
3581 case OP_DEREF:
3582 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003583 case Load:
3584 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3585 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003586 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003587 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003588 }
3589 break;
3590 case OP_FAST:
3591 switch (ctx) {
3592 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003593 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003594 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003595 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003596 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 return 1;
3598 case OP_GLOBAL:
3599 switch (ctx) {
3600 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003601 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 }
3604 break;
3605 case OP_NAME:
3606 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003607 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003608 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003610 }
3611 break;
3612 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003615 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003616 Py_DECREF(mangled);
3617 if (arg < 0)
3618 return 0;
3619 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003620}
3621
3622static int
3623compiler_boolop(struct compiler *c, expr_ty e)
3624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003625 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003626 int jumpi;
3627 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003628 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003630 assert(e->kind == BoolOp_kind);
3631 if (e->v.BoolOp.op == And)
3632 jumpi = JUMP_IF_FALSE_OR_POP;
3633 else
3634 jumpi = JUMP_IF_TRUE_OR_POP;
3635 end = compiler_new_block(c);
3636 if (end == NULL)
3637 return 0;
3638 s = e->v.BoolOp.values;
3639 n = asdl_seq_LEN(s) - 1;
3640 assert(n >= 0);
3641 for (i = 0; i < n; ++i) {
3642 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003643 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003644 basicblock *next = compiler_new_block(c);
3645 if (next == NULL) {
3646 return 0;
3647 }
3648 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003649 }
3650 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3651 compiler_use_next_block(c, end);
3652 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003653}
3654
3655static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003656starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003657 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003658{
3659 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003660 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003661 if (n > 2 && are_all_items_const(elts, 0, n)) {
3662 PyObject *folded = PyTuple_New(n);
3663 if (folded == NULL) {
3664 return 0;
3665 }
3666 PyObject *val;
3667 for (i = 0; i < n; i++) {
3668 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3669 Py_INCREF(val);
3670 PyTuple_SET_ITEM(folded, i, val);
3671 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003672 if (tuple) {
3673 ADDOP_LOAD_CONST_NEW(c, folded);
3674 } else {
3675 if (add == SET_ADD) {
3676 Py_SETREF(folded, PyFrozenSet_New(folded));
3677 if (folded == NULL) {
3678 return 0;
3679 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003680 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003681 ADDOP_I(c, build, pushed);
3682 ADDOP_LOAD_CONST_NEW(c, folded);
3683 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003684 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003685 return 1;
3686 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003687
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003688 for (i = 0; i < n; i++) {
3689 expr_ty elt = asdl_seq_GET(elts, i);
3690 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003691 seen_star = 1;
3692 }
3693 }
3694 if (seen_star) {
3695 seen_star = 0;
3696 for (i = 0; i < n; i++) {
3697 expr_ty elt = asdl_seq_GET(elts, i);
3698 if (elt->kind == Starred_kind) {
3699 if (seen_star == 0) {
3700 ADDOP_I(c, build, i+pushed);
3701 seen_star = 1;
3702 }
3703 VISIT(c, expr, elt->v.Starred.value);
3704 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003705 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003706 else {
3707 VISIT(c, expr, elt);
3708 if (seen_star) {
3709 ADDOP_I(c, add, 1);
3710 }
3711 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003712 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003713 assert(seen_star);
3714 if (tuple) {
3715 ADDOP(c, LIST_TO_TUPLE);
3716 }
3717 }
3718 else {
3719 for (i = 0; i < n; i++) {
3720 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003721 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003722 }
3723 if (tuple) {
3724 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3725 } else {
3726 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003727 }
3728 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003729 return 1;
3730}
3731
3732static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003733assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003734{
3735 Py_ssize_t n = asdl_seq_LEN(elts);
3736 Py_ssize_t i;
3737 int seen_star = 0;
3738 for (i = 0; i < n; i++) {
3739 expr_ty elt = asdl_seq_GET(elts, i);
3740 if (elt->kind == Starred_kind && !seen_star) {
3741 if ((i >= (1 << 8)) ||
3742 (n-i-1 >= (INT_MAX >> 8)))
3743 return compiler_error(c,
3744 "too many expressions in "
3745 "star-unpacking assignment");
3746 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3747 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003748 }
3749 else if (elt->kind == Starred_kind) {
3750 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003751 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003752 }
3753 }
3754 if (!seen_star) {
3755 ADDOP_I(c, UNPACK_SEQUENCE, n);
3756 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003757 for (i = 0; i < n; i++) {
3758 expr_ty elt = asdl_seq_GET(elts, i);
3759 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3760 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003761 return 1;
3762}
3763
3764static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003765compiler_list(struct compiler *c, expr_ty e)
3766{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003767 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003768 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003769 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003770 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003771 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003772 return starunpack_helper(c, elts, 0, BUILD_LIST,
3773 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003775 else
3776 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003777 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003778}
3779
3780static int
3781compiler_tuple(struct compiler *c, expr_ty e)
3782{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003783 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003784 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003785 return assignment_helper(c, elts);
3786 }
3787 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003788 return starunpack_helper(c, elts, 0, BUILD_LIST,
3789 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003790 }
3791 else
3792 VISIT_SEQ(c, expr, elts);
3793 return 1;
3794}
3795
3796static int
3797compiler_set(struct compiler *c, expr_ty e)
3798{
Mark Shannon13bc1392020-01-23 09:25:17 +00003799 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3800 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003801}
3802
3803static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003804are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003805{
3806 Py_ssize_t i;
3807 for (i = begin; i < end; i++) {
3808 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003809 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003810 return 0;
3811 }
3812 return 1;
3813}
3814
3815static int
3816compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3817{
3818 Py_ssize_t i, n = end - begin;
3819 PyObject *keys, *key;
3820 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3821 for (i = begin; i < end; i++) {
3822 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3823 }
3824 keys = PyTuple_New(n);
3825 if (keys == NULL) {
3826 return 0;
3827 }
3828 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003829 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003830 Py_INCREF(key);
3831 PyTuple_SET_ITEM(keys, i - begin, key);
3832 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003833 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003834 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3835 }
3836 else {
3837 for (i = begin; i < end; i++) {
3838 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3839 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3840 }
3841 ADDOP_I(c, BUILD_MAP, n);
3842 }
3843 return 1;
3844}
3845
3846static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003847compiler_dict(struct compiler *c, expr_ty e)
3848{
Victor Stinner976bb402016-03-23 11:36:19 +01003849 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003850 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003851 int is_unpacking = 0;
3852 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003853 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003854 elements = 0;
3855 for (i = 0; i < n; i++) {
3856 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003857 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003858 if (elements) {
3859 if (!compiler_subdict(c, e, i - elements, i)) {
3860 return 0;
3861 }
3862 if (have_dict) {
3863 ADDOP_I(c, DICT_UPDATE, 1);
3864 }
3865 have_dict = 1;
3866 elements = 0;
3867 }
3868 if (have_dict == 0) {
3869 ADDOP_I(c, BUILD_MAP, 0);
3870 have_dict = 1;
3871 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003872 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003873 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003874 }
3875 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003876 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003877 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003878 return 0;
3879 }
3880 if (have_dict) {
3881 ADDOP_I(c, DICT_UPDATE, 1);
3882 }
3883 have_dict = 1;
3884 elements = 0;
3885 }
3886 else {
3887 elements++;
3888 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003889 }
3890 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003891 if (elements) {
3892 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003893 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003894 }
3895 if (have_dict) {
3896 ADDOP_I(c, DICT_UPDATE, 1);
3897 }
3898 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003899 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003900 if (!have_dict) {
3901 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 }
3903 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003904}
3905
3906static int
3907compiler_compare(struct compiler *c, expr_ty e)
3908{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003909 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003910
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003911 if (!check_compare(c, e)) {
3912 return 0;
3913 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003915 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3916 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3917 if (n == 0) {
3918 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003919 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003920 }
3921 else {
3922 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 if (cleanup == NULL)
3924 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003925 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003926 VISIT(c, expr,
3927 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003928 ADDOP(c, DUP_TOP);
3929 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003930 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003931 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003932 NEXT_BLOCK(c);
3933 }
3934 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003935 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 basicblock *end = compiler_new_block(c);
3937 if (end == NULL)
3938 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003939 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 compiler_use_next_block(c, cleanup);
3941 ADDOP(c, ROT_TWO);
3942 ADDOP(c, POP_TOP);
3943 compiler_use_next_block(c, end);
3944 }
3945 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003946}
3947
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003948static PyTypeObject *
3949infer_type(expr_ty e)
3950{
3951 switch (e->kind) {
3952 case Tuple_kind:
3953 return &PyTuple_Type;
3954 case List_kind:
3955 case ListComp_kind:
3956 return &PyList_Type;
3957 case Dict_kind:
3958 case DictComp_kind:
3959 return &PyDict_Type;
3960 case Set_kind:
3961 case SetComp_kind:
3962 return &PySet_Type;
3963 case GeneratorExp_kind:
3964 return &PyGen_Type;
3965 case Lambda_kind:
3966 return &PyFunction_Type;
3967 case JoinedStr_kind:
3968 case FormattedValue_kind:
3969 return &PyUnicode_Type;
3970 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003971 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003972 default:
3973 return NULL;
3974 }
3975}
3976
3977static int
3978check_caller(struct compiler *c, expr_ty e)
3979{
3980 switch (e->kind) {
3981 case Constant_kind:
3982 case Tuple_kind:
3983 case List_kind:
3984 case ListComp_kind:
3985 case Dict_kind:
3986 case DictComp_kind:
3987 case Set_kind:
3988 case SetComp_kind:
3989 case GeneratorExp_kind:
3990 case JoinedStr_kind:
3991 case FormattedValue_kind:
3992 return compiler_warn(c, "'%.200s' object is not callable; "
3993 "perhaps you missed a comma?",
3994 infer_type(e)->tp_name);
3995 default:
3996 return 1;
3997 }
3998}
3999
4000static int
4001check_subscripter(struct compiler *c, expr_ty e)
4002{
4003 PyObject *v;
4004
4005 switch (e->kind) {
4006 case Constant_kind:
4007 v = e->v.Constant.value;
4008 if (!(v == Py_None || v == Py_Ellipsis ||
4009 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4010 PyAnySet_Check(v)))
4011 {
4012 return 1;
4013 }
4014 /* fall through */
4015 case Set_kind:
4016 case SetComp_kind:
4017 case GeneratorExp_kind:
4018 case Lambda_kind:
4019 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4020 "perhaps you missed a comma?",
4021 infer_type(e)->tp_name);
4022 default:
4023 return 1;
4024 }
4025}
4026
4027static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004028check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004029{
4030 PyObject *v;
4031
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004032 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004033 if (index_type == NULL
4034 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4035 || index_type == &PySlice_Type) {
4036 return 1;
4037 }
4038
4039 switch (e->kind) {
4040 case Constant_kind:
4041 v = e->v.Constant.value;
4042 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4043 return 1;
4044 }
4045 /* fall through */
4046 case Tuple_kind:
4047 case List_kind:
4048 case ListComp_kind:
4049 case JoinedStr_kind:
4050 case FormattedValue_kind:
4051 return compiler_warn(c, "%.200s indices must be integers or slices, "
4052 "not %.200s; "
4053 "perhaps you missed a comma?",
4054 infer_type(e)->tp_name,
4055 index_type->tp_name);
4056 default:
4057 return 1;
4058 }
4059}
4060
Zackery Spytz97f5de02019-03-22 01:30:32 -06004061// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004062static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004063maybe_optimize_method_call(struct compiler *c, expr_ty e)
4064{
4065 Py_ssize_t argsl, i;
4066 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004067 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004068
4069 /* Check that the call node is an attribute access, and that
4070 the call doesn't have keyword parameters. */
4071 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4072 asdl_seq_LEN(e->v.Call.keywords))
4073 return -1;
4074
4075 /* Check that there are no *varargs types of arguments. */
4076 argsl = asdl_seq_LEN(args);
4077 for (i = 0; i < argsl; i++) {
4078 expr_ty elt = asdl_seq_GET(args, i);
4079 if (elt->kind == Starred_kind) {
4080 return -1;
4081 }
4082 }
4083
4084 /* Alright, we can optimize the code. */
4085 VISIT(c, expr, meth->v.Attribute.value);
4086 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4087 VISIT_SEQ(c, expr, e->v.Call.args);
4088 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4089 return 1;
4090}
4091
4092static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004093validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004094{
4095 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4096 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004097 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4098 if (key->arg == NULL) {
4099 continue;
4100 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004101 if (forbidden_name(c, key->arg, Store)) {
4102 return -1;
4103 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004104 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004105 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4106 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4107 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4108 if (msg == NULL) {
4109 return -1;
4110 }
4111 c->u->u_col_offset = other->col_offset;
4112 compiler_error(c, PyUnicode_AsUTF8(msg));
4113 Py_DECREF(msg);
4114 return -1;
4115 }
4116 }
4117 }
4118 return 0;
4119}
4120
4121static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004122compiler_call(struct compiler *c, expr_ty e)
4123{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004124 int ret = maybe_optimize_method_call(c, e);
4125 if (ret >= 0) {
4126 return ret;
4127 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004128 if (!check_caller(c, e->v.Call.func)) {
4129 return 0;
4130 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004131 VISIT(c, expr, e->v.Call.func);
4132 return compiler_call_helper(c, 0,
4133 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004134 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004135}
4136
Eric V. Smith235a6f02015-09-19 14:51:32 -04004137static int
4138compiler_joined_str(struct compiler *c, expr_ty e)
4139{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004140 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004141 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4142 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004143 return 1;
4144}
4145
Eric V. Smitha78c7952015-11-03 12:45:05 -05004146/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004147static int
4148compiler_formatted_value(struct compiler *c, expr_ty e)
4149{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004150 /* Our oparg encodes 2 pieces of information: the conversion
4151 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004152
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004153 Convert the conversion char to 3 bits:
4154 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004155 !s : 001 0x1 FVC_STR
4156 !r : 010 0x2 FVC_REPR
4157 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004158
Eric V. Smitha78c7952015-11-03 12:45:05 -05004159 next bit is whether or not we have a format spec:
4160 yes : 100 0x4
4161 no : 000 0x0
4162 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004163
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004164 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004165 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004166
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004167 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004168 VISIT(c, expr, e->v.FormattedValue.value);
4169
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004170 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004171 case 's': oparg = FVC_STR; break;
4172 case 'r': oparg = FVC_REPR; break;
4173 case 'a': oparg = FVC_ASCII; break;
4174 case -1: oparg = FVC_NONE; break;
4175 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004176 PyErr_Format(PyExc_SystemError,
4177 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004178 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004179 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004180 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004181 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004182 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004183 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004184 }
4185
Eric V. Smitha78c7952015-11-03 12:45:05 -05004186 /* And push our opcode and oparg */
4187 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004188
Eric V. Smith235a6f02015-09-19 14:51:32 -04004189 return 1;
4190}
4191
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004192static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004193compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004194{
4195 Py_ssize_t i, n = end - begin;
4196 keyword_ty kw;
4197 PyObject *keys, *key;
4198 assert(n > 0);
4199 if (n > 1) {
4200 for (i = begin; i < end; i++) {
4201 kw = asdl_seq_GET(keywords, i);
4202 VISIT(c, expr, kw->value);
4203 }
4204 keys = PyTuple_New(n);
4205 if (keys == NULL) {
4206 return 0;
4207 }
4208 for (i = begin; i < end; i++) {
4209 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4210 Py_INCREF(key);
4211 PyTuple_SET_ITEM(keys, i - begin, key);
4212 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004213 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004214 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4215 }
4216 else {
4217 /* a for loop only executes once */
4218 for (i = begin; i < end; i++) {
4219 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004220 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004221 VISIT(c, expr, kw->value);
4222 }
4223 ADDOP_I(c, BUILD_MAP, n);
4224 }
4225 return 1;
4226}
4227
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004228/* shared code between compiler_call and compiler_class */
4229static int
4230compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004231 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004232 asdl_expr_seq *args,
4233 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004234{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004235 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004236
Pablo Galindo254ec782020-04-03 20:37:13 +01004237 if (validate_keywords(c, keywords) == -1) {
4238 return 0;
4239 }
4240
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004241 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004242 nkwelts = asdl_seq_LEN(keywords);
4243
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004244 for (i = 0; i < nelts; i++) {
4245 expr_ty elt = asdl_seq_GET(args, i);
4246 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004247 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004248 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004249 }
4250 for (i = 0; i < nkwelts; i++) {
4251 keyword_ty kw = asdl_seq_GET(keywords, i);
4252 if (kw->arg == NULL) {
4253 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004254 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004255 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004256
Mark Shannon13bc1392020-01-23 09:25:17 +00004257 /* No * or ** args, so can use faster calling sequence */
4258 for (i = 0; i < nelts; i++) {
4259 expr_ty elt = asdl_seq_GET(args, i);
4260 assert(elt->kind != Starred_kind);
4261 VISIT(c, expr, elt);
4262 }
4263 if (nkwelts) {
4264 PyObject *names;
4265 VISIT_SEQ(c, keyword, keywords);
4266 names = PyTuple_New(nkwelts);
4267 if (names == NULL) {
4268 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004269 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004270 for (i = 0; i < nkwelts; i++) {
4271 keyword_ty kw = asdl_seq_GET(keywords, i);
4272 Py_INCREF(kw->arg);
4273 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004274 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004275 ADDOP_LOAD_CONST_NEW(c, names);
4276 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4277 return 1;
4278 }
4279 else {
4280 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4281 return 1;
4282 }
4283
4284ex_call:
4285
4286 /* Do positional arguments. */
4287 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4288 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4289 }
4290 else if (starunpack_helper(c, args, n, BUILD_LIST,
4291 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4292 return 0;
4293 }
4294 /* Then keyword arguments */
4295 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004296 /* Has a new dict been pushed */
4297 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004298
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004299 nseen = 0; /* the number of keyword arguments on the stack following */
4300 for (i = 0; i < nkwelts; i++) {
4301 keyword_ty kw = asdl_seq_GET(keywords, i);
4302 if (kw->arg == NULL) {
4303 /* A keyword argument unpacking. */
4304 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004305 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004306 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004307 }
Mark Shannondb64f122020-06-01 10:42:42 +01004308 if (have_dict) {
4309 ADDOP_I(c, DICT_MERGE, 1);
4310 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004311 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004312 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004313 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004314 if (!have_dict) {
4315 ADDOP_I(c, BUILD_MAP, 0);
4316 have_dict = 1;
4317 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004318 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004319 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004320 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004321 else {
4322 nseen++;
4323 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004324 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004325 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004326 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004327 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004328 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004329 }
4330 if (have_dict) {
4331 ADDOP_I(c, DICT_MERGE, 1);
4332 }
4333 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004334 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004335 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004336 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004337 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4338 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004339}
4340
Nick Coghlan650f0d02007-04-15 12:05:43 +00004341
4342/* List and set comprehensions and generator expressions work by creating a
4343 nested function to perform the actual iteration. This means that the
4344 iteration variables don't leak into the current scope.
4345 The defined function is called immediately following its definition, with the
4346 result of that call being the result of the expression.
4347 The LC/SC version returns the populated container, while the GE version is
4348 flagged in symtable.c as a generator, so it returns the generator object
4349 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004350
4351 Possible cleanups:
4352 - iterate over the generator sequence instead of using recursion
4353*/
4354
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004355
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004356static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004357compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004358 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004359 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004360 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004361{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004362 comprehension_ty gen;
4363 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4364 if (gen->is_async) {
4365 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004366 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004367 } else {
4368 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004369 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004370 }
4371}
4372
4373static int
4374compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004375 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004376 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004377 expr_ty elt, expr_ty val, int type)
4378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 /* generate code for the iterator, then each of the ifs,
4380 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004382 comprehension_ty gen;
4383 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004384 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 start = compiler_new_block(c);
4387 skip = compiler_new_block(c);
4388 if_cleanup = compiler_new_block(c);
4389 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4392 anchor == NULL)
4393 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004397 if (gen_index == 0) {
4398 /* Receive outermost iter as an implicit argument */
4399 c->u->u_argcount = 1;
4400 ADDOP_I(c, LOAD_FAST, 0);
4401 }
4402 else {
4403 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004404 /* Fast path for the temporary variable assignment idiom:
4405 for y in [f(x)]
4406 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004407 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004408 switch (gen->iter->kind) {
4409 case List_kind:
4410 elts = gen->iter->v.List.elts;
4411 break;
4412 case Tuple_kind:
4413 elts = gen->iter->v.Tuple.elts;
4414 break;
4415 default:
4416 elts = NULL;
4417 }
4418 if (asdl_seq_LEN(elts) == 1) {
4419 expr_ty elt = asdl_seq_GET(elts, 0);
4420 if (elt->kind != Starred_kind) {
4421 VISIT(c, expr, elt);
4422 start = NULL;
4423 }
4424 }
4425 if (start) {
4426 VISIT(c, expr, gen->iter);
4427 ADDOP(c, GET_ITER);
4428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004430 if (start) {
4431 depth++;
4432 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004433 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004434 NEXT_BLOCK(c);
4435 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004436 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 /* XXX this needs to be cleaned up...a lot! */
4439 n = asdl_seq_LEN(gen->ifs);
4440 for (i = 0; i < n; i++) {
4441 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004442 if (!compiler_jump_if(c, e, if_cleanup, 0))
4443 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004444 NEXT_BLOCK(c);
4445 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004447 if (++gen_index < asdl_seq_LEN(generators))
4448 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004449 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004450 elt, val, type))
4451 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 /* only append after the last for generator */
4454 if (gen_index >= asdl_seq_LEN(generators)) {
4455 /* comprehension specific code */
4456 switch (type) {
4457 case COMP_GENEXP:
4458 VISIT(c, expr, elt);
4459 ADDOP(c, YIELD_VALUE);
4460 ADDOP(c, POP_TOP);
4461 break;
4462 case COMP_LISTCOMP:
4463 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004464 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 break;
4466 case COMP_SETCOMP:
4467 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004468 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 break;
4470 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004471 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004474 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004475 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 break;
4477 default:
4478 return 0;
4479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 compiler_use_next_block(c, skip);
4482 }
4483 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004484 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004485 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004486 compiler_use_next_block(c, anchor);
4487 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004488
4489 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004490}
4491
4492static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004493compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004494 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004495 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004496 expr_ty elt, expr_ty val, int type)
4497{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004498 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004499 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004500 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004501 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004502 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004503 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004504
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004505 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004506 return 0;
4507 }
4508
4509 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4510
4511 if (gen_index == 0) {
4512 /* Receive outermost iter as an implicit argument */
4513 c->u->u_argcount = 1;
4514 ADDOP_I(c, LOAD_FAST, 0);
4515 }
4516 else {
4517 /* Sub-iter - calculate on the fly */
4518 VISIT(c, expr, gen->iter);
4519 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004520 }
4521
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004522 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004523
Mark Shannon582aaf12020-08-04 17:30:11 +01004524 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004525 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004526 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004529 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530
4531 n = asdl_seq_LEN(gen->ifs);
4532 for (i = 0; i < n; i++) {
4533 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004534 if (!compiler_jump_if(c, e, if_cleanup, 0))
4535 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004536 NEXT_BLOCK(c);
4537 }
4538
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004539 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004540 if (++gen_index < asdl_seq_LEN(generators))
4541 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004542 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004543 elt, val, type))
4544 return 0;
4545
4546 /* only append after the last for generator */
4547 if (gen_index >= asdl_seq_LEN(generators)) {
4548 /* comprehension specific code */
4549 switch (type) {
4550 case COMP_GENEXP:
4551 VISIT(c, expr, elt);
4552 ADDOP(c, YIELD_VALUE);
4553 ADDOP(c, POP_TOP);
4554 break;
4555 case COMP_LISTCOMP:
4556 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004557 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004558 break;
4559 case COMP_SETCOMP:
4560 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004561 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004562 break;
4563 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004564 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004565 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004566 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004567 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004568 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004569 break;
4570 default:
4571 return 0;
4572 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004573 }
4574 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004575 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004576
4577 compiler_use_next_block(c, except);
4578 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004579
4580 return 1;
4581}
4582
4583static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004584compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004585 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004586 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004588 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004589 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004590 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004591 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004592 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004593
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004594
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004595 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004596
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004597 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004598 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4599 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004600 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004601 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004602 }
4603
4604 is_async_generator = c->u->u_ste->ste_coroutine;
4605
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004606 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004607 compiler_error(c, "asynchronous comprehension outside of "
4608 "an asynchronous function");
4609 goto error_in_scope;
4610 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004612 if (type != COMP_GENEXP) {
4613 int op;
4614 switch (type) {
4615 case COMP_LISTCOMP:
4616 op = BUILD_LIST;
4617 break;
4618 case COMP_SETCOMP:
4619 op = BUILD_SET;
4620 break;
4621 case COMP_DICTCOMP:
4622 op = BUILD_MAP;
4623 break;
4624 default:
4625 PyErr_Format(PyExc_SystemError,
4626 "unknown comprehension type %d", type);
4627 goto error_in_scope;
4628 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 ADDOP_I(c, op, 0);
4631 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004632
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004633 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 val, type))
4635 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 if (type != COMP_GENEXP) {
4638 ADDOP(c, RETURN_VALUE);
4639 }
4640
4641 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004642 qualname = c->u->u_qualname;
4643 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004645 if (top_level_await && is_async_generator){
4646 c->u->u_ste->ste_coroutine = 1;
4647 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004648 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004649 goto error;
4650
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004651 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004653 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 Py_DECREF(co);
4655
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004656 VISIT(c, expr, outermost->iter);
4657
4658 if (outermost->is_async) {
4659 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004660 } else {
4661 ADDOP(c, GET_ITER);
4662 }
4663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004665
4666 if (is_async_generator && type != COMP_GENEXP) {
4667 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004668 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004669 ADDOP(c, YIELD_FROM);
4670 }
4671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004673error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004675error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004676 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004677 Py_XDECREF(co);
4678 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004679}
4680
4681static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004682compiler_genexp(struct compiler *c, expr_ty e)
4683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 static identifier name;
4685 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004686 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 if (!name)
4688 return 0;
4689 }
4690 assert(e->kind == GeneratorExp_kind);
4691 return compiler_comprehension(c, e, COMP_GENEXP, name,
4692 e->v.GeneratorExp.generators,
4693 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004694}
4695
4696static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004697compiler_listcomp(struct compiler *c, expr_ty e)
4698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004699 static identifier name;
4700 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004701 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 if (!name)
4703 return 0;
4704 }
4705 assert(e->kind == ListComp_kind);
4706 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4707 e->v.ListComp.generators,
4708 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004709}
4710
4711static int
4712compiler_setcomp(struct compiler *c, expr_ty e)
4713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004714 static identifier name;
4715 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004716 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004717 if (!name)
4718 return 0;
4719 }
4720 assert(e->kind == SetComp_kind);
4721 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4722 e->v.SetComp.generators,
4723 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004724}
4725
4726
4727static int
4728compiler_dictcomp(struct compiler *c, expr_ty e)
4729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004730 static identifier name;
4731 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004732 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 if (!name)
4734 return 0;
4735 }
4736 assert(e->kind == DictComp_kind);
4737 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4738 e->v.DictComp.generators,
4739 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004740}
4741
4742
4743static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004744compiler_visit_keyword(struct compiler *c, keyword_ty k)
4745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 VISIT(c, expr, k->value);
4747 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004748}
4749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004751 whether they are true or false.
4752
4753 Return values: 1 for true, 0 for false, -1 for non-constant.
4754 */
4755
4756static int
Mark Shannonfee55262019-11-21 09:11:43 +00004757compiler_with_except_finish(struct compiler *c) {
4758 basicblock *exit;
4759 exit = compiler_new_block(c);
4760 if (exit == NULL)
4761 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004762 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004763 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004764 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004765 compiler_use_next_block(c, exit);
4766 ADDOP(c, POP_TOP);
4767 ADDOP(c, POP_TOP);
4768 ADDOP(c, POP_TOP);
4769 ADDOP(c, POP_EXCEPT);
4770 ADDOP(c, POP_TOP);
4771 return 1;
4772}
Yury Selivanov75445082015-05-11 22:57:16 -04004773
4774/*
4775 Implements the async with statement.
4776
4777 The semantics outlined in that PEP are as follows:
4778
4779 async with EXPR as VAR:
4780 BLOCK
4781
4782 It is implemented roughly as:
4783
4784 context = EXPR
4785 exit = context.__aexit__ # not calling it
4786 value = await context.__aenter__()
4787 try:
4788 VAR = value # if VAR present in the syntax
4789 BLOCK
4790 finally:
4791 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004792 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004793 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004794 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004795 if not (await exit(*exc)):
4796 raise
4797 */
4798static int
4799compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4800{
Mark Shannonfee55262019-11-21 09:11:43 +00004801 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004802 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4803
4804 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004805 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004806 c->u->u_ste->ste_coroutine = 1;
4807 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004808 return compiler_error(c, "'async with' outside async function");
4809 }
Yury Selivanov75445082015-05-11 22:57:16 -04004810
4811 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004812 final = compiler_new_block(c);
4813 exit = compiler_new_block(c);
4814 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004815 return 0;
4816
4817 /* Evaluate EXPR */
4818 VISIT(c, expr, item->context_expr);
4819
4820 ADDOP(c, BEFORE_ASYNC_WITH);
4821 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004822 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004823 ADDOP(c, YIELD_FROM);
4824
Mark Shannon582aaf12020-08-04 17:30:11 +01004825 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004826
4827 /* SETUP_ASYNC_WITH pushes a finally block. */
4828 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004829 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004830 return 0;
4831 }
4832
4833 if (item->optional_vars) {
4834 VISIT(c, expr, item->optional_vars);
4835 }
4836 else {
4837 /* Discard result from context.__aenter__() */
4838 ADDOP(c, POP_TOP);
4839 }
4840
4841 pos++;
4842 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4843 /* BLOCK code */
4844 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4845 else if (!compiler_async_with(c, s, pos))
4846 return 0;
4847
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004848 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004849 ADDOP(c, POP_BLOCK);
4850 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004851
Mark Shannonfee55262019-11-21 09:11:43 +00004852 /* For successful outcome:
4853 * call __exit__(None, None, None)
4854 */
4855 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004856 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004857 ADDOP(c, GET_AWAITABLE);
4858 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4859 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004860
Mark Shannonfee55262019-11-21 09:11:43 +00004861 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004862
Mark Shannon582aaf12020-08-04 17:30:11 +01004863 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004864
4865 /* For exceptional outcome: */
4866 compiler_use_next_block(c, final);
4867
4868 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004869 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004870 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004871 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004872 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004873
Mark Shannonfee55262019-11-21 09:11:43 +00004874compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004875 return 1;
4876}
4877
4878
Guido van Rossumc2e20742006-02-27 22:32:47 +00004879/*
4880 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004881 with EXPR as VAR:
4882 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004883 is implemented as:
4884 <code for EXPR>
4885 SETUP_WITH E
4886 <code to store to VAR> or POP_TOP
4887 <code for BLOCK>
4888 LOAD_CONST (None, None, None)
4889 CALL_FUNCTION_EX 0
4890 JUMP_FORWARD EXIT
4891 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4892 POP_JUMP_IF_TRUE T:
4893 RERAISE
4894 T: POP_TOP * 3 (remove exception from stack)
4895 POP_EXCEPT
4896 POP_TOP
4897 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004898 */
Mark Shannonfee55262019-11-21 09:11:43 +00004899
Guido van Rossumc2e20742006-02-27 22:32:47 +00004900static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004901compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004902{
Mark Shannonfee55262019-11-21 09:11:43 +00004903 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004904 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004905
4906 assert(s->kind == With_kind);
4907
Guido van Rossumc2e20742006-02-27 22:32:47 +00004908 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004909 final = compiler_new_block(c);
4910 exit = compiler_new_block(c);
4911 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004912 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004913
Thomas Wouters477c8d52006-05-27 19:21:47 +00004914 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004915 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004916 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004917 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004918
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004919 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004920 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004921 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004922 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004923 }
4924
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004925 if (item->optional_vars) {
4926 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004927 }
4928 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004929 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004930 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004931 }
4932
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004933 pos++;
4934 if (pos == asdl_seq_LEN(s->v.With.items))
4935 /* BLOCK code */
4936 VISIT_SEQ(c, stmt, s->v.With.body)
4937 else if (!compiler_with(c, s, pos))
4938 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004939
Guido van Rossumc2e20742006-02-27 22:32:47 +00004940 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004941 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004942
Mark Shannonfee55262019-11-21 09:11:43 +00004943 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004944
Mark Shannonfee55262019-11-21 09:11:43 +00004945 /* For successful outcome:
4946 * call __exit__(None, None, None)
4947 */
4948 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004949 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004950 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004951 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004952
Mark Shannonfee55262019-11-21 09:11:43 +00004953 /* For exceptional outcome: */
4954 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004955
Mark Shannonfee55262019-11-21 09:11:43 +00004956 ADDOP(c, WITH_EXCEPT_START);
4957 compiler_with_except_finish(c);
4958
4959 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004960 return 1;
4961}
4962
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004963static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004964compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004967 case NamedExpr_kind:
4968 VISIT(c, expr, e->v.NamedExpr.value);
4969 ADDOP(c, DUP_TOP);
4970 VISIT(c, expr, e->v.NamedExpr.target);
4971 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004972 case BoolOp_kind:
4973 return compiler_boolop(c, e);
4974 case BinOp_kind:
4975 VISIT(c, expr, e->v.BinOp.left);
4976 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004977 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004978 break;
4979 case UnaryOp_kind:
4980 VISIT(c, expr, e->v.UnaryOp.operand);
4981 ADDOP(c, unaryop(e->v.UnaryOp.op));
4982 break;
4983 case Lambda_kind:
4984 return compiler_lambda(c, e);
4985 case IfExp_kind:
4986 return compiler_ifexp(c, e);
4987 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004988 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004989 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004990 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 case GeneratorExp_kind:
4992 return compiler_genexp(c, e);
4993 case ListComp_kind:
4994 return compiler_listcomp(c, e);
4995 case SetComp_kind:
4996 return compiler_setcomp(c, e);
4997 case DictComp_kind:
4998 return compiler_dictcomp(c, e);
4999 case Yield_kind:
5000 if (c->u->u_ste->ste_type != FunctionBlock)
5001 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005002 if (e->v.Yield.value) {
5003 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005004 }
5005 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005006 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005008 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005010 case YieldFrom_kind:
5011 if (c->u->u_ste->ste_type != FunctionBlock)
5012 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005013
5014 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5015 return compiler_error(c, "'yield from' inside async function");
5016
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005017 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005018 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005019 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005020 ADDOP(c, YIELD_FROM);
5021 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005022 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005023 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005024 if (c->u->u_ste->ste_type != FunctionBlock){
5025 return compiler_error(c, "'await' outside function");
5026 }
Yury Selivanov75445082015-05-11 22:57:16 -04005027
Victor Stinner331a6a52019-05-27 16:39:22 +02005028 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005029 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5030 return compiler_error(c, "'await' outside async function");
5031 }
5032 }
Yury Selivanov75445082015-05-11 22:57:16 -04005033
5034 VISIT(c, expr, e->v.Await.value);
5035 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005036 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005037 ADDOP(c, YIELD_FROM);
5038 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 case Compare_kind:
5040 return compiler_compare(c, e);
5041 case Call_kind:
5042 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005043 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005044 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005045 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005046 case JoinedStr_kind:
5047 return compiler_joined_str(c, e);
5048 case FormattedValue_kind:
5049 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 /* The following exprs can be assignment targets. */
5051 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005052 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 case Load:
5055 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5056 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005058 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5059 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005060 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5061 break;
5062 case Del:
5063 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5064 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005065 }
5066 break;
5067 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005068 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 case Starred_kind:
5070 switch (e->v.Starred.ctx) {
5071 case Store:
5072 /* In all legitimate cases, the Starred node was already replaced
5073 * by compiler_list/compiler_tuple. XXX: is that okay? */
5074 return compiler_error(c,
5075 "starred assignment target must be in a list or tuple");
5076 default:
5077 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005078 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005080 break;
5081 case Slice_kind:
5082 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 case Name_kind:
5084 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5085 /* child nodes of List and Tuple will have expr_context set */
5086 case List_kind:
5087 return compiler_list(c, e);
5088 case Tuple_kind:
5089 return compiler_tuple(c, e);
5090 }
5091 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005092}
5093
5094static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005095compiler_visit_expr(struct compiler *c, expr_ty e)
5096{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005097 int old_lineno = c->u->u_lineno;
5098 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005099 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005100 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005101 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005102 c->u->u_col_offset = old_col_offset;
5103 return res;
5104}
5105
5106static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005107compiler_augassign(struct compiler *c, stmt_ty s)
5108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005110 expr_ty e = s->v.AugAssign.target;
5111
5112 int old_lineno = c->u->u_lineno;
5113 int old_col_offset = c->u->u_col_offset;
5114 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 switch (e->kind) {
5117 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005118 VISIT(c, expr, e->v.Attribute.value);
5119 ADDOP(c, DUP_TOP);
5120 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005121 break;
5122 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005123 VISIT(c, expr, e->v.Subscript.value);
5124 VISIT(c, expr, e->v.Subscript.slice);
5125 ADDOP(c, DUP_TOP_TWO);
5126 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005127 break;
5128 case Name_kind:
5129 if (!compiler_nameop(c, e->v.Name.id, Load))
5130 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005131 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005132 default:
5133 PyErr_Format(PyExc_SystemError,
5134 "invalid node type (%d) for augmented assignment",
5135 e->kind);
5136 return 0;
5137 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005138
5139 c->u->u_lineno = old_lineno;
5140 c->u->u_col_offset = old_col_offset;
5141
5142 VISIT(c, expr, s->v.AugAssign.value);
5143 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5144
5145 SET_LOC(c, e);
5146
5147 switch (e->kind) {
5148 case Attribute_kind:
5149 ADDOP(c, ROT_TWO);
5150 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5151 break;
5152 case Subscript_kind:
5153 ADDOP(c, ROT_THREE);
5154 ADDOP(c, STORE_SUBSCR);
5155 break;
5156 case Name_kind:
5157 return compiler_nameop(c, e->v.Name.id, Store);
5158 default:
5159 Py_UNREACHABLE();
5160 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005161 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005162}
5163
5164static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005165check_ann_expr(struct compiler *c, expr_ty e)
5166{
5167 VISIT(c, expr, e);
5168 ADDOP(c, POP_TOP);
5169 return 1;
5170}
5171
5172static int
5173check_annotation(struct compiler *c, stmt_ty s)
5174{
5175 /* Annotations are only evaluated in a module or class. */
5176 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5177 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5178 return check_ann_expr(c, s->v.AnnAssign.annotation);
5179 }
5180 return 1;
5181}
5182
5183static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005184check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005185{
5186 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005187 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005188 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005189 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005190 return 0;
5191 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005192 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5193 return 0;
5194 }
5195 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5196 return 0;
5197 }
5198 return 1;
5199 case Tuple_kind: {
5200 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005201 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005202 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005203 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005204 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005205 return 0;
5206 }
5207 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005208 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005209 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005210 default:
5211 return check_ann_expr(c, e);
5212 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005213}
5214
5215static int
5216compiler_annassign(struct compiler *c, stmt_ty s)
5217{
5218 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005219 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005220
5221 assert(s->kind == AnnAssign_kind);
5222
5223 /* We perform the actual assignment first. */
5224 if (s->v.AnnAssign.value) {
5225 VISIT(c, expr, s->v.AnnAssign.value);
5226 VISIT(c, expr, targ);
5227 }
5228 switch (targ->kind) {
5229 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005230 if (forbidden_name(c, targ->v.Name.id, Store))
5231 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005232 /* If we have a simple name in a module or class, store annotation. */
5233 if (s->v.AnnAssign.simple &&
5234 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5235 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005236 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005237 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005238 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005239 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005240 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005241 }
5242 break;
5243 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005244 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5245 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005246 if (!s->v.AnnAssign.value &&
5247 !check_ann_expr(c, targ->v.Attribute.value)) {
5248 return 0;
5249 }
5250 break;
5251 case Subscript_kind:
5252 if (!s->v.AnnAssign.value &&
5253 (!check_ann_expr(c, targ->v.Subscript.value) ||
5254 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5255 return 0;
5256 }
5257 break;
5258 default:
5259 PyErr_Format(PyExc_SystemError,
5260 "invalid node type (%d) for annotated assignment",
5261 targ->kind);
5262 return 0;
5263 }
5264 /* Annotation is evaluated last. */
5265 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5266 return 0;
5267 }
5268 return 1;
5269}
5270
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005271/* Raises a SyntaxError and returns 0.
5272 If something goes wrong, a different exception may be raised.
5273*/
5274
5275static int
5276compiler_error(struct compiler *c, const char *errstr)
5277{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005278 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005279 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005280
Victor Stinner14e461d2013-08-26 22:28:21 +02005281 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005282 if (!loc) {
5283 Py_INCREF(Py_None);
5284 loc = Py_None;
5285 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005286 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005287 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005288 if (!u)
5289 goto exit;
5290 v = Py_BuildValue("(zO)", errstr, u);
5291 if (!v)
5292 goto exit;
5293 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005294 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005295 Py_DECREF(loc);
5296 Py_XDECREF(u);
5297 Py_XDECREF(v);
5298 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005299}
5300
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005301/* Emits a SyntaxWarning and returns 1 on success.
5302 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5303 and returns 0.
5304*/
5305static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005306compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005307{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005308 va_list vargs;
5309#ifdef HAVE_STDARG_PROTOTYPES
5310 va_start(vargs, format);
5311#else
5312 va_start(vargs);
5313#endif
5314 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5315 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005316 if (msg == NULL) {
5317 return 0;
5318 }
5319 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5320 c->u->u_lineno, NULL, NULL) < 0)
5321 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005322 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005323 /* Replace the SyntaxWarning exception with a SyntaxError
5324 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005325 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005326 assert(PyUnicode_AsUTF8(msg) != NULL);
5327 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005328 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005329 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005330 return 0;
5331 }
5332 Py_DECREF(msg);
5333 return 1;
5334}
5335
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005336static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005337compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005338{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005339 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005341
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005342 if (ctx == Load) {
5343 if (!check_subscripter(c, e->v.Subscript.value)) {
5344 return 0;
5345 }
5346 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5347 return 0;
5348 }
5349 }
5350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005351 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005352 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005353 case Store: op = STORE_SUBSCR; break;
5354 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005356 assert(op);
5357 VISIT(c, expr, e->v.Subscript.value);
5358 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005359 ADDOP(c, op);
5360 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005361}
5362
5363static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005364compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005366 int n = 2;
5367 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005369 /* only handles the cases where BUILD_SLICE is emitted */
5370 if (s->v.Slice.lower) {
5371 VISIT(c, expr, s->v.Slice.lower);
5372 }
5373 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005374 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 if (s->v.Slice.upper) {
5378 VISIT(c, expr, s->v.Slice.upper);
5379 }
5380 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005381 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005382 }
5383
5384 if (s->v.Slice.step) {
5385 n++;
5386 VISIT(c, expr, s->v.Slice.step);
5387 }
5388 ADDOP_I(c, BUILD_SLICE, n);
5389 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005390}
5391
Thomas Wouters89f507f2006-12-13 04:49:30 +00005392/* End of the compiler section, beginning of the assembler section */
5393
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005394/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005395 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005396
5397 XXX must handle implicit jumps from one block to next
5398*/
5399
Thomas Wouters89f507f2006-12-13 04:49:30 +00005400struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 PyObject *a_bytecode; /* string containing bytecode */
5402 int a_offset; /* offset into bytecode */
5403 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 PyObject *a_lnotab; /* string containing lnotab */
5405 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005406 int a_prevlineno; /* lineno of last emitted line in line table */
5407 int a_lineno; /* lineno of last emitted instruction */
5408 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005409 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005410};
5411
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005412Py_LOCAL_INLINE(void)
5413stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005414{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005415 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005416 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005417 assert(b->b_startdepth < 0);
5418 b->b_startdepth = depth;
5419 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005420 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005421}
5422
5423/* Find the flow path that needs the largest stack. We assume that
5424 * cycles in the flow graph have no net effect on the stack depth.
5425 */
5426static int
5427stackdepth(struct compiler *c)
5428{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005429 basicblock *b, *entryblock = NULL;
5430 basicblock **stack, **sp;
5431 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005432 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005433 b->b_startdepth = INT_MIN;
5434 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005435 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 }
5437 if (!entryblock)
5438 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005439 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5440 if (!stack) {
5441 PyErr_NoMemory();
5442 return -1;
5443 }
5444
5445 sp = stack;
5446 stackdepth_push(&sp, entryblock, 0);
5447 while (sp != stack) {
5448 b = *--sp;
5449 int depth = b->b_startdepth;
5450 assert(depth >= 0);
5451 basicblock *next = b->b_next;
5452 for (int i = 0; i < b->b_iused; i++) {
5453 struct instr *instr = &b->b_instr[i];
5454 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5455 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005456 _Py_FatalErrorFormat(__func__,
5457 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005458 }
5459 int new_depth = depth + effect;
5460 if (new_depth > maxdepth) {
5461 maxdepth = new_depth;
5462 }
5463 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005464 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005465 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5466 assert(effect != PY_INVALID_STACK_EFFECT);
5467 int target_depth = depth + effect;
5468 if (target_depth > maxdepth) {
5469 maxdepth = target_depth;
5470 }
5471 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005472 stackdepth_push(&sp, instr->i_target, target_depth);
5473 }
5474 depth = new_depth;
5475 if (instr->i_opcode == JUMP_ABSOLUTE ||
5476 instr->i_opcode == JUMP_FORWARD ||
5477 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005478 instr->i_opcode == RAISE_VARARGS ||
5479 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005480 {
5481 /* remaining code is dead */
5482 next = NULL;
5483 break;
5484 }
5485 }
5486 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005487 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005488 stackdepth_push(&sp, next, depth);
5489 }
5490 }
5491 PyObject_Free(stack);
5492 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005493}
5494
5495static int
5496assemble_init(struct assembler *a, int nblocks, int firstlineno)
5497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005499 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005500 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005502 if (a->a_bytecode == NULL) {
5503 goto error;
5504 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005506 if (a->a_lnotab == NULL) {
5507 goto error;
5508 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005509 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005510 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005511 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005512 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005513 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005514error:
5515 Py_XDECREF(a->a_bytecode);
5516 Py_XDECREF(a->a_lnotab);
5517 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005518}
5519
5520static void
5521assemble_free(struct assembler *a)
5522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 Py_XDECREF(a->a_bytecode);
5524 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005525}
5526
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005527static int
5528blocksize(basicblock *b)
5529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 int i;
5531 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005534 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005536}
5537
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005538static int
Mark Shannon877df852020-11-12 09:43:29 +00005539assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005540{
Mark Shannon877df852020-11-12 09:43:29 +00005541 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 if (a->a_lnotab_off + 2 >= len) {
5543 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5544 return 0;
5545 }
Mark Shannon877df852020-11-12 09:43:29 +00005546 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005550 *lnotab++ = bdelta;
5551 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005553}
5554
Mark Shannon877df852020-11-12 09:43:29 +00005555/* Appends a range to the end of the line number table. See
5556 * Objects/lnotab_notes.txt for the description of the line number table. */
5557
5558static int
5559assemble_line_range(struct assembler *a)
5560{
5561 int ldelta, bdelta;
5562 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5563 if (bdelta == 0) {
5564 return 1;
5565 }
5566 if (a->a_lineno < 0) {
5567 ldelta = -128;
5568 }
5569 else {
5570 ldelta = a->a_lineno - a->a_prevlineno;
5571 a->a_prevlineno = a->a_lineno;
5572 while (ldelta > 127) {
5573 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5574 return 0;
5575 }
5576 ldelta -= 127;
5577 }
5578 while (ldelta < -127) {
5579 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5580 return 0;
5581 }
5582 ldelta += 127;
5583 }
5584 }
5585 assert(-128 <= ldelta && ldelta < 128);
5586 while (bdelta > 254) {
5587 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5588 return 0;
5589 }
5590 ldelta = a->a_lineno < 0 ? -128 : 0;
5591 bdelta -= 254;
5592 }
5593 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5594 return 0;
5595 }
5596 a->a_lineno_start = a->a_offset;
5597 return 1;
5598}
5599
5600static int
5601assemble_lnotab(struct assembler *a, struct instr *i)
5602{
5603 if (i->i_lineno == a->a_lineno) {
5604 return 1;
5605 }
5606 if (!assemble_line_range(a)) {
5607 return 0;
5608 }
5609 a->a_lineno = i->i_lineno;
5610 return 1;
5611}
5612
5613
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005614/* assemble_emit()
5615 Extend the bytecode with a new instruction.
5616 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005617*/
5618
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005619static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005620assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005621{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005622 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005623 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005624 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005625
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005626 arg = i->i_oparg;
5627 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005628 if (i->i_lineno && !assemble_lnotab(a, i))
5629 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005630 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005631 if (len > PY_SSIZE_T_MAX / 2)
5632 return 0;
5633 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5634 return 0;
5635 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005636 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005638 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005639 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005640}
5641
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005642static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005643assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005645 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005646 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 /* Compute the size of each block and fixup jump args.
5650 Replace block pointer with position in bytecode. */
5651 do {
5652 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005653 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005654 bsize = blocksize(b);
5655 b->b_offset = totsize;
5656 totsize += bsize;
5657 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005658 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5660 bsize = b->b_offset;
5661 for (i = 0; i < b->b_iused; i++) {
5662 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005663 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 /* Relative jumps are computed relative to
5665 the instruction pointer after fetching
5666 the jump instruction.
5667 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005668 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005669 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005671 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005672 instr->i_oparg -= bsize;
5673 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005674 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005675 if (instrsize(instr->i_oparg) != isize) {
5676 extended_arg_recompile = 1;
5677 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 }
5680 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 /* XXX: This is an awful hack that could hurt performance, but
5683 on the bright side it should work until we come up
5684 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 The issue is that in the first loop blocksize() is called
5687 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005688 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005691 So we loop until we stop seeing new EXTENDED_ARGs.
5692 The only EXTENDED_ARGs that could be popping up are
5693 ones in jump instructions. So this should converge
5694 fairly quickly.
5695 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005696 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005697}
5698
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005699static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005700dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005703 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 tuple = PyTuple_New(size);
5706 if (tuple == NULL)
5707 return NULL;
5708 while (PyDict_Next(dict, &pos, &k, &v)) {
5709 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005710 Py_INCREF(k);
5711 assert((i - offset) < size);
5712 assert((i - offset) >= 0);
5713 PyTuple_SET_ITEM(tuple, i - offset, k);
5714 }
5715 return tuple;
5716}
5717
5718static PyObject *
5719consts_dict_keys_inorder(PyObject *dict)
5720{
5721 PyObject *consts, *k, *v;
5722 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5723
5724 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5725 if (consts == NULL)
5726 return NULL;
5727 while (PyDict_Next(dict, &pos, &k, &v)) {
5728 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005729 /* The keys of the dictionary can be tuples wrapping a contant.
5730 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5731 * the object we want is always second. */
5732 if (PyTuple_CheckExact(k)) {
5733 k = PyTuple_GET_ITEM(k, 1);
5734 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005735 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005736 assert(i < size);
5737 assert(i >= 0);
5738 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005740 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005741}
5742
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005743static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005744compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005747 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005749 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 if (ste->ste_nested)
5751 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005752 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005753 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005754 if (!ste->ste_generator && ste->ste_coroutine)
5755 flags |= CO_COROUTINE;
5756 if (ste->ste_generator && ste->ste_coroutine)
5757 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 if (ste->ste_varargs)
5759 flags |= CO_VARARGS;
5760 if (ste->ste_varkeywords)
5761 flags |= CO_VARKEYWORDS;
5762 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005764 /* (Only) inherit compilerflags in PyCF_MASK */
5765 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005766
Pablo Galindo90235812020-03-15 04:29:22 +00005767 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005768 ste->ste_coroutine &&
5769 !ste->ste_generator) {
5770 flags |= CO_COROUTINE;
5771 }
5772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005773 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005774}
5775
INADA Naokic2e16072018-11-26 21:23:22 +09005776// Merge *tuple* with constant cache.
5777// Unlike merge_consts_recursive(), this function doesn't work recursively.
5778static int
5779merge_const_tuple(struct compiler *c, PyObject **tuple)
5780{
5781 assert(PyTuple_CheckExact(*tuple));
5782
5783 PyObject *key = _PyCode_ConstantKey(*tuple);
5784 if (key == NULL) {
5785 return 0;
5786 }
5787
5788 // t is borrowed reference
5789 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5790 Py_DECREF(key);
5791 if (t == NULL) {
5792 return 0;
5793 }
5794 if (t == key) { // tuple is new constant.
5795 return 1;
5796 }
5797
5798 PyObject *u = PyTuple_GET_ITEM(t, 1);
5799 Py_INCREF(u);
5800 Py_DECREF(*tuple);
5801 *tuple = u;
5802 return 1;
5803}
5804
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005805static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005806makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 PyObject *names = NULL;
5810 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005811 PyObject *name = NULL;
5812 PyObject *freevars = NULL;
5813 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005814 Py_ssize_t nlocals;
5815 int nlocals_int;
5816 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005817 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005819 names = dict_keys_inorder(c->u->u_names, 0);
5820 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005821 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005822 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005823 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005824 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5825 if (!cellvars)
5826 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005827 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 if (!freevars)
5829 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005830
INADA Naokic2e16072018-11-26 21:23:22 +09005831 if (!merge_const_tuple(c, &names) ||
5832 !merge_const_tuple(c, &varnames) ||
5833 !merge_const_tuple(c, &cellvars) ||
5834 !merge_const_tuple(c, &freevars))
5835 {
5836 goto error;
5837 }
5838
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005839 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005840 assert(nlocals < INT_MAX);
5841 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 flags = compute_code_flags(c);
5844 if (flags < 0)
5845 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005846
Mark Shannon6e8128f2020-07-30 10:03:00 +01005847 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5848 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005849 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005850 }
INADA Naokic2e16072018-11-26 21:23:22 +09005851 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005852 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005853 goto error;
5854 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005855
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005856 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005857 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005858 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005859 maxdepth = stackdepth(c);
5860 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005861 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005862 goto error;
5863 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005864 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005865 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005866 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005867 varnames, freevars, cellvars, c->c_filename,
5868 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005869 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005870 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 Py_XDECREF(names);
5872 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005873 Py_XDECREF(name);
5874 Py_XDECREF(freevars);
5875 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005876 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005877}
5878
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005879
5880/* For debugging purposes only */
5881#if 0
5882static void
5883dump_instr(const struct instr *i)
5884{
Mark Shannon582aaf12020-08-04 17:30:11 +01005885 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5886 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005887 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005889 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005890 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005892 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5894 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005895}
5896
5897static void
5898dump_basicblock(const basicblock *b)
5899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005900 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005901 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5902 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005903 if (b->b_instr) {
5904 int i;
5905 for (i = 0; i < b->b_iused; i++) {
5906 fprintf(stderr, " [%02d] ", i);
5907 dump_instr(b->b_instr + i);
5908 }
5909 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005910}
5911#endif
5912
Mark Shannon5977a792020-12-02 13:31:40 +00005913
5914static int
5915normalize_basic_block(basicblock *bb);
5916
Mark Shannon6e8128f2020-07-30 10:03:00 +01005917static int
5918optimize_cfg(struct assembler *a, PyObject *consts);
5919
Mark Shannon5977a792020-12-02 13:31:40 +00005920static int
5921ensure_exits_have_lineno(struct compiler *c);
5922
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005923static PyCodeObject *
5924assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 basicblock *b, *entryblock;
5927 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005928 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005929 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005930 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 /* Make sure every block that falls off the end returns None.
5933 XXX NEXT_BLOCK() isn't quite right, because if the last
5934 block ends with a jump or return b_next shouldn't set.
5935 */
5936 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005937 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005939 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005940 ADDOP(c, RETURN_VALUE);
5941 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005942
Mark Shannon5977a792020-12-02 13:31:40 +00005943 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
5944 if (normalize_basic_block(b)) {
5945 goto error;
5946 }
5947 }
5948
5949 if (ensure_exits_have_lineno(c)) {
5950 goto error;
5951 }
5952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 nblocks = 0;
5954 entryblock = NULL;
5955 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5956 nblocks++;
5957 entryblock = b;
5958 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 /* Set firstlineno if it wasn't explicitly set. */
5961 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005962 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005963 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005964 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005965 c->u->u_firstlineno = 1;
5966 }
Mark Shannon5977a792020-12-02 13:31:40 +00005967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005968 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5969 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005970 a.a_entry = entryblock;
5971 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005972
Mark Shannon6e8128f2020-07-30 10:03:00 +01005973 consts = consts_dict_keys_inorder(c->u->u_consts);
5974 if (consts == NULL) {
5975 goto error;
5976 }
5977 if (optimize_cfg(&a, consts)) {
5978 goto error;
5979 }
5980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 /* Can't modify the bytecode after computing jump offsets. */
5982 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005983
Mark Shannoncc75ab72020-11-12 19:49:33 +00005984 /* Emit code. */
5985 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005986 for (j = 0; j < b->b_iused; j++)
5987 if (!assemble_emit(&a, &b->b_instr[j]))
5988 goto error;
5989 }
Mark Shannon877df852020-11-12 09:43:29 +00005990 if (!assemble_line_range(&a)) {
5991 return 0;
5992 }
5993 /* Emit sentinel at end of line number table */
5994 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
5995 goto error;
5996 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005998 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5999 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006000 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006001 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006002
Mark Shannon6e8128f2020-07-30 10:03:00 +01006003 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006004 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006005 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006006 assemble_free(&a);
6007 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006008}
Georg Brandl8334fd92010-12-04 10:26:46 +00006009
6010#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006011PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006012PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6013 PyArena *arena)
6014{
6015 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6016}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006017
6018
6019/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6020 with LOAD_CONST (c1, c2, ... cn).
6021 The consts table must still be in list form so that the
6022 new constant (c1, c2, ... cn) can be appended.
6023 Called with codestr pointing to the first LOAD_CONST.
6024*/
6025static int
6026fold_tuple_on_constants(struct instr *inst,
6027 int n, PyObject *consts)
6028{
6029 /* Pre-conditions */
6030 assert(PyList_CheckExact(consts));
6031 assert(inst[n].i_opcode == BUILD_TUPLE);
6032 assert(inst[n].i_oparg == n);
6033
6034 for (int i = 0; i < n; i++) {
6035 if (inst[i].i_opcode != LOAD_CONST) {
6036 return 0;
6037 }
6038 }
6039
6040 /* Buildup new tuple of constants */
6041 PyObject *newconst = PyTuple_New(n);
6042 if (newconst == NULL) {
6043 return -1;
6044 }
6045 for (int i = 0; i < n; i++) {
6046 int arg = inst[i].i_oparg;
6047 PyObject *constant = PyList_GET_ITEM(consts, arg);
6048 Py_INCREF(constant);
6049 PyTuple_SET_ITEM(newconst, i, constant);
6050 }
6051 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006052 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006053 Py_DECREF(newconst);
6054 PyErr_SetString(PyExc_OverflowError, "too many constants");
6055 return -1;
6056 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006057 if (PyList_Append(consts, newconst)) {
6058 Py_DECREF(newconst);
6059 return -1;
6060 }
6061 Py_DECREF(newconst);
6062 for (int i = 0; i < n; i++) {
6063 inst[i].i_opcode = NOP;
6064 }
6065 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006066 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006067 return 0;
6068}
6069
Mark Shannoncc75ab72020-11-12 19:49:33 +00006070/* Maximum size of basic block that should be copied in optimizer */
6071#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006072
6073/* Optimization */
6074static int
6075optimize_basic_block(basicblock *bb, PyObject *consts)
6076{
6077 assert(PyList_CheckExact(consts));
6078 struct instr nop;
6079 nop.i_opcode = NOP;
6080 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006081 for (int i = 0; i < bb->b_iused; i++) {
6082 struct instr *inst = &bb->b_instr[i];
6083 int oparg = inst->i_oparg;
6084 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006085 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006086 /* Skip over empty basic blocks. */
6087 while (inst->i_target->b_iused == 0) {
6088 inst->i_target = inst->i_target->b_next;
6089 }
6090 target = &inst->i_target->b_instr[0];
6091 }
6092 else {
6093 target = &nop;
6094 }
6095 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006096 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006097 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006098 {
6099 PyObject* cnt;
6100 int is_true;
6101 int jump_if_true;
6102 switch(nextop) {
6103 case POP_JUMP_IF_FALSE:
6104 case POP_JUMP_IF_TRUE:
6105 cnt = PyList_GET_ITEM(consts, oparg);
6106 is_true = PyObject_IsTrue(cnt);
6107 if (is_true == -1) {
6108 goto error;
6109 }
6110 inst->i_opcode = NOP;
6111 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6112 if (is_true == jump_if_true) {
6113 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6114 bb->b_nofallthrough = 1;
6115 }
6116 else {
6117 bb->b_instr[i+1].i_opcode = NOP;
6118 }
6119 break;
6120 case JUMP_IF_FALSE_OR_POP:
6121 case JUMP_IF_TRUE_OR_POP:
6122 cnt = PyList_GET_ITEM(consts, oparg);
6123 is_true = PyObject_IsTrue(cnt);
6124 if (is_true == -1) {
6125 goto error;
6126 }
6127 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6128 if (is_true == jump_if_true) {
6129 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6130 bb->b_nofallthrough = 1;
6131 }
6132 else {
6133 inst->i_opcode = NOP;
6134 bb->b_instr[i+1].i_opcode = NOP;
6135 }
6136 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006137 }
6138 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006139 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006140
6141 /* Try to fold tuples of constants.
6142 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6143 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6144 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6145 case BUILD_TUPLE:
6146 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6147 switch(oparg) {
6148 case 1:
6149 inst->i_opcode = NOP;
6150 bb->b_instr[i+1].i_opcode = NOP;
6151 break;
6152 case 2:
6153 inst->i_opcode = ROT_TWO;
6154 bb->b_instr[i+1].i_opcode = NOP;
6155 break;
6156 case 3:
6157 inst->i_opcode = ROT_THREE;
6158 bb->b_instr[i+1].i_opcode = ROT_TWO;
6159 }
6160 break;
6161 }
6162 if (i >= oparg) {
6163 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6164 goto error;
6165 }
6166 }
6167 break;
6168
6169 /* Simplify conditional jump to conditional jump where the
6170 result of the first test implies the success of a similar
6171 test or the failure of the opposite test.
6172 Arises in code like:
6173 "a and b or c"
6174 "(a and b) and c"
6175 "(a or b) or c"
6176 "(a or b) and c"
6177 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6178 --> x:JUMP_IF_FALSE_OR_POP z
6179 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6180 --> x:POP_JUMP_IF_FALSE y+1
6181 where y+1 is the instruction following the second test.
6182 */
6183 case JUMP_IF_FALSE_OR_POP:
6184 switch(target->i_opcode) {
6185 case POP_JUMP_IF_FALSE:
6186 *inst = *target;
Mark Shannon266b4622020-11-17 19:30:14 +00006187 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006188 break;
6189 case JUMP_ABSOLUTE:
6190 case JUMP_FORWARD:
6191 case JUMP_IF_FALSE_OR_POP:
Mark Shannon266b4622020-11-17 19:30:14 +00006192 if (inst->i_target != target->i_target) {
6193 inst->i_target = target->i_target;
6194 --i;
6195 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006196 break;
6197 case JUMP_IF_TRUE_OR_POP:
6198 assert (inst->i_target->b_iused == 1);
6199 inst->i_opcode = POP_JUMP_IF_FALSE;
6200 inst->i_target = inst->i_target->b_next;
Mark Shannon266b4622020-11-17 19:30:14 +00006201 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006202 break;
6203 }
6204 break;
6205
6206 case JUMP_IF_TRUE_OR_POP:
6207 switch(target->i_opcode) {
6208 case POP_JUMP_IF_TRUE:
6209 *inst = *target;
Mark Shannon266b4622020-11-17 19:30:14 +00006210 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006211 break;
6212 case JUMP_ABSOLUTE:
6213 case JUMP_FORWARD:
6214 case JUMP_IF_TRUE_OR_POP:
Mark Shannon266b4622020-11-17 19:30:14 +00006215 if (inst->i_target != target->i_target) {
6216 inst->i_target = target->i_target;
6217 --i;
6218 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006219 break;
6220 case JUMP_IF_FALSE_OR_POP:
6221 assert (inst->i_target->b_iused == 1);
6222 inst->i_opcode = POP_JUMP_IF_TRUE;
6223 inst->i_target = inst->i_target->b_next;
Mark Shannon266b4622020-11-17 19:30:14 +00006224 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006225 break;
6226 }
6227 break;
6228
6229 case POP_JUMP_IF_FALSE:
6230 switch(target->i_opcode) {
6231 case JUMP_ABSOLUTE:
6232 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006233 if (inst->i_target != target->i_target) {
6234 inst->i_target = target->i_target;
6235 --i;
6236 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006237 break;
6238 }
6239 break;
6240
6241 case POP_JUMP_IF_TRUE:
6242 switch(target->i_opcode) {
6243 case JUMP_ABSOLUTE:
6244 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006245 if (inst->i_target != target->i_target) {
6246 inst->i_target = target->i_target;
6247 --i;
6248 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006249 break;
6250 }
6251 break;
6252
6253 case JUMP_ABSOLUTE:
6254 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006255 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006256 switch(target->i_opcode) {
6257 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006258 if (inst->i_target != target->i_target) {
6259 inst->i_target = target->i_target;
Mark Shannon8473cf82020-12-15 11:07:50 +00006260// --i;
Mark Shannon266b4622020-11-17 19:30:14 +00006261 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006262 break;
6263 case JUMP_ABSOLUTE:
Mark Shannon266b4622020-11-17 19:30:14 +00006264 if (inst->i_target != target->i_target) {
6265 inst->i_target = target->i_target;
6266 inst->i_opcode = target->i_opcode;
6267 --i;
6268 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006269 break;
6270 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006271 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6272 basicblock *to_copy = inst->i_target;
Mark Shannon8473cf82020-12-15 11:07:50 +00006273 inst->i_opcode = NOP;
6274 for (i = 0; i < to_copy->b_iused; i++) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006275 int index = compiler_next_instr(bb);
6276 if (index < 0) {
6277 return -1;
6278 }
6279 bb->b_instr[index] = to_copy->b_instr[i];
6280 }
6281 bb->b_exit = 1;
6282 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006283 break;
6284 }
6285 }
6286 return 0;
6287error:
6288 return -1;
6289}
6290
6291
6292static void
6293clean_basic_block(basicblock *bb) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006294 /* Remove NOPs. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006295 int dest = 0;
Mark Shannon877df852020-11-12 09:43:29 +00006296 int prev_lineno = -1;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006297 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006298 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006299 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006300 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006301 if (lineno < 0) {
6302 continue;
6303 }
Mark Shannon266b4622020-11-17 19:30:14 +00006304 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006305 if (prev_lineno == lineno) {
6306 continue;
6307 }
Mark Shannon266b4622020-11-17 19:30:14 +00006308 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006309 if (src < bb->b_iused - 1) {
6310 int next_lineno = bb->b_instr[src+1].i_lineno;
6311 if (next_lineno < 0 || next_lineno == lineno) {
6312 bb->b_instr[src+1].i_lineno = lineno;
6313 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006314 }
6315 }
Mark Shannon266b4622020-11-17 19:30:14 +00006316 else {
6317 basicblock* next = bb->b_next;
6318 while (next && next->b_iused == 0) {
6319 next = next->b_next;
6320 }
6321 /* or if last instruction in BB and next BB has same line number */
6322 if (next) {
6323 if (lineno == next->b_instr[0].i_lineno) {
6324 continue;
6325 }
6326 }
6327 }
6328
Mark Shannon6e8128f2020-07-30 10:03:00 +01006329 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006330 if (dest != src) {
6331 bb->b_instr[dest] = bb->b_instr[src];
6332 }
6333 dest++;
6334 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006335 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006336 assert(dest <= bb->b_iused);
6337 bb->b_iused = dest;
6338}
6339
Mark Shannon266b4622020-11-17 19:30:14 +00006340static int
6341normalize_basic_block(basicblock *bb) {
6342 /* Mark blocks as exit and/or nofallthrough.
6343 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006344 for (int i = 0; i < bb->b_iused; i++) {
6345 switch(bb->b_instr[i].i_opcode) {
6346 case RETURN_VALUE:
6347 case RAISE_VARARGS:
6348 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006349 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00006350 bb->b_nofallthrough = 1;
6351 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006352 case JUMP_ABSOLUTE:
6353 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006354 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006355 /* fall through */
6356 case POP_JUMP_IF_FALSE:
6357 case POP_JUMP_IF_TRUE:
6358 case JUMP_IF_FALSE_OR_POP:
6359 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00006360 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00006361 if (i != bb->b_iused-1) {
6362 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6363 return -1;
6364 }
Mark Shannon5977a792020-12-02 13:31:40 +00006365 /* Skip over empty basic blocks. */
6366 while (bb->b_instr[i].i_target->b_iused == 0) {
6367 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
6368 }
6369
Mark Shannoncc75ab72020-11-12 19:49:33 +00006370 }
6371 }
Mark Shannon266b4622020-11-17 19:30:14 +00006372 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006373}
6374
Mark Shannon6e8128f2020-07-30 10:03:00 +01006375static int
6376mark_reachable(struct assembler *a) {
6377 basicblock **stack, **sp;
6378 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6379 if (stack == NULL) {
6380 return -1;
6381 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006382 a->a_entry->b_reachable = 1;
6383 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006384 while (sp > stack) {
6385 basicblock *b = *(--sp);
Mark Shannoncc75ab72020-11-12 19:49:33 +00006386 if (b->b_next && !b->b_nofallthrough && b->b_next->b_reachable == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006387 b->b_next->b_reachable = 1;
6388 *sp++ = b->b_next;
6389 }
6390 for (int i = 0; i < b->b_iused; i++) {
6391 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006392 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006393 target = b->b_instr[i].i_target;
6394 if (target->b_reachable == 0) {
6395 target->b_reachable = 1;
6396 *sp++ = target;
6397 }
6398 }
6399 }
6400 }
6401 PyObject_Free(stack);
6402 return 0;
6403}
6404
Mark Shannon5977a792020-12-02 13:31:40 +00006405/* If an instruction has no line number, but it's predecessor in the BB does,
6406 * then copy the line number. This reduces the size of the line number table,
6407 * but has no impact on the generated line number events.
6408 */
6409static void
6410minimize_lineno_table(struct assembler *a) {
6411 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6412 int prev_lineno = -1;
6413 for (int i = 0; i < b->b_iused; i++) {
6414 if (b->b_instr[i].i_lineno < 0) {
6415 b->b_instr[i].i_lineno = prev_lineno;
6416 }
6417 else {
6418 prev_lineno = b->b_instr[i].i_lineno;
6419 }
6420 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006421
Mark Shannon5977a792020-12-02 13:31:40 +00006422 }
6423}
6424
6425/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01006426 The consts object should still be in list form to allow new constants
6427 to be appended.
6428
6429 All transformations keep the code size the same or smaller.
6430 For those that reduce size, the gaps are initially filled with
6431 NOPs. Later those NOPs are removed.
6432*/
6433
6434static int
6435optimize_cfg(struct assembler *a, PyObject *consts)
6436{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006437 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006438 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006439 return -1;
6440 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006441 clean_basic_block(b);
6442 assert(b->b_reachable == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006443 }
6444 if (mark_reachable(a)) {
6445 return -1;
6446 }
6447 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006448 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6449 if (b->b_reachable == 0) {
6450 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05306451 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006452 }
6453 }
Om Gc71581c2020-12-16 17:48:05 +05306454 /* Delete jump instructions made redundant by previous step. If a non-empty
6455 block ends with a jump instruction, check if the next non-empty block
6456 reached through normal flow control is the target of that jump. If it
6457 is, then the jump instruction is redundant and can be deleted.
6458 */
6459 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6460 if (b->b_iused > 0) {
6461 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
6462 if (b_last_instr->i_opcode == POP_JUMP_IF_FALSE ||
6463 b_last_instr->i_opcode == POP_JUMP_IF_TRUE ||
6464 b_last_instr->i_opcode == JUMP_ABSOLUTE ||
6465 b_last_instr->i_opcode == JUMP_FORWARD) {
6466 basicblock *b_next_act = b->b_next;
6467 while (b_next_act != NULL && b_next_act->b_iused == 0) {
6468 b_next_act = b_next_act->b_next;
6469 }
6470 if (b_last_instr->i_target == b_next_act) {
6471 b->b_nofallthrough = 0;
6472 switch(b_last_instr->i_opcode) {
6473 case POP_JUMP_IF_FALSE:
6474 case POP_JUMP_IF_TRUE:
6475 b_last_instr->i_opcode = POP_TOP;
6476 b_last_instr->i_target = NULL;
6477 b_last_instr->i_oparg = 0;
6478 break;
6479 case JUMP_ABSOLUTE:
6480 case JUMP_FORWARD:
6481 b_last_instr->i_opcode = NOP;
6482 clean_basic_block(b);
6483 break;
6484 }
6485 /* The blocks after this one are now reachable through it */
6486 b_next_act = b->b_next;
6487 while (b_next_act != NULL && b_next_act->b_iused == 0) {
6488 b_next_act->b_reachable = 1;
6489 b_next_act = b_next_act->b_next;
6490 }
6491 }
6492 }
6493 }
6494 }
Mark Shannon5977a792020-12-02 13:31:40 +00006495 minimize_lineno_table(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006496 return 0;
6497}
6498
Mark Shannon5977a792020-12-02 13:31:40 +00006499static inline int
6500is_exit_without_lineno(basicblock *b) {
6501 return b->b_exit && b->b_instr[0].i_lineno < 0;
6502}
6503
6504/* PEP 626 mandates that the f_lineno of a frame is correct
6505 * after a frame terminates. It would be prohibitively expensive
6506 * to continuously update the f_lineno field at runtime,
6507 * so we make sure that all exiting instruction (raises and returns)
6508 * have a valid line number, allowing us to compute f_lineno lazily.
6509 * We can do this by duplicating the exit blocks without line number
6510 * so that none have more than one predecessor. We can then safely
6511 * copy the line number from the sole predecessor block.
6512 */
6513static int
6514ensure_exits_have_lineno(struct compiler *c)
6515{
Mark Shannoneaccc122020-12-04 15:22:12 +00006516 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006517 /* Copy all exit blocks without line number that are targets of a jump.
6518 */
6519 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6520 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
6521 switch (b->b_instr[b->b_iused-1].i_opcode) {
6522 /* Note: Only actual jumps, not exception handlers */
6523 case SETUP_ASYNC_WITH:
6524 case SETUP_WITH:
6525 case SETUP_FINALLY:
6526 continue;
6527 }
6528 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6529 if (is_exit_without_lineno(target)) {
6530 basicblock *new_target = compiler_copy_block(c, target);
6531 if (new_target == NULL) {
6532 return -1;
6533 }
6534 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6535 b->b_instr[b->b_iused-1].i_target = new_target;
6536 }
6537 }
Mark Shannoneaccc122020-12-04 15:22:12 +00006538 entry = b;
6539 }
6540 assert(entry != NULL);
6541 if (is_exit_without_lineno(entry)) {
6542 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00006543 }
6544 /* Any remaining reachable exit blocks without line number can only be reached by
6545 * fall through, and thus can only have a single predecessor */
6546 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6547 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
6548 if (is_exit_without_lineno(b->b_next)) {
6549 assert(b->b_next->b_iused > 0);
6550 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6551 }
6552 }
6553 }
6554 return 0;
6555}
6556
6557
Mark Shannon6e8128f2020-07-30 10:03:00 +01006558/* Retained for API compatibility.
6559 * Optimization is now done in optimize_cfg */
6560
6561PyObject *
6562PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6563 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6564{
6565 Py_INCREF(code);
6566 return code;
6567}
6568