blob: 57aa43476becd5259e77a723fe13c7948a6915f0 [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);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200231static int expr_constant(expr_ty);
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
815/* Returns the offset of the next instruction in the current block's
816 b_instr array. Resizes the b_instr as necessary.
817 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000818*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819
820static int
Andy Lester76d58772020-03-10 21:18:12 -0500821compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 assert(b != NULL);
824 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500825 b->b_instr = (struct instr *)PyObject_Calloc(
826 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (b->b_instr == NULL) {
828 PyErr_NoMemory();
829 return -1;
830 }
831 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 }
833 else if (b->b_iused == b->b_ialloc) {
834 struct instr *tmp;
835 size_t oldsize, newsize;
836 oldsize = b->b_ialloc * sizeof(struct instr);
837 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000838
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700839 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyErr_NoMemory();
841 return -1;
842 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (newsize == 0) {
845 PyErr_NoMemory();
846 return -1;
847 }
848 b->b_ialloc <<= 1;
849 tmp = (struct instr *)PyObject_Realloc(
850 (void *)b->b_instr, newsize);
851 if (tmp == NULL) {
852 PyErr_NoMemory();
853 return -1;
854 }
855 b->b_instr = tmp;
856 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
857 }
858 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859}
860
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200861/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000862
Christian Heimes2202f872008-02-06 14:31:34 +0000863 The line number is reset in the following cases:
864 - when entering a new scope
865 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200866 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200867 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000868*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000869
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200870#define SET_LOC(c, x) \
871 (c)->u->u_lineno = (x)->lineno; \
872 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200874/* Return the stack effect of opcode with argument oparg.
875
876 Some opcodes have different stack effect when jump to the target and
877 when not jump. The 'jump' parameter specifies the case:
878
879 * 0 -- when not jump
880 * 1 -- when jump
881 * -1 -- maximal
882 */
883/* XXX Make the stack effect of WITH_CLEANUP_START and
884 WITH_CLEANUP_FINISH deterministic. */
885static int
886stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300889 case NOP:
890 case EXTENDED_ARG:
891 return 0;
892
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200893 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 case POP_TOP:
895 return -1;
896 case ROT_TWO:
897 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200898 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return 0;
900 case DUP_TOP:
901 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000902 case DUP_TOP_TWO:
903 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000904
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200905 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case UNARY_POSITIVE:
907 case UNARY_NEGATIVE:
908 case UNARY_NOT:
909 case UNARY_INVERT:
910 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 case SET_ADD:
913 case LIST_APPEND:
914 return -1;
915 case MAP_ADD:
916 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000917
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200918 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 case BINARY_POWER:
920 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400921 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case BINARY_MODULO:
923 case BINARY_ADD:
924 case BINARY_SUBTRACT:
925 case BINARY_SUBSCR:
926 case BINARY_FLOOR_DIVIDE:
927 case BINARY_TRUE_DIVIDE:
928 return -1;
929 case INPLACE_FLOOR_DIVIDE:
930 case INPLACE_TRUE_DIVIDE:
931 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case INPLACE_ADD:
934 case INPLACE_SUBTRACT:
935 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400936 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 case INPLACE_MODULO:
938 return -1;
939 case STORE_SUBSCR:
940 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case DELETE_SUBSCR:
942 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 case BINARY_LSHIFT:
945 case BINARY_RSHIFT:
946 case BINARY_AND:
947 case BINARY_XOR:
948 case BINARY_OR:
949 return -1;
950 case INPLACE_POWER:
951 return -1;
952 case GET_ITER:
953 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 case PRINT_EXPR:
956 return -1;
957 case LOAD_BUILD_CLASS:
958 return 1;
959 case INPLACE_LSHIFT:
960 case INPLACE_RSHIFT:
961 case INPLACE_AND:
962 case INPLACE_XOR:
963 case INPLACE_OR:
964 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200967 /* 1 in the normal flow.
968 * Restore the stack position and push 6 values before jumping to
969 * the handler if an exception be raised. */
970 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case RETURN_VALUE:
972 return -1;
973 case IMPORT_STAR:
974 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700975 case SETUP_ANNOTATIONS:
976 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case YIELD_VALUE:
978 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500979 case YIELD_FROM:
980 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case POP_BLOCK:
982 return 0;
983 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200984 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 case STORE_NAME:
987 return -1;
988 case DELETE_NAME:
989 return 0;
990 case UNPACK_SEQUENCE:
991 return oparg-1;
992 case UNPACK_EX:
993 return (oparg&0xFF) + (oparg>>8);
994 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200995 /* -1 at end of iterator, 1 if continue iterating. */
996 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case STORE_ATTR:
999 return -2;
1000 case DELETE_ATTR:
1001 return -1;
1002 case STORE_GLOBAL:
1003 return -1;
1004 case DELETE_GLOBAL:
1005 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 case LOAD_CONST:
1007 return 1;
1008 case LOAD_NAME:
1009 return 1;
1010 case BUILD_TUPLE:
1011 case BUILD_LIST:
1012 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001013 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return 1-oparg;
1015 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001016 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001017 case BUILD_CONST_KEY_MAP:
1018 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case LOAD_ATTR:
1020 return 0;
1021 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001022 case IS_OP:
1023 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001025 case JUMP_IF_NOT_EXC_MATCH:
1026 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case IMPORT_NAME:
1028 return -1;
1029 case IMPORT_FROM:
1030 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001032 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case JUMP_ABSOLUTE:
1035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001037 case JUMP_IF_TRUE_OR_POP:
1038 case JUMP_IF_FALSE_OR_POP:
1039 return jump ? 0 : -1;
1040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case POP_JUMP_IF_FALSE:
1042 case POP_JUMP_IF_TRUE:
1043 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case LOAD_GLOBAL:
1046 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001048 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001050 /* 0 in the normal flow.
1051 * Restore the stack position and push 6 values before jumping to
1052 * the handler if an exception be raised. */
1053 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001054 case RERAISE:
1055 return -3;
1056
1057 case WITH_EXCEPT_START:
1058 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case LOAD_FAST:
1061 return 1;
1062 case STORE_FAST:
1063 return -1;
1064 case DELETE_FAST:
1065 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case RAISE_VARARGS:
1068 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001069
1070 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001072 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001073 case CALL_METHOD:
1074 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001076 return -oparg-1;
1077 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001078 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001079 case MAKE_FUNCTION:
1080 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1081 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 case BUILD_SLICE:
1083 if (oparg == 3)
1084 return -2;
1085 else
1086 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001088 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 case LOAD_CLOSURE:
1090 return 1;
1091 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001092 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 return 1;
1094 case STORE_DEREF:
1095 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001096 case DELETE_DEREF:
1097 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001098
1099 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001100 case GET_AWAITABLE:
1101 return 0;
1102 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001103 /* 0 in the normal flow.
1104 * Restore the stack position to the position before the result
1105 * of __aenter__ and push 6 values before jumping to the handler
1106 * if an exception be raised. */
1107 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001108 case BEFORE_ASYNC_WITH:
1109 return 1;
1110 case GET_AITER:
1111 return 0;
1112 case GET_ANEXT:
1113 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001114 case GET_YIELD_FROM_ITER:
1115 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001116 case END_ASYNC_FOR:
1117 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001118 case FORMAT_VALUE:
1119 /* If there's a fmt_spec on the stack, we go from 2->1,
1120 else 1->1. */
1121 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001122 case LOAD_METHOD:
1123 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001124 case LOAD_ASSERTION_ERROR:
1125 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001126 case LIST_TO_TUPLE:
1127 return 0;
1128 case LIST_EXTEND:
1129 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001130 case DICT_MERGE:
1131 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001132 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001134 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 }
Larry Hastings3a907972013-11-23 14:49:22 -08001136 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137}
1138
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001139int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001140PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1141{
1142 return stack_effect(opcode, oparg, jump);
1143}
1144
1145int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001146PyCompile_OpcodeStackEffect(int opcode, int oparg)
1147{
1148 return stack_effect(opcode, oparg, -1);
1149}
1150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151/* Add an opcode with no argument.
1152 Returns 0 on failure, 1 on success.
1153*/
1154
1155static int
1156compiler_addop(struct compiler *c, int opcode)
1157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 basicblock *b;
1159 struct instr *i;
1160 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001161 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001162 if (c->c_do_not_emit_bytecode) {
1163 return 1;
1164 }
Andy Lester76d58772020-03-10 21:18:12 -05001165 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (off < 0)
1167 return 0;
1168 b = c->u->u_curblock;
1169 i = &b->b_instr[off];
1170 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001171 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (opcode == RETURN_VALUE)
1173 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001174 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176}
1177
Victor Stinnerf8e32212013-11-19 23:56:34 +01001178static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001179compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001181 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001184 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001186 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001188 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001189 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001190 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 return -1;
1193 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001194 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 Py_DECREF(v);
1196 return -1;
1197 }
1198 Py_DECREF(v);
1199 }
1200 else
1201 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001202 return arg;
1203}
1204
INADA Naokic2e16072018-11-26 21:23:22 +09001205// Merge const *o* recursively and return constant key object.
1206static PyObject*
1207merge_consts_recursive(struct compiler *c, PyObject *o)
1208{
1209 // None and Ellipsis are singleton, and key is the singleton.
1210 // No need to merge object and key.
1211 if (o == Py_None || o == Py_Ellipsis) {
1212 Py_INCREF(o);
1213 return o;
1214 }
1215
1216 PyObject *key = _PyCode_ConstantKey(o);
1217 if (key == NULL) {
1218 return NULL;
1219 }
1220
1221 // t is borrowed reference
1222 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1223 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001224 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001225 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001226 Py_DECREF(key);
1227 return t;
1228 }
1229
INADA Naokif7e4d362018-11-29 00:58:46 +09001230 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001231 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001232 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001233 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001234 Py_ssize_t len = PyTuple_GET_SIZE(o);
1235 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001236 PyObject *item = PyTuple_GET_ITEM(o, i);
1237 PyObject *u = merge_consts_recursive(c, item);
1238 if (u == NULL) {
1239 Py_DECREF(key);
1240 return NULL;
1241 }
1242
1243 // See _PyCode_ConstantKey()
1244 PyObject *v; // borrowed
1245 if (PyTuple_CheckExact(u)) {
1246 v = PyTuple_GET_ITEM(u, 1);
1247 }
1248 else {
1249 v = u;
1250 }
1251 if (v != item) {
1252 Py_INCREF(v);
1253 PyTuple_SET_ITEM(o, i, v);
1254 Py_DECREF(item);
1255 }
1256
1257 Py_DECREF(u);
1258 }
1259 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001260 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001261 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001262 // constant keys.
1263 // See _PyCode_ConstantKey() for detail.
1264 assert(PyTuple_CheckExact(key));
1265 assert(PyTuple_GET_SIZE(key) == 2);
1266
1267 Py_ssize_t len = PySet_GET_SIZE(o);
1268 if (len == 0) { // empty frozenset should not be re-created.
1269 return key;
1270 }
1271 PyObject *tuple = PyTuple_New(len);
1272 if (tuple == NULL) {
1273 Py_DECREF(key);
1274 return NULL;
1275 }
1276 Py_ssize_t i = 0, pos = 0;
1277 PyObject *item;
1278 Py_hash_t hash;
1279 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1280 PyObject *k = merge_consts_recursive(c, item);
1281 if (k == NULL) {
1282 Py_DECREF(tuple);
1283 Py_DECREF(key);
1284 return NULL;
1285 }
1286 PyObject *u;
1287 if (PyTuple_CheckExact(k)) {
1288 u = PyTuple_GET_ITEM(k, 1);
1289 Py_INCREF(u);
1290 Py_DECREF(k);
1291 }
1292 else {
1293 u = k;
1294 }
1295 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1296 i++;
1297 }
1298
1299 // Instead of rewriting o, we create new frozenset and embed in the
1300 // key tuple. Caller should get merged frozenset from the key tuple.
1301 PyObject *new = PyFrozenSet_New(tuple);
1302 Py_DECREF(tuple);
1303 if (new == NULL) {
1304 Py_DECREF(key);
1305 return NULL;
1306 }
1307 assert(PyTuple_GET_ITEM(key, 1) == o);
1308 Py_DECREF(o);
1309 PyTuple_SET_ITEM(key, 1, new);
1310 }
INADA Naokic2e16072018-11-26 21:23:22 +09001311
1312 return key;
1313}
1314
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001315static Py_ssize_t
1316compiler_add_const(struct compiler *c, PyObject *o)
1317{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001318 if (c->c_do_not_emit_bytecode) {
1319 return 0;
1320 }
1321
INADA Naokic2e16072018-11-26 21:23:22 +09001322 PyObject *key = merge_consts_recursive(c, o);
1323 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001324 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001325 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001326
Andy Lester76d58772020-03-10 21:18:12 -05001327 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001328 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330}
1331
1332static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001333compiler_addop_load_const(struct compiler *c, PyObject *o)
1334{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001335 if (c->c_do_not_emit_bytecode) {
1336 return 1;
1337 }
1338
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001339 Py_ssize_t arg = compiler_add_const(c, o);
1340 if (arg < 0)
1341 return 0;
1342 return compiler_addop_i(c, LOAD_CONST, arg);
1343}
1344
1345static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001348{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001349 if (c->c_do_not_emit_bytecode) {
1350 return 1;
1351 }
1352
Andy Lester76d58772020-03-10 21:18:12 -05001353 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001355 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356 return compiler_addop_i(c, opcode, arg);
1357}
1358
1359static int
1360compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001363 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001364
1365 if (c->c_do_not_emit_bytecode) {
1366 return 1;
1367 }
1368
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1370 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001371 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001372 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373 Py_DECREF(mangled);
1374 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001375 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376 return compiler_addop_i(c, opcode, arg);
1377}
1378
1379/* Add an opcode with an integer argument.
1380 Returns 0 on failure, 1 on success.
1381*/
1382
1383static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001384compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 struct instr *i;
1387 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001388
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001389 if (c->c_do_not_emit_bytecode) {
1390 return 1;
1391 }
1392
Victor Stinner2ad474b2016-03-01 23:34:47 +01001393 /* oparg value is unsigned, but a signed C int is usually used to store
1394 it in the C code (like Python/ceval.c).
1395
1396 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1397
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001398 The argument of a concrete bytecode instruction is limited to 8-bit.
1399 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1400 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001401 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001402
Andy Lester76d58772020-03-10 21:18:12 -05001403 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 if (off < 0)
1405 return 0;
1406 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001407 i->i_opcode = opcode;
1408 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001409 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411}
1412
1413static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001414compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 struct instr *i;
1417 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001418
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001419 if (c->c_do_not_emit_bytecode) {
1420 return 1;
1421 }
1422
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001423 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 assert(b != NULL);
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];
1429 i->i_opcode = opcode;
1430 i->i_target = b;
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
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001435/* NEXT_BLOCK() creates an implicit jump from the current block
1436 to the new block.
1437
1438 The returns inside this macro make it impossible to decref objects
1439 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (compiler_next_block((C)) == NULL) \
1443 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444}
1445
1446#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (!compiler_addop((C), (OP))) \
1448 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449}
1450
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001451#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!compiler_addop((C), (OP))) { \
1453 compiler_exit_scope(c); \
1454 return 0; \
1455 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001456}
1457
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001458#define ADDOP_LOAD_CONST(C, O) { \
1459 if (!compiler_addop_load_const((C), (O))) \
1460 return 0; \
1461}
1462
1463/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1464#define ADDOP_LOAD_CONST_NEW(C, O) { \
1465 PyObject *__new_const = (O); \
1466 if (__new_const == NULL) { \
1467 return 0; \
1468 } \
1469 if (!compiler_addop_load_const((C), __new_const)) { \
1470 Py_DECREF(__new_const); \
1471 return 0; \
1472 } \
1473 Py_DECREF(__new_const); \
1474}
1475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1478 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479}
1480
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001481/* Same as ADDOP_O, but steals a reference. */
1482#define ADDOP_N(C, OP, O, TYPE) { \
1483 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1484 Py_DECREF((O)); \
1485 return 0; \
1486 } \
1487 Py_DECREF((O)); \
1488}
1489
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1492 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493}
1494
1495#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_i((C), (OP), (O))) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
Mark Shannon582aaf12020-08-04 17:30:11 +01001500#define ADDOP_JUMP(C, OP, O) { \
1501 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503}
1504
Mark Shannon9af0e472020-01-14 10:12:45 +00001505#define ADDOP_COMPARE(C, CMP) { \
1506 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1507 return 0; \
1508}
1509
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1511 the ASDL name to synthesize the name of the C type and the visit function.
1512*/
1513
1514#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (!compiler_visit_ ## TYPE((C), (V))) \
1516 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517}
1518
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001519#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (!compiler_visit_ ## TYPE((C), (V))) { \
1521 compiler_exit_scope(c); \
1522 return 0; \
1523 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001524}
1525
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (!compiler_visit_slice((C), (V), (CTX))) \
1528 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529}
1530
1531#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001533 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1535 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1536 if (!compiler_visit_ ## TYPE((C), elt)) \
1537 return 0; \
1538 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539}
1540
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001541#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001543 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1545 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1546 if (!compiler_visit_ ## TYPE((C), elt)) { \
1547 compiler_exit_scope(c); \
1548 return 0; \
1549 } \
1550 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001551}
1552
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001553/* These macros allows to check only for errors and not emmit bytecode
1554 * while visiting nodes.
1555*/
1556
1557#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1558 c->c_do_not_emit_bytecode++;
1559
1560#define END_DO_NOT_EMIT_BYTECODE \
1561 c->c_do_not_emit_bytecode--; \
1562}
1563
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001564/* Search if variable annotations are present statically in a block. */
1565
1566static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001567find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001568{
1569 int i, j, res = 0;
1570 stmt_ty st;
1571
1572 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1573 st = (stmt_ty)asdl_seq_GET(stmts, i);
1574 switch (st->kind) {
1575 case AnnAssign_kind:
1576 return 1;
1577 case For_kind:
1578 res = find_ann(st->v.For.body) ||
1579 find_ann(st->v.For.orelse);
1580 break;
1581 case AsyncFor_kind:
1582 res = find_ann(st->v.AsyncFor.body) ||
1583 find_ann(st->v.AsyncFor.orelse);
1584 break;
1585 case While_kind:
1586 res = find_ann(st->v.While.body) ||
1587 find_ann(st->v.While.orelse);
1588 break;
1589 case If_kind:
1590 res = find_ann(st->v.If.body) ||
1591 find_ann(st->v.If.orelse);
1592 break;
1593 case With_kind:
1594 res = find_ann(st->v.With.body);
1595 break;
1596 case AsyncWith_kind:
1597 res = find_ann(st->v.AsyncWith.body);
1598 break;
1599 case Try_kind:
1600 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1601 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1602 st->v.Try.handlers, j);
1603 if (find_ann(handler->v.ExceptHandler.body)) {
1604 return 1;
1605 }
1606 }
1607 res = find_ann(st->v.Try.body) ||
1608 find_ann(st->v.Try.finalbody) ||
1609 find_ann(st->v.Try.orelse);
1610 break;
1611 default:
1612 res = 0;
1613 }
1614 if (res) {
1615 break;
1616 }
1617 }
1618 return res;
1619}
1620
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001621/*
1622 * Frame block handling functions
1623 */
1624
1625static int
1626compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001627 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001628{
1629 struct fblockinfo *f;
1630 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001631 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001632 }
1633 f = &c->u->u_fblock[c->u->u_nfblocks++];
1634 f->fb_type = t;
1635 f->fb_block = b;
1636 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001637 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001638 return 1;
1639}
1640
1641static void
1642compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1643{
1644 struct compiler_unit *u = c->u;
1645 assert(u->u_nfblocks > 0);
1646 u->u_nfblocks--;
1647 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1648 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1649}
1650
Mark Shannonfee55262019-11-21 09:11:43 +00001651static int
1652compiler_call_exit_with_nones(struct compiler *c) {
1653 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1654 ADDOP(c, DUP_TOP);
1655 ADDOP(c, DUP_TOP);
1656 ADDOP_I(c, CALL_FUNCTION, 3);
1657 return 1;
1658}
1659
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001660/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001661 * popping the blocks will be restored afterwards, unless another
1662 * return, break or continue is found. In which case, the TOS will
1663 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001664 */
1665static int
1666compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1667 int preserve_tos)
1668{
1669 switch (info->fb_type) {
1670 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001671 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001672 return 1;
1673
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001674 case FOR_LOOP:
1675 /* Pop the iterator */
1676 if (preserve_tos) {
1677 ADDOP(c, ROT_TWO);
1678 }
1679 ADDOP(c, POP_TOP);
1680 return 1;
1681
Mark Shannon02d126a2020-09-25 14:04:19 +01001682 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001683 ADDOP(c, POP_BLOCK);
1684 return 1;
1685
1686 case FINALLY_TRY:
1687 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001688 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001689 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1690 return 0;
1691 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001692 }
Mark Shannon88dce262019-12-30 09:53:36 +00001693 /* Emit the finally block, restoring the line number when done */
1694 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001695 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001696 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001697 if (preserve_tos) {
1698 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001699 }
1700 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001701
Mark Shannonfee55262019-11-21 09:11:43 +00001702 case FINALLY_END:
1703 if (preserve_tos) {
1704 ADDOP(c, ROT_FOUR);
1705 }
1706 ADDOP(c, POP_TOP);
1707 ADDOP(c, POP_TOP);
1708 ADDOP(c, POP_TOP);
1709 if (preserve_tos) {
1710 ADDOP(c, ROT_FOUR);
1711 }
1712 ADDOP(c, POP_EXCEPT);
1713 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001714
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001715 case WITH:
1716 case ASYNC_WITH:
1717 ADDOP(c, POP_BLOCK);
1718 if (preserve_tos) {
1719 ADDOP(c, ROT_TWO);
1720 }
Mark Shannonfee55262019-11-21 09:11:43 +00001721 if(!compiler_call_exit_with_nones(c)) {
1722 return 0;
1723 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001724 if (info->fb_type == ASYNC_WITH) {
1725 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001726 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001727 ADDOP(c, YIELD_FROM);
1728 }
Mark Shannonfee55262019-11-21 09:11:43 +00001729 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001730 return 1;
1731
1732 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001733 if (info->fb_datum) {
1734 ADDOP(c, POP_BLOCK);
1735 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001736 if (preserve_tos) {
1737 ADDOP(c, ROT_FOUR);
1738 }
Mark Shannonfee55262019-11-21 09:11:43 +00001739 ADDOP(c, POP_EXCEPT);
1740 if (info->fb_datum) {
1741 ADDOP_LOAD_CONST(c, Py_None);
1742 compiler_nameop(c, info->fb_datum, Store);
1743 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001744 }
Mark Shannonfee55262019-11-21 09:11:43 +00001745 return 1;
1746
1747 case POP_VALUE:
1748 if (preserve_tos) {
1749 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001750 }
Mark Shannonfee55262019-11-21 09:11:43 +00001751 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001752 return 1;
1753 }
1754 Py_UNREACHABLE();
1755}
1756
Mark Shannonfee55262019-11-21 09:11:43 +00001757/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1758static int
1759compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1760 if (c->u->u_nfblocks == 0) {
1761 return 1;
1762 }
1763 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1764 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1765 *loop = top;
1766 return 1;
1767 }
1768 struct fblockinfo copy = *top;
1769 c->u->u_nfblocks--;
1770 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1771 return 0;
1772 }
1773 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1774 return 0;
1775 }
1776 c->u->u_fblock[c->u->u_nfblocks] = copy;
1777 c->u->u_nfblocks++;
1778 return 1;
1779}
1780
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001781/* Compile a sequence of statements, checking for a docstring
1782 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783
1784static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001785compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001787 int i = 0;
1788 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001789 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001790
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001791 /* Set current line number to the line number of first statement.
1792 This way line number for SETUP_ANNOTATIONS will always
1793 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301794 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001795 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001796 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001797 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001798 }
1799 /* Every annotated class and module should have __annotations__. */
1800 if (find_ann(stmts)) {
1801 ADDOP(c, SETUP_ANNOTATIONS);
1802 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001803 if (!asdl_seq_LEN(stmts))
1804 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001805 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001806 if (c->c_optimize < 2) {
1807 docstring = _PyAST_GetDocString(stmts);
1808 if (docstring) {
1809 i = 1;
1810 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1811 assert(st->kind == Expr_kind);
1812 VISIT(c, expr, st->v.Expr.value);
1813 if (!compiler_nameop(c, __doc__, Store))
1814 return 0;
1815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001817 for (; i < asdl_seq_LEN(stmts); i++)
1818 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820}
1821
1822static PyCodeObject *
1823compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 PyCodeObject *co;
1826 int addNone = 1;
1827 static PyObject *module;
1828 if (!module) {
1829 module = PyUnicode_InternFromString("<module>");
1830 if (!module)
1831 return NULL;
1832 }
1833 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001834 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return NULL;
1836 switch (mod->kind) {
1837 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001838 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 compiler_exit_scope(c);
1840 return 0;
1841 }
1842 break;
1843 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001844 if (find_ann(mod->v.Interactive.body)) {
1845 ADDOP(c, SETUP_ANNOTATIONS);
1846 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001848 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 break;
1850 case Expression_kind:
1851 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1852 addNone = 0;
1853 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 default:
1855 PyErr_Format(PyExc_SystemError,
1856 "module kind %d should not be possible",
1857 mod->kind);
1858 return 0;
1859 }
1860 co = assemble(c, addNone);
1861 compiler_exit_scope(c);
1862 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001863}
1864
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865/* The test for LOCAL must come before the test for FREE in order to
1866 handle classes where name is both local and free. The local var is
1867 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001868*/
1869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870static int
1871get_ref_type(struct compiler *c, PyObject *name)
1872{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001873 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001874 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001875 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001876 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001877 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001879 _Py_FatalErrorFormat(__func__,
1880 "unknown scope for %.100s in %.100s(%s)\n"
1881 "symbols: %s\nlocals: %s\nglobals: %s",
1882 PyUnicode_AsUTF8(name),
1883 PyUnicode_AsUTF8(c->u->u_name),
1884 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1885 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1886 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1887 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891}
1892
1893static int
1894compiler_lookup_arg(PyObject *dict, PyObject *name)
1895{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001896 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001897 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001899 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001900 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901}
1902
1903static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001904compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001906 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001907 if (qualname == NULL)
1908 qualname = co->co_name;
1909
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910 if (free) {
1911 for (i = 0; i < free; ++i) {
1912 /* Bypass com_addop_varname because it will generate
1913 LOAD_DEREF but LOAD_CLOSURE is needed.
1914 */
1915 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1916 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001918 /* Special case: If a class contains a method with a
1919 free variable that has the same name as a method,
1920 the name will be considered free *and* local in the
1921 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001922 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001923 */
1924 reftype = get_ref_type(c, name);
1925 if (reftype == CELL)
1926 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1927 else /* (reftype == FREE) */
1928 arg = compiler_lookup_arg(c->u->u_freevars, name);
1929 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001930 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001931 "lookup %s in %s %d %d\n"
1932 "freevars of %s: %s\n",
1933 PyUnicode_AsUTF8(PyObject_Repr(name)),
1934 PyUnicode_AsUTF8(c->u->u_name),
1935 reftype, arg,
1936 PyUnicode_AsUTF8(co->co_name),
1937 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001938 }
1939 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 flags |= 0x08;
1942 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001944 ADDOP_LOAD_CONST(c, (PyObject*)co);
1945 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001946 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948}
1949
1950static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001951compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 if (!decos)
1956 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1959 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1960 }
1961 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962}
1963
1964static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001965compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1966 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001967{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001968 /* Push a dict of keyword-only default values.
1969
1970 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1971 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001972 int i;
1973 PyObject *keys = NULL;
1974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1976 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1977 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1978 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001979 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001980 if (!mangled) {
1981 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001983 if (keys == NULL) {
1984 keys = PyList_New(1);
1985 if (keys == NULL) {
1986 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001987 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001988 }
1989 PyList_SET_ITEM(keys, 0, mangled);
1990 }
1991 else {
1992 int res = PyList_Append(keys, mangled);
1993 Py_DECREF(mangled);
1994 if (res == -1) {
1995 goto error;
1996 }
1997 }
1998 if (!compiler_visit_expr(c, default_)) {
1999 goto error;
2000 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
2002 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002003 if (keys != NULL) {
2004 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2005 PyObject *keys_tuple = PyList_AsTuple(keys);
2006 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002007 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002008 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002009 assert(default_count > 0);
2010 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 }
2012 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002013 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002014 }
2015
2016error:
2017 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002018 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002019}
2020
2021static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002022compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2023{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002024 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002025 return 1;
2026}
2027
2028static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002029compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002030 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002033 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002034 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002035 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002036
2037 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002038 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002039 VISIT(c, annexpr, annotation);
2040 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002042 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002043}
2044
2045static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002046compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002047 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002048{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002049 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 for (i = 0; i < asdl_seq_LEN(args); i++) {
2051 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002052 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 c,
2054 arg->arg,
2055 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002056 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002057 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002059 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002060}
2061
2062static int
2063compiler_visit_annotations(struct compiler *c, arguments_ty args,
2064 expr_ty returns)
2065{
Yurii Karabas73019792020-11-25 12:43:18 +02002066 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002067 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002068
Yurii Karabas73019792020-11-25 12:43:18 +02002069 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 */
2071 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002072 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002073
Yurii Karabas73019792020-11-25 12:43:18 +02002074 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2075 return 0;
2076 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2077 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002078 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002079 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002080 args->vararg->annotation, &annotations_len))
2081 return 0;
2082 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2083 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002084 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002085 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002086 args->kwarg->annotation, &annotations_len))
2087 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (!return_str) {
2090 return_str = PyUnicode_InternFromString("return");
2091 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002092 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 }
Yurii Karabas73019792020-11-25 12:43:18 +02002094 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2095 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 }
2097
Yurii Karabas73019792020-11-25 12:43:18 +02002098 if (annotations_len) {
2099 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002100 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002102
Yurii Karabas73019792020-11-25 12:43:18 +02002103 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002104}
2105
2106static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002107compiler_visit_defaults(struct compiler *c, arguments_ty args)
2108{
2109 VISIT_SEQ(c, expr, args->defaults);
2110 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2111 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112}
2113
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002114static Py_ssize_t
2115compiler_default_arguments(struct compiler *c, arguments_ty args)
2116{
2117 Py_ssize_t funcflags = 0;
2118 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002119 if (!compiler_visit_defaults(c, args))
2120 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002121 funcflags |= 0x01;
2122 }
2123 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002124 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002125 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002126 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002127 return -1;
2128 }
2129 else if (res > 0) {
2130 funcflags |= 0x02;
2131 }
2132 }
2133 return funcflags;
2134}
2135
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002137forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2138{
2139
2140 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2141 compiler_error(c, "cannot assign to __debug__");
2142 return 1;
2143 }
2144 return 0;
2145}
2146
2147static int
2148compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2149{
2150 if (arg != NULL) {
2151 if (forbidden_name(c, arg->arg, Store))
2152 return 0;
2153 }
2154 return 1;
2155}
2156
2157static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002158compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002159{
2160 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002161 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002162 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2163 return 0;
2164 }
2165 }
2166 return 1;
2167}
2168
2169static int
2170compiler_check_debug_args(struct compiler *c, arguments_ty args)
2171{
2172 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2173 return 0;
2174 if (!compiler_check_debug_args_seq(c, args->args))
2175 return 0;
2176 if (!compiler_check_debug_one_arg(c, args->vararg))
2177 return 0;
2178 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2179 return 0;
2180 if (!compiler_check_debug_one_arg(c, args->kwarg))
2181 return 0;
2182 return 1;
2183}
2184
2185static int
Yury Selivanov75445082015-05-11 22:57:16 -04002186compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002189 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002190 arguments_ty args;
2191 expr_ty returns;
2192 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002193 asdl_expr_seq* decos;
2194 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002195 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002196 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002197 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002198 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199
Yury Selivanov75445082015-05-11 22:57:16 -04002200 if (is_async) {
2201 assert(s->kind == AsyncFunctionDef_kind);
2202
2203 args = s->v.AsyncFunctionDef.args;
2204 returns = s->v.AsyncFunctionDef.returns;
2205 decos = s->v.AsyncFunctionDef.decorator_list;
2206 name = s->v.AsyncFunctionDef.name;
2207 body = s->v.AsyncFunctionDef.body;
2208
2209 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2210 } else {
2211 assert(s->kind == FunctionDef_kind);
2212
2213 args = s->v.FunctionDef.args;
2214 returns = s->v.FunctionDef.returns;
2215 decos = s->v.FunctionDef.decorator_list;
2216 name = s->v.FunctionDef.name;
2217 body = s->v.FunctionDef.body;
2218
2219 scope_type = COMPILER_SCOPE_FUNCTION;
2220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002222 if (!compiler_check_debug_args(c, args))
2223 return 0;
2224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (!compiler_decorators(c, decos))
2226 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002227
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002228 firstlineno = s->lineno;
2229 if (asdl_seq_LEN(decos)) {
2230 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2231 }
2232
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002233 funcflags = compiler_default_arguments(c, args);
2234 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002236 }
2237
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002238 annotations = compiler_visit_annotations(c, args, returns);
2239 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002240 return 0;
2241 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002242 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002243 funcflags |= 0x04;
2244 }
2245
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002246 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002247 return 0;
2248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249
INADA Naokicb41b272017-02-23 00:31:59 +09002250 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002251 if (c->c_optimize < 2) {
2252 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002253 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002254 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 compiler_exit_scope(c);
2256 return 0;
2257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002260 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002262 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002263 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002266 qualname = c->u->u_qualname;
2267 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002269 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002270 Py_XDECREF(qualname);
2271 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002275 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002276 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* decorators */
2280 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2281 ADDOP_I(c, CALL_FUNCTION, 1);
2282 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002283
Yury Selivanov75445082015-05-11 22:57:16 -04002284 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
2287static int
2288compiler_class(struct compiler *c, stmt_ty s)
2289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 PyCodeObject *co;
2291 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002292 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002293 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (!compiler_decorators(c, decos))
2296 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002297
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002298 firstlineno = s->lineno;
2299 if (asdl_seq_LEN(decos)) {
2300 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2301 }
2302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* ultimately generate code for:
2304 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2305 where:
2306 <func> is a function/closure created from the class body;
2307 it has a single argument (__locals__) where the dict
2308 (or MutableSequence) representing the locals is passed
2309 <name> is the class name
2310 <bases> is the positional arguments and *varargs argument
2311 <keywords> is the keyword arguments and **kwds argument
2312 This borrows from compiler_call.
2313 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002316 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002317 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 return 0;
2319 /* this block represents what we do in the new scope */
2320 {
2321 /* use the class name for name mangling */
2322 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002323 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* load (global) __name__ ... */
2325 str = PyUnicode_InternFromString("__name__");
2326 if (!str || !compiler_nameop(c, str, Load)) {
2327 Py_XDECREF(str);
2328 compiler_exit_scope(c);
2329 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 Py_DECREF(str);
2332 /* ... and store it as __module__ */
2333 str = PyUnicode_InternFromString("__module__");
2334 if (!str || !compiler_nameop(c, str, Store)) {
2335 Py_XDECREF(str);
2336 compiler_exit_scope(c);
2337 return 0;
2338 }
2339 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002340 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002341 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002342 str = PyUnicode_InternFromString("__qualname__");
2343 if (!str || !compiler_nameop(c, str, Store)) {
2344 Py_XDECREF(str);
2345 compiler_exit_scope(c);
2346 return 0;
2347 }
2348 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002350 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 compiler_exit_scope(c);
2352 return 0;
2353 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002354 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002355 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002356 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002357 str = PyUnicode_InternFromString("__class__");
2358 if (str == NULL) {
2359 compiler_exit_scope(c);
2360 return 0;
2361 }
2362 i = compiler_lookup_arg(c->u->u_cellvars, str);
2363 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002364 if (i < 0) {
2365 compiler_exit_scope(c);
2366 return 0;
2367 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002368 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002371 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002372 str = PyUnicode_InternFromString("__classcell__");
2373 if (!str || !compiler_nameop(c, str, Store)) {
2374 Py_XDECREF(str);
2375 compiler_exit_scope(c);
2376 return 0;
2377 }
2378 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002380 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002381 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002382 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002383 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002384 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002385 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* create the code object */
2387 co = assemble(c, 1);
2388 }
2389 /* leave the new scope */
2390 compiler_exit_scope(c);
2391 if (co == NULL)
2392 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* 2. load the 'build_class' function */
2395 ADDOP(c, LOAD_BUILD_CLASS);
2396
2397 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002398 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 Py_DECREF(co);
2400
2401 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002402 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403
2404 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002405 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return 0;
2407
2408 /* 6. apply decorators */
2409 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2410 ADDOP_I(c, CALL_FUNCTION, 1);
2411 }
2412
2413 /* 7. store into <name> */
2414 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2415 return 0;
2416 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417}
2418
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002419/* Return 0 if the expression is a constant value except named singletons.
2420 Return 1 otherwise. */
2421static int
2422check_is_arg(expr_ty e)
2423{
2424 if (e->kind != Constant_kind) {
2425 return 1;
2426 }
2427 PyObject *value = e->v.Constant.value;
2428 return (value == Py_None
2429 || value == Py_False
2430 || value == Py_True
2431 || value == Py_Ellipsis);
2432}
2433
2434/* Check operands of identity chacks ("is" and "is not").
2435 Emit a warning if any operand is a constant except named singletons.
2436 Return 0 on error.
2437 */
2438static int
2439check_compare(struct compiler *c, expr_ty e)
2440{
2441 Py_ssize_t i, n;
2442 int left = check_is_arg(e->v.Compare.left);
2443 n = asdl_seq_LEN(e->v.Compare.ops);
2444 for (i = 0; i < n; i++) {
2445 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2446 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2447 if (op == Is || op == IsNot) {
2448 if (!right || !left) {
2449 const char *msg = (op == Is)
2450 ? "\"is\" with a literal. Did you mean \"==\"?"
2451 : "\"is not\" with a literal. Did you mean \"!=\"?";
2452 return compiler_warn(c, msg);
2453 }
2454 }
2455 left = right;
2456 }
2457 return 1;
2458}
2459
Mark Shannon9af0e472020-01-14 10:12:45 +00002460static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002461{
Mark Shannon9af0e472020-01-14 10:12:45 +00002462 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002463 switch (op) {
2464 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002465 cmp = Py_EQ;
2466 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002467 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002468 cmp = Py_NE;
2469 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002470 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002471 cmp = Py_LT;
2472 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002473 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002474 cmp = Py_LE;
2475 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002476 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002477 cmp = Py_GT;
2478 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002479 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002480 cmp = Py_GE;
2481 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002482 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002483 ADDOP_I(c, IS_OP, 0);
2484 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002486 ADDOP_I(c, IS_OP, 1);
2487 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002488 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002489 ADDOP_I(c, CONTAINS_OP, 0);
2490 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002491 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002492 ADDOP_I(c, CONTAINS_OP, 1);
2493 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002494 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002495 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002496 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002497 ADDOP_I(c, COMPARE_OP, cmp);
2498 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002499}
2500
Mark Shannon9af0e472020-01-14 10:12:45 +00002501
2502
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002503static int
2504compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2505{
2506 switch (e->kind) {
2507 case UnaryOp_kind:
2508 if (e->v.UnaryOp.op == Not)
2509 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2510 /* fallback to general implementation */
2511 break;
2512 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002513 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002514 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2515 assert(n >= 0);
2516 int cond2 = e->v.BoolOp.op == Or;
2517 basicblock *next2 = next;
2518 if (!cond2 != !cond) {
2519 next2 = compiler_new_block(c);
2520 if (next2 == NULL)
2521 return 0;
2522 }
2523 for (i = 0; i < n; ++i) {
2524 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2525 return 0;
2526 }
2527 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2528 return 0;
2529 if (next2 != next)
2530 compiler_use_next_block(c, next2);
2531 return 1;
2532 }
2533 case IfExp_kind: {
2534 basicblock *end, *next2;
2535 end = compiler_new_block(c);
2536 if (end == NULL)
2537 return 0;
2538 next2 = compiler_new_block(c);
2539 if (next2 == NULL)
2540 return 0;
2541 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2542 return 0;
2543 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2544 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002545 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002546 compiler_use_next_block(c, next2);
2547 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2548 return 0;
2549 compiler_use_next_block(c, end);
2550 return 1;
2551 }
2552 case Compare_kind: {
2553 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2554 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002555 if (!check_compare(c, e)) {
2556 return 0;
2557 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002558 basicblock *cleanup = compiler_new_block(c);
2559 if (cleanup == NULL)
2560 return 0;
2561 VISIT(c, expr, e->v.Compare.left);
2562 for (i = 0; i < n; i++) {
2563 VISIT(c, expr,
2564 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2565 ADDOP(c, DUP_TOP);
2566 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002567 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002568 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002569 NEXT_BLOCK(c);
2570 }
2571 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002572 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002573 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002574 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002575 basicblock *end = compiler_new_block(c);
2576 if (end == NULL)
2577 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002578 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002579 compiler_use_next_block(c, cleanup);
2580 ADDOP(c, POP_TOP);
2581 if (!cond) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002582 ADDOP_JUMP(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002583 }
2584 compiler_use_next_block(c, end);
2585 return 1;
2586 }
2587 /* fallback to general implementation */
2588 break;
2589 }
2590 default:
2591 /* fallback to general implementation */
2592 break;
2593 }
2594
2595 /* general implementation */
2596 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002597 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002598 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002599 return 1;
2600}
2601
2602static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002603compiler_ifexp(struct compiler *c, expr_ty e)
2604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 basicblock *end, *next;
2606
2607 assert(e->kind == IfExp_kind);
2608 end = compiler_new_block(c);
2609 if (end == NULL)
2610 return 0;
2611 next = compiler_new_block(c);
2612 if (next == NULL)
2613 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002614 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2615 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002617 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 compiler_use_next_block(c, next);
2619 VISIT(c, expr, e->v.IfExp.orelse);
2620 compiler_use_next_block(c, end);
2621 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002622}
2623
2624static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625compiler_lambda(struct compiler *c, expr_ty e)
2626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002628 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002630 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 arguments_ty args = e->v.Lambda.args;
2632 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002634 if (!compiler_check_debug_args(c, args))
2635 return 0;
2636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (!name) {
2638 name = PyUnicode_InternFromString("<lambda>");
2639 if (!name)
2640 return 0;
2641 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002643 funcflags = compiler_default_arguments(c, args);
2644 if (funcflags == -1) {
2645 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002647
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002648 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002649 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* Make None the first constant, so the lambda can't have a
2653 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002654 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002658 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2660 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2661 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002662 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 }
2664 else {
2665 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002666 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002668 qualname = c->u->u_qualname;
2669 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002671 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002674 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002675 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 Py_DECREF(co);
2677
2678 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679}
2680
2681static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682compiler_if(struct compiler *c, stmt_ty s)
2683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 basicblock *end, *next;
2685 int constant;
2686 assert(s->kind == If_kind);
2687 end = compiler_new_block(c);
2688 if (end == NULL)
2689 return 0;
2690
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002691 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002692 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 * constant = 1: "if 1", "if 2", ...
2694 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002695 if (constant == 0) {
2696 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002698 END_DO_NOT_EMIT_BYTECODE
2699 if (s->v.If.orelse) {
2700 VISIT_SEQ(c, stmt, s->v.If.orelse);
2701 }
2702 } else if (constant == 1) {
2703 VISIT_SEQ(c, stmt, s->v.If.body);
2704 if (s->v.If.orelse) {
2705 BEGIN_DO_NOT_EMIT_BYTECODE
2706 VISIT_SEQ(c, stmt, s->v.If.orelse);
2707 END_DO_NOT_EMIT_BYTECODE
2708 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002710 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 next = compiler_new_block(c);
2712 if (next == NULL)
2713 return 0;
2714 }
Mark Shannonfee55262019-11-21 09:11:43 +00002715 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002717 }
2718 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002719 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002720 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002722 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002723 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 compiler_use_next_block(c, next);
2725 VISIT_SEQ(c, stmt, s->v.If.orelse);
2726 }
2727 }
2728 compiler_use_next_block(c, end);
2729 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002730}
2731
2732static int
2733compiler_for(struct compiler *c, stmt_ty s)
2734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 start = compiler_new_block(c);
2738 cleanup = compiler_new_block(c);
2739 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002740 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002742 }
2743 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002745 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 VISIT(c, expr, s->v.For.iter);
2747 ADDOP(c, GET_ITER);
2748 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002749 ADDOP_JUMP(c, FOR_ITER, cleanup);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 VISIT(c, expr, s->v.For.target);
2751 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002752 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002754
2755 compiler_pop_fblock(c, FOR_LOOP, start);
2756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 VISIT_SEQ(c, stmt, s->v.For.orelse);
2758 compiler_use_next_block(c, end);
2759 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002760}
2761
Yury Selivanov75445082015-05-11 22:57:16 -04002762
2763static int
2764compiler_async_for(struct compiler *c, stmt_ty s)
2765{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002766 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002767 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002768 c->u->u_ste->ste_coroutine = 1;
2769 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002770 return compiler_error(c, "'async for' outside async function");
2771 }
2772
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002773 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002774 except = compiler_new_block(c);
2775 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002776
Mark Shannonfee55262019-11-21 09:11:43 +00002777 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002778 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002779 }
Yury Selivanov75445082015-05-11 22:57:16 -04002780 VISIT(c, expr, s->v.AsyncFor.iter);
2781 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002782
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002783 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002784 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002785 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002786 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002787 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002788 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002789 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002790 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002791 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002792 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002793
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002794 /* Success block for __anext__ */
2795 VISIT(c, expr, s->v.AsyncFor.target);
2796 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002797 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002798
2799 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002800
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002802 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002803
2804 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002805 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002806
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002807 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002808 VISIT_SEQ(c, stmt, s->v.For.orelse);
2809
2810 compiler_use_next_block(c, end);
2811
2812 return 1;
2813}
2814
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002815static int
2816compiler_while(struct compiler *c, stmt_ty s)
2817{
Mark Shannon266b4622020-11-17 19:30:14 +00002818 basicblock *loop, *body, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002819 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002822 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002823 // Push a dummy block so the VISIT_SEQ knows that we are
2824 // inside a while loop so it can correctly evaluate syntax
2825 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002826 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002827 return 0;
2828 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002829 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002830 // Remove the dummy block now that is not needed.
2831 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002832 END_DO_NOT_EMIT_BYTECODE
2833 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002835 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return 1;
2837 }
2838 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002839 body = compiler_new_block(c);
2840 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002842 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002846 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 }
Mark Shannon266b4622020-11-17 19:30:14 +00002849 if (constant == -1) {
2850 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2851 return 0;
2852 }
2853 }
2854
2855 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002857 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002859 compiler_pop_fblock(c, WHILE_LOOP, loop);
2860
Mark Shannon266b4622020-11-17 19:30:14 +00002861 compiler_use_next_block(c, anchor);
2862 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868}
2869
2870static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002871compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002872{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002873 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002874 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002875 if (c->u->u_ste->ste_type != FunctionBlock)
2876 return compiler_error(c, "'return' outside function");
2877 if (s->v.Return.value != NULL &&
2878 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2879 {
2880 return compiler_error(
2881 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 if (preserve_tos) {
2884 VISIT(c, expr, s->v.Return.value);
2885 }
Mark Shannonfee55262019-11-21 09:11:43 +00002886 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2887 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002888 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002889 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002890 }
2891 else if (!preserve_tos) {
2892 VISIT(c, expr, s->v.Return.value);
2893 }
2894 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002895 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002898}
2899
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002900static int
2901compiler_break(struct compiler *c)
2902{
Mark Shannonfee55262019-11-21 09:11:43 +00002903 struct fblockinfo *loop = NULL;
2904 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2905 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002906 }
Mark Shannonfee55262019-11-21 09:11:43 +00002907 if (loop == NULL) {
2908 return compiler_error(c, "'break' outside loop");
2909 }
2910 if (!compiler_unwind_fblock(c, loop, 0)) {
2911 return 0;
2912 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002913 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002914 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002915 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002916}
2917
2918static int
2919compiler_continue(struct compiler *c)
2920{
Mark Shannonfee55262019-11-21 09:11:43 +00002921 struct fblockinfo *loop = NULL;
2922 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2923 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002924 }
Mark Shannonfee55262019-11-21 09:11:43 +00002925 if (loop == NULL) {
2926 return compiler_error(c, "'continue' not properly in loop");
2927 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002928 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002929 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002930 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002931}
2932
2933
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002934/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002935
2936 SETUP_FINALLY L
2937 <code for body>
2938 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002939 <code for finalbody>
2940 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002941 L:
2942 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002943 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945 The special instructions use the block stack. Each block
2946 stack entry contains the instruction that created it (here
2947 SETUP_FINALLY), the level of the value stack at the time the
2948 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 Pushes the current value stack level and the label
2952 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002953 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002954 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002956 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002957 when a SETUP_FINALLY entry is found, the raised and the caught
2958 exceptions are pushed onto the value stack (and the exception
2959 condition is cleared), and the interpreter jumps to the label
2960 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961*/
2962
2963static int
2964compiler_try_finally(struct compiler *c, stmt_ty s)
2965{
Mark Shannonfee55262019-11-21 09:11:43 +00002966 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 body = compiler_new_block(c);
2969 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002970 exit = compiler_new_block(c);
2971 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002974 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002975 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002977 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002979 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2980 if (!compiler_try_except(c, s))
2981 return 0;
2982 }
2983 else {
2984 VISIT_SEQ(c, stmt, s->v.Try.body);
2985 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002987 compiler_pop_fblock(c, FINALLY_TRY, body);
2988 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon582aaf12020-08-04 17:30:11 +01002989 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00002990 /* `finally` block */
2991 compiler_use_next_block(c, end);
2992 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2993 return 0;
2994 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2995 compiler_pop_fblock(c, FINALLY_END, end);
2996 ADDOP(c, RERAISE);
2997 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002999}
3000
3001/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003002 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003 (The contents of the value stack is shown in [], with the top
3004 at the right; 'tb' is trace-back info, 'val' the exception's
3005 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003006
3007 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003008 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003009 [] <code for S>
3010 [] POP_BLOCK
3011 [] JUMP_FORWARD L0
3012
3013 [tb, val, exc] L1: DUP )
3014 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003015 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003016 [tb, val, exc] POP
3017 [tb, val] <assign to V1> (or POP if no V1)
3018 [tb] POP
3019 [] <code for S1>
3020 JUMP_FORWARD L0
3021
3022 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023 .............................etc.......................
3024
Mark Shannonfee55262019-11-21 09:11:43 +00003025 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026
3027 [] L0: <next statement>
3028
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003029 Of course, parts are not generated if Vi or Ei is not present.
3030*/
3031static int
3032compiler_try_except(struct compiler *c, stmt_ty s)
3033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003034 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003035 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 body = compiler_new_block(c);
3038 except = compiler_new_block(c);
3039 orelse = compiler_new_block(c);
3040 end = compiler_new_block(c);
3041 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3042 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003043 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003045 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003046 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003047 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 ADDOP(c, POP_BLOCK);
Mark Shannon02d126a2020-09-25 14:04:19 +01003049 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon582aaf12020-08-04 17:30:11 +01003050 ADDOP_JUMP(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003051 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003052 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003053 /* Runtime will push a block here, so we need to account for that */
3054 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3055 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003056 for (i = 0; i < n; i++) {
3057 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003058 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003059 if (!handler->v.ExceptHandler.type && i < n-1)
3060 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003061 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 except = compiler_new_block(c);
3063 if (except == NULL)
3064 return 0;
3065 if (handler->v.ExceptHandler.type) {
3066 ADDOP(c, DUP_TOP);
3067 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003068 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003069 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 }
3071 ADDOP(c, POP_TOP);
3072 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003073 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003074
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003075 cleanup_end = compiler_new_block(c);
3076 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003077 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003078 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003079 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003080
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003081 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3082 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003084 /*
3085 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003086 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003088 try:
3089 # body
3090 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003091 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003092 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003093 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003095 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003096 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003097 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003098 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003099 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 /* second # body */
3102 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003103 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003104 ADDOP(c, POP_BLOCK);
3105 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003106 /* name = None; del name; # Mark as artificial */
3107 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003108 ADDOP_LOAD_CONST(c, Py_None);
3109 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3110 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003111 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112
Mark Shannonfee55262019-11-21 09:11:43 +00003113 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003114 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115
Mark Shannon877df852020-11-12 09:43:29 +00003116 /* name = None; del name; # Mark as artificial */
3117 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003118 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003120 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121
Mark Shannonfee55262019-11-21 09:11:43 +00003122 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 }
3124 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003125 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003127 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003128 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003129 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130
Guido van Rossumb940e112007-01-10 16:19:56 +00003131 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003132 ADDOP(c, POP_TOP);
3133 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003134 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003135 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003137 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003138 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003139 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 compiler_use_next_block(c, except);
3142 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003143 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonfee55262019-11-21 09:11:43 +00003144 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003146 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 compiler_use_next_block(c, end);
3148 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003149}
3150
3151static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003152compiler_try(struct compiler *c, stmt_ty s) {
3153 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3154 return compiler_try_finally(c, s);
3155 else
3156 return compiler_try_except(c, s);
3157}
3158
3159
3160static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003161compiler_import_as(struct compiler *c, identifier name, identifier asname)
3162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 /* The IMPORT_NAME opcode was already generated. This function
3164 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003166 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003167 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003169 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3170 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003171 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003172 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003173 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003175 while (1) {
3176 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003177 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003178 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003179 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003180 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003181 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003183 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003184 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003185 if (dot == -1) {
3186 break;
3187 }
3188 ADDOP(c, ROT_TWO);
3189 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003191 if (!compiler_nameop(c, asname, Store)) {
3192 return 0;
3193 }
3194 ADDOP(c, POP_TOP);
3195 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 }
3197 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198}
3199
3200static int
3201compiler_import(struct compiler *c, stmt_ty s)
3202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 /* The Import node stores a module name like a.b.c as a single
3204 string. This is convenient for all cases except
3205 import a.b.c as d
3206 where we need to parse that string to extract the individual
3207 module names.
3208 XXX Perhaps change the representation to make this case simpler?
3209 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003210 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003211
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003212 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 for (i = 0; i < n; i++) {
3214 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3215 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003216
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003217 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003218 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003221 if (alias->asname) {
3222 r = compiler_import_as(c, alias->name, alias->asname);
3223 if (!r)
3224 return r;
3225 }
3226 else {
3227 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003228 Py_ssize_t dot = PyUnicode_FindChar(
3229 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003230 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003231 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003232 if (tmp == NULL)
3233 return 0;
3234 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003236 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 Py_DECREF(tmp);
3238 }
3239 if (!r)
3240 return r;
3241 }
3242 }
3243 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244}
3245
3246static int
3247compiler_from_import(struct compiler *c, stmt_ty s)
3248{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003249 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003250 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 if (!empty_string) {
3254 empty_string = PyUnicode_FromString("");
3255 if (!empty_string)
3256 return 0;
3257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003259 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003260
3261 names = PyTuple_New(n);
3262 if (!names)
3263 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 /* build up the names */
3266 for (i = 0; i < n; i++) {
3267 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3268 Py_INCREF(alias->name);
3269 PyTuple_SET_ITEM(names, i, alias->name);
3270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003273 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 Py_DECREF(names);
3275 return compiler_error(c, "from __future__ imports must occur "
3276 "at the beginning of the file");
3277 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003278 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 if (s->v.ImportFrom.module) {
3281 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3282 }
3283 else {
3284 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3285 }
3286 for (i = 0; i < n; i++) {
3287 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3288 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003289
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003290 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 assert(n == 1);
3292 ADDOP(c, IMPORT_STAR);
3293 return 1;
3294 }
3295
3296 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3297 store_name = alias->name;
3298 if (alias->asname)
3299 store_name = alias->asname;
3300
3301 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 return 0;
3303 }
3304 }
3305 /* remove imported module */
3306 ADDOP(c, POP_TOP);
3307 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308}
3309
3310static int
3311compiler_assert(struct compiler *c, stmt_ty s)
3312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003313 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003314
Georg Brandl8334fd92010-12-04 10:26:46 +00003315 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003317 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003318 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3319 {
3320 if (!compiler_warn(c, "assertion is always true, "
3321 "perhaps remove parentheses?"))
3322 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003323 return 0;
3324 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003325 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 end = compiler_new_block(c);
3327 if (end == NULL)
3328 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003329 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3330 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003331 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 if (s->v.Assert.msg) {
3333 VISIT(c, expr, s->v.Assert.msg);
3334 ADDOP_I(c, CALL_FUNCTION, 1);
3335 }
3336 ADDOP_I(c, RAISE_VARARGS, 1);
3337 compiler_use_next_block(c, end);
3338 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003339}
3340
3341static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003342compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3343{
3344 if (c->c_interactive && c->c_nestlevel <= 1) {
3345 VISIT(c, expr, value);
3346 ADDOP(c, PRINT_EXPR);
3347 return 1;
3348 }
3349
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003350 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003351 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003352 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003353 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003354 }
3355
3356 VISIT(c, expr, value);
3357 ADDOP(c, POP_TOP);
3358 return 1;
3359}
3360
3361static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003362compiler_visit_stmt(struct compiler *c, stmt_ty s)
3363{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003364 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003367 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003369 switch (s->kind) {
3370 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003371 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003372 case ClassDef_kind:
3373 return compiler_class(c, s);
3374 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003375 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003376 case Delete_kind:
3377 VISIT_SEQ(c, expr, s->v.Delete.targets)
3378 break;
3379 case Assign_kind:
3380 n = asdl_seq_LEN(s->v.Assign.targets);
3381 VISIT(c, expr, s->v.Assign.value);
3382 for (i = 0; i < n; i++) {
3383 if (i < n - 1)
3384 ADDOP(c, DUP_TOP);
3385 VISIT(c, expr,
3386 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3387 }
3388 break;
3389 case AugAssign_kind:
3390 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003391 case AnnAssign_kind:
3392 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 case For_kind:
3394 return compiler_for(c, s);
3395 case While_kind:
3396 return compiler_while(c, s);
3397 case If_kind:
3398 return compiler_if(c, s);
3399 case Raise_kind:
3400 n = 0;
3401 if (s->v.Raise.exc) {
3402 VISIT(c, expr, s->v.Raise.exc);
3403 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003404 if (s->v.Raise.cause) {
3405 VISIT(c, expr, s->v.Raise.cause);
3406 n++;
3407 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003409 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003410 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003411 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003412 case Try_kind:
3413 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003414 case Assert_kind:
3415 return compiler_assert(c, s);
3416 case Import_kind:
3417 return compiler_import(c, s);
3418 case ImportFrom_kind:
3419 return compiler_from_import(c, s);
3420 case Global_kind:
3421 case Nonlocal_kind:
3422 break;
3423 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003424 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003425 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003426 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 break;
3428 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003429 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 case Continue_kind:
3431 return compiler_continue(c);
3432 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003433 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003434 case AsyncFunctionDef_kind:
3435 return compiler_function(c, s, 1);
3436 case AsyncWith_kind:
3437 return compiler_async_with(c, s, 0);
3438 case AsyncFor_kind:
3439 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003440 }
Yury Selivanov75445082015-05-11 22:57:16 -04003441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003443}
3444
3445static int
3446unaryop(unaryop_ty op)
3447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003448 switch (op) {
3449 case Invert:
3450 return UNARY_INVERT;
3451 case Not:
3452 return UNARY_NOT;
3453 case UAdd:
3454 return UNARY_POSITIVE;
3455 case USub:
3456 return UNARY_NEGATIVE;
3457 default:
3458 PyErr_Format(PyExc_SystemError,
3459 "unary op %d should not be possible", op);
3460 return 0;
3461 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462}
3463
3464static int
Andy Lester76d58772020-03-10 21:18:12 -05003465binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 switch (op) {
3468 case Add:
3469 return BINARY_ADD;
3470 case Sub:
3471 return BINARY_SUBTRACT;
3472 case Mult:
3473 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003474 case MatMult:
3475 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003476 case Div:
3477 return BINARY_TRUE_DIVIDE;
3478 case Mod:
3479 return BINARY_MODULO;
3480 case Pow:
3481 return BINARY_POWER;
3482 case LShift:
3483 return BINARY_LSHIFT;
3484 case RShift:
3485 return BINARY_RSHIFT;
3486 case BitOr:
3487 return BINARY_OR;
3488 case BitXor:
3489 return BINARY_XOR;
3490 case BitAnd:
3491 return BINARY_AND;
3492 case FloorDiv:
3493 return BINARY_FLOOR_DIVIDE;
3494 default:
3495 PyErr_Format(PyExc_SystemError,
3496 "binary op %d should not be possible", op);
3497 return 0;
3498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003499}
3500
3501static int
Andy Lester76d58772020-03-10 21:18:12 -05003502inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003504 switch (op) {
3505 case Add:
3506 return INPLACE_ADD;
3507 case Sub:
3508 return INPLACE_SUBTRACT;
3509 case Mult:
3510 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003511 case MatMult:
3512 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003513 case Div:
3514 return INPLACE_TRUE_DIVIDE;
3515 case Mod:
3516 return INPLACE_MODULO;
3517 case Pow:
3518 return INPLACE_POWER;
3519 case LShift:
3520 return INPLACE_LSHIFT;
3521 case RShift:
3522 return INPLACE_RSHIFT;
3523 case BitOr:
3524 return INPLACE_OR;
3525 case BitXor:
3526 return INPLACE_XOR;
3527 case BitAnd:
3528 return INPLACE_AND;
3529 case FloorDiv:
3530 return INPLACE_FLOOR_DIVIDE;
3531 default:
3532 PyErr_Format(PyExc_SystemError,
3533 "inplace binary op %d should not be possible", op);
3534 return 0;
3535 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003536}
3537
3538static int
3539compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3540{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003541 int op, scope;
3542 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003543 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003545 PyObject *dict = c->u->u_names;
3546 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003547
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003548 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3549 !_PyUnicode_EqualToASCIIString(name, "True") &&
3550 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003551
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003552 if (forbidden_name(c, name, ctx))
3553 return 0;
3554
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003555 mangled = _Py_Mangle(c->u->u_private, name);
3556 if (!mangled)
3557 return 0;
3558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 op = 0;
3560 optype = OP_NAME;
3561 scope = PyST_GetScope(c->u->u_ste, mangled);
3562 switch (scope) {
3563 case FREE:
3564 dict = c->u->u_freevars;
3565 optype = OP_DEREF;
3566 break;
3567 case CELL:
3568 dict = c->u->u_cellvars;
3569 optype = OP_DEREF;
3570 break;
3571 case LOCAL:
3572 if (c->u->u_ste->ste_type == FunctionBlock)
3573 optype = OP_FAST;
3574 break;
3575 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003576 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003577 optype = OP_GLOBAL;
3578 break;
3579 case GLOBAL_EXPLICIT:
3580 optype = OP_GLOBAL;
3581 break;
3582 default:
3583 /* scope can be 0 */
3584 break;
3585 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003587 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003588 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 switch (optype) {
3591 case OP_DEREF:
3592 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003593 case Load:
3594 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3595 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003596 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003597 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 }
3599 break;
3600 case OP_FAST:
3601 switch (ctx) {
3602 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003603 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003605 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003606 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 return 1;
3608 case OP_GLOBAL:
3609 switch (ctx) {
3610 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003611 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003612 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 }
3614 break;
3615 case OP_NAME:
3616 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003617 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003618 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003619 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 }
3621 break;
3622 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003625 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 Py_DECREF(mangled);
3627 if (arg < 0)
3628 return 0;
3629 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003630}
3631
3632static int
3633compiler_boolop(struct compiler *c, expr_ty e)
3634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003636 int jumpi;
3637 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003638 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 assert(e->kind == BoolOp_kind);
3641 if (e->v.BoolOp.op == And)
3642 jumpi = JUMP_IF_FALSE_OR_POP;
3643 else
3644 jumpi = JUMP_IF_TRUE_OR_POP;
3645 end = compiler_new_block(c);
3646 if (end == NULL)
3647 return 0;
3648 s = e->v.BoolOp.values;
3649 n = asdl_seq_LEN(s) - 1;
3650 assert(n >= 0);
3651 for (i = 0; i < n; ++i) {
3652 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003653 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003654 basicblock *next = compiler_new_block(c);
3655 if (next == NULL) {
3656 return 0;
3657 }
3658 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 }
3660 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3661 compiler_use_next_block(c, end);
3662 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663}
3664
3665static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003666starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003667 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003668{
3669 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003670 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003671 if (n > 2 && are_all_items_const(elts, 0, n)) {
3672 PyObject *folded = PyTuple_New(n);
3673 if (folded == NULL) {
3674 return 0;
3675 }
3676 PyObject *val;
3677 for (i = 0; i < n; i++) {
3678 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3679 Py_INCREF(val);
3680 PyTuple_SET_ITEM(folded, i, val);
3681 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003682 if (tuple) {
3683 ADDOP_LOAD_CONST_NEW(c, folded);
3684 } else {
3685 if (add == SET_ADD) {
3686 Py_SETREF(folded, PyFrozenSet_New(folded));
3687 if (folded == NULL) {
3688 return 0;
3689 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003690 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003691 ADDOP_I(c, build, pushed);
3692 ADDOP_LOAD_CONST_NEW(c, folded);
3693 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003694 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003695 return 1;
3696 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003697
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003698 for (i = 0; i < n; i++) {
3699 expr_ty elt = asdl_seq_GET(elts, i);
3700 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003701 seen_star = 1;
3702 }
3703 }
3704 if (seen_star) {
3705 seen_star = 0;
3706 for (i = 0; i < n; i++) {
3707 expr_ty elt = asdl_seq_GET(elts, i);
3708 if (elt->kind == Starred_kind) {
3709 if (seen_star == 0) {
3710 ADDOP_I(c, build, i+pushed);
3711 seen_star = 1;
3712 }
3713 VISIT(c, expr, elt->v.Starred.value);
3714 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003715 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003716 else {
3717 VISIT(c, expr, elt);
3718 if (seen_star) {
3719 ADDOP_I(c, add, 1);
3720 }
3721 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003722 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003723 assert(seen_star);
3724 if (tuple) {
3725 ADDOP(c, LIST_TO_TUPLE);
3726 }
3727 }
3728 else {
3729 for (i = 0; i < n; i++) {
3730 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003731 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003732 }
3733 if (tuple) {
3734 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3735 } else {
3736 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003737 }
3738 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003739 return 1;
3740}
3741
3742static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003743assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003744{
3745 Py_ssize_t n = asdl_seq_LEN(elts);
3746 Py_ssize_t i;
3747 int seen_star = 0;
3748 for (i = 0; i < n; i++) {
3749 expr_ty elt = asdl_seq_GET(elts, i);
3750 if (elt->kind == Starred_kind && !seen_star) {
3751 if ((i >= (1 << 8)) ||
3752 (n-i-1 >= (INT_MAX >> 8)))
3753 return compiler_error(c,
3754 "too many expressions in "
3755 "star-unpacking assignment");
3756 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3757 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003758 }
3759 else if (elt->kind == Starred_kind) {
3760 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003761 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003762 }
3763 }
3764 if (!seen_star) {
3765 ADDOP_I(c, UNPACK_SEQUENCE, n);
3766 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003767 for (i = 0; i < n; i++) {
3768 expr_ty elt = asdl_seq_GET(elts, i);
3769 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3770 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003771 return 1;
3772}
3773
3774static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003775compiler_list(struct compiler *c, expr_ty e)
3776{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003777 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003778 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003779 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003780 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003781 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003782 return starunpack_helper(c, elts, 0, BUILD_LIST,
3783 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003784 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003785 else
3786 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003787 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003788}
3789
3790static int
3791compiler_tuple(struct compiler *c, expr_ty e)
3792{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003793 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003794 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 return assignment_helper(c, elts);
3796 }
3797 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003798 return starunpack_helper(c, elts, 0, BUILD_LIST,
3799 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003800 }
3801 else
3802 VISIT_SEQ(c, expr, elts);
3803 return 1;
3804}
3805
3806static int
3807compiler_set(struct compiler *c, expr_ty e)
3808{
Mark Shannon13bc1392020-01-23 09:25:17 +00003809 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3810 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003811}
3812
3813static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003814are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003815{
3816 Py_ssize_t i;
3817 for (i = begin; i < end; i++) {
3818 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003819 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003820 return 0;
3821 }
3822 return 1;
3823}
3824
3825static int
3826compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3827{
3828 Py_ssize_t i, n = end - begin;
3829 PyObject *keys, *key;
3830 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3831 for (i = begin; i < end; i++) {
3832 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3833 }
3834 keys = PyTuple_New(n);
3835 if (keys == NULL) {
3836 return 0;
3837 }
3838 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003839 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003840 Py_INCREF(key);
3841 PyTuple_SET_ITEM(keys, i - begin, key);
3842 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003843 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003844 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3845 }
3846 else {
3847 for (i = begin; i < end; i++) {
3848 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3849 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3850 }
3851 ADDOP_I(c, BUILD_MAP, n);
3852 }
3853 return 1;
3854}
3855
3856static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003857compiler_dict(struct compiler *c, expr_ty e)
3858{
Victor Stinner976bb402016-03-23 11:36:19 +01003859 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003860 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003861 int is_unpacking = 0;
3862 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003863 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003864 elements = 0;
3865 for (i = 0; i < n; i++) {
3866 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003867 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003868 if (elements) {
3869 if (!compiler_subdict(c, e, i - elements, i)) {
3870 return 0;
3871 }
3872 if (have_dict) {
3873 ADDOP_I(c, DICT_UPDATE, 1);
3874 }
3875 have_dict = 1;
3876 elements = 0;
3877 }
3878 if (have_dict == 0) {
3879 ADDOP_I(c, BUILD_MAP, 0);
3880 have_dict = 1;
3881 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003882 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003883 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003884 }
3885 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003886 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003887 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003888 return 0;
3889 }
3890 if (have_dict) {
3891 ADDOP_I(c, DICT_UPDATE, 1);
3892 }
3893 have_dict = 1;
3894 elements = 0;
3895 }
3896 else {
3897 elements++;
3898 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003899 }
3900 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003901 if (elements) {
3902 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003903 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003904 }
3905 if (have_dict) {
3906 ADDOP_I(c, DICT_UPDATE, 1);
3907 }
3908 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003909 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003910 if (!have_dict) {
3911 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003912 }
3913 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914}
3915
3916static int
3917compiler_compare(struct compiler *c, expr_ty e)
3918{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003919 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003920
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003921 if (!check_compare(c, e)) {
3922 return 0;
3923 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003925 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3926 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3927 if (n == 0) {
3928 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003929 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003930 }
3931 else {
3932 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003933 if (cleanup == NULL)
3934 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003935 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 VISIT(c, expr,
3937 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003938 ADDOP(c, DUP_TOP);
3939 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003940 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003941 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003942 NEXT_BLOCK(c);
3943 }
3944 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003945 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003946 basicblock *end = compiler_new_block(c);
3947 if (end == NULL)
3948 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003949 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003950 compiler_use_next_block(c, cleanup);
3951 ADDOP(c, ROT_TWO);
3952 ADDOP(c, POP_TOP);
3953 compiler_use_next_block(c, end);
3954 }
3955 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003956}
3957
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003958static PyTypeObject *
3959infer_type(expr_ty e)
3960{
3961 switch (e->kind) {
3962 case Tuple_kind:
3963 return &PyTuple_Type;
3964 case List_kind:
3965 case ListComp_kind:
3966 return &PyList_Type;
3967 case Dict_kind:
3968 case DictComp_kind:
3969 return &PyDict_Type;
3970 case Set_kind:
3971 case SetComp_kind:
3972 return &PySet_Type;
3973 case GeneratorExp_kind:
3974 return &PyGen_Type;
3975 case Lambda_kind:
3976 return &PyFunction_Type;
3977 case JoinedStr_kind:
3978 case FormattedValue_kind:
3979 return &PyUnicode_Type;
3980 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003981 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003982 default:
3983 return NULL;
3984 }
3985}
3986
3987static int
3988check_caller(struct compiler *c, expr_ty e)
3989{
3990 switch (e->kind) {
3991 case Constant_kind:
3992 case Tuple_kind:
3993 case List_kind:
3994 case ListComp_kind:
3995 case Dict_kind:
3996 case DictComp_kind:
3997 case Set_kind:
3998 case SetComp_kind:
3999 case GeneratorExp_kind:
4000 case JoinedStr_kind:
4001 case FormattedValue_kind:
4002 return compiler_warn(c, "'%.200s' object is not callable; "
4003 "perhaps you missed a comma?",
4004 infer_type(e)->tp_name);
4005 default:
4006 return 1;
4007 }
4008}
4009
4010static int
4011check_subscripter(struct compiler *c, expr_ty e)
4012{
4013 PyObject *v;
4014
4015 switch (e->kind) {
4016 case Constant_kind:
4017 v = e->v.Constant.value;
4018 if (!(v == Py_None || v == Py_Ellipsis ||
4019 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4020 PyAnySet_Check(v)))
4021 {
4022 return 1;
4023 }
4024 /* fall through */
4025 case Set_kind:
4026 case SetComp_kind:
4027 case GeneratorExp_kind:
4028 case Lambda_kind:
4029 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4030 "perhaps you missed a comma?",
4031 infer_type(e)->tp_name);
4032 default:
4033 return 1;
4034 }
4035}
4036
4037static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004038check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004039{
4040 PyObject *v;
4041
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004042 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004043 if (index_type == NULL
4044 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4045 || index_type == &PySlice_Type) {
4046 return 1;
4047 }
4048
4049 switch (e->kind) {
4050 case Constant_kind:
4051 v = e->v.Constant.value;
4052 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4053 return 1;
4054 }
4055 /* fall through */
4056 case Tuple_kind:
4057 case List_kind:
4058 case ListComp_kind:
4059 case JoinedStr_kind:
4060 case FormattedValue_kind:
4061 return compiler_warn(c, "%.200s indices must be integers or slices, "
4062 "not %.200s; "
4063 "perhaps you missed a comma?",
4064 infer_type(e)->tp_name,
4065 index_type->tp_name);
4066 default:
4067 return 1;
4068 }
4069}
4070
Zackery Spytz97f5de02019-03-22 01:30:32 -06004071// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004072static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004073maybe_optimize_method_call(struct compiler *c, expr_ty e)
4074{
4075 Py_ssize_t argsl, i;
4076 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004077 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004078
4079 /* Check that the call node is an attribute access, and that
4080 the call doesn't have keyword parameters. */
4081 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4082 asdl_seq_LEN(e->v.Call.keywords))
4083 return -1;
4084
4085 /* Check that there are no *varargs types of arguments. */
4086 argsl = asdl_seq_LEN(args);
4087 for (i = 0; i < argsl; i++) {
4088 expr_ty elt = asdl_seq_GET(args, i);
4089 if (elt->kind == Starred_kind) {
4090 return -1;
4091 }
4092 }
4093
4094 /* Alright, we can optimize the code. */
4095 VISIT(c, expr, meth->v.Attribute.value);
4096 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4097 VISIT_SEQ(c, expr, e->v.Call.args);
4098 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4099 return 1;
4100}
4101
4102static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004103validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004104{
4105 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4106 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004107 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4108 if (key->arg == NULL) {
4109 continue;
4110 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004111 if (forbidden_name(c, key->arg, Store)) {
4112 return -1;
4113 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004114 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004115 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4116 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4117 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4118 if (msg == NULL) {
4119 return -1;
4120 }
4121 c->u->u_col_offset = other->col_offset;
4122 compiler_error(c, PyUnicode_AsUTF8(msg));
4123 Py_DECREF(msg);
4124 return -1;
4125 }
4126 }
4127 }
4128 return 0;
4129}
4130
4131static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004132compiler_call(struct compiler *c, expr_ty e)
4133{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004134 int ret = maybe_optimize_method_call(c, e);
4135 if (ret >= 0) {
4136 return ret;
4137 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004138 if (!check_caller(c, e->v.Call.func)) {
4139 return 0;
4140 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004141 VISIT(c, expr, e->v.Call.func);
4142 return compiler_call_helper(c, 0,
4143 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004144 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004145}
4146
Eric V. Smith235a6f02015-09-19 14:51:32 -04004147static int
4148compiler_joined_str(struct compiler *c, expr_ty e)
4149{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004150 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004151 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4152 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004153 return 1;
4154}
4155
Eric V. Smitha78c7952015-11-03 12:45:05 -05004156/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004157static int
4158compiler_formatted_value(struct compiler *c, expr_ty e)
4159{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004160 /* Our oparg encodes 2 pieces of information: the conversion
4161 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004162
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004163 Convert the conversion char to 3 bits:
4164 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004165 !s : 001 0x1 FVC_STR
4166 !r : 010 0x2 FVC_REPR
4167 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004168
Eric V. Smitha78c7952015-11-03 12:45:05 -05004169 next bit is whether or not we have a format spec:
4170 yes : 100 0x4
4171 no : 000 0x0
4172 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004173
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004174 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004175 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004176
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004177 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004178 VISIT(c, expr, e->v.FormattedValue.value);
4179
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004180 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004181 case 's': oparg = FVC_STR; break;
4182 case 'r': oparg = FVC_REPR; break;
4183 case 'a': oparg = FVC_ASCII; break;
4184 case -1: oparg = FVC_NONE; break;
4185 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004186 PyErr_Format(PyExc_SystemError,
4187 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004188 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004189 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004190 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004191 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004192 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004193 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004194 }
4195
Eric V. Smitha78c7952015-11-03 12:45:05 -05004196 /* And push our opcode and oparg */
4197 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004198
Eric V. Smith235a6f02015-09-19 14:51:32 -04004199 return 1;
4200}
4201
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004202static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004203compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004204{
4205 Py_ssize_t i, n = end - begin;
4206 keyword_ty kw;
4207 PyObject *keys, *key;
4208 assert(n > 0);
4209 if (n > 1) {
4210 for (i = begin; i < end; i++) {
4211 kw = asdl_seq_GET(keywords, i);
4212 VISIT(c, expr, kw->value);
4213 }
4214 keys = PyTuple_New(n);
4215 if (keys == NULL) {
4216 return 0;
4217 }
4218 for (i = begin; i < end; i++) {
4219 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4220 Py_INCREF(key);
4221 PyTuple_SET_ITEM(keys, i - begin, key);
4222 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004223 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004224 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4225 }
4226 else {
4227 /* a for loop only executes once */
4228 for (i = begin; i < end; i++) {
4229 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004230 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004231 VISIT(c, expr, kw->value);
4232 }
4233 ADDOP_I(c, BUILD_MAP, n);
4234 }
4235 return 1;
4236}
4237
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004238/* shared code between compiler_call and compiler_class */
4239static int
4240compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004241 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004242 asdl_expr_seq *args,
4243 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004244{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004245 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004246
Pablo Galindo254ec782020-04-03 20:37:13 +01004247 if (validate_keywords(c, keywords) == -1) {
4248 return 0;
4249 }
4250
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004251 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004252 nkwelts = asdl_seq_LEN(keywords);
4253
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004254 for (i = 0; i < nelts; i++) {
4255 expr_ty elt = asdl_seq_GET(args, i);
4256 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004257 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004258 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004259 }
4260 for (i = 0; i < nkwelts; i++) {
4261 keyword_ty kw = asdl_seq_GET(keywords, i);
4262 if (kw->arg == NULL) {
4263 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004265 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004266
Mark Shannon13bc1392020-01-23 09:25:17 +00004267 /* No * or ** args, so can use faster calling sequence */
4268 for (i = 0; i < nelts; i++) {
4269 expr_ty elt = asdl_seq_GET(args, i);
4270 assert(elt->kind != Starred_kind);
4271 VISIT(c, expr, elt);
4272 }
4273 if (nkwelts) {
4274 PyObject *names;
4275 VISIT_SEQ(c, keyword, keywords);
4276 names = PyTuple_New(nkwelts);
4277 if (names == NULL) {
4278 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004279 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004280 for (i = 0; i < nkwelts; i++) {
4281 keyword_ty kw = asdl_seq_GET(keywords, i);
4282 Py_INCREF(kw->arg);
4283 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004284 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004285 ADDOP_LOAD_CONST_NEW(c, names);
4286 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4287 return 1;
4288 }
4289 else {
4290 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4291 return 1;
4292 }
4293
4294ex_call:
4295
4296 /* Do positional arguments. */
4297 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4298 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4299 }
4300 else if (starunpack_helper(c, args, n, BUILD_LIST,
4301 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4302 return 0;
4303 }
4304 /* Then keyword arguments */
4305 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004306 /* Has a new dict been pushed */
4307 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004308
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004309 nseen = 0; /* the number of keyword arguments on the stack following */
4310 for (i = 0; i < nkwelts; i++) {
4311 keyword_ty kw = asdl_seq_GET(keywords, i);
4312 if (kw->arg == NULL) {
4313 /* A keyword argument unpacking. */
4314 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004315 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004316 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004317 }
Mark Shannondb64f122020-06-01 10:42:42 +01004318 if (have_dict) {
4319 ADDOP_I(c, DICT_MERGE, 1);
4320 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004321 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004322 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004323 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004324 if (!have_dict) {
4325 ADDOP_I(c, BUILD_MAP, 0);
4326 have_dict = 1;
4327 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004328 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004329 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004330 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004331 else {
4332 nseen++;
4333 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004334 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004335 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004336 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004337 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004338 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004339 }
4340 if (have_dict) {
4341 ADDOP_I(c, DICT_MERGE, 1);
4342 }
4343 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004344 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004345 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004346 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004347 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4348 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349}
4350
Nick Coghlan650f0d02007-04-15 12:05:43 +00004351
4352/* List and set comprehensions and generator expressions work by creating a
4353 nested function to perform the actual iteration. This means that the
4354 iteration variables don't leak into the current scope.
4355 The defined function is called immediately following its definition, with the
4356 result of that call being the result of the expression.
4357 The LC/SC version returns the populated container, while the GE version is
4358 flagged in symtable.c as a generator, so it returns the generator object
4359 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004360
4361 Possible cleanups:
4362 - iterate over the generator sequence instead of using recursion
4363*/
4364
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004365
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004366static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004368 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004369 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004371{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004372 comprehension_ty gen;
4373 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4374 if (gen->is_async) {
4375 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004376 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004377 } else {
4378 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004379 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004380 }
4381}
4382
4383static int
4384compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004385 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004386 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004387 expr_ty elt, expr_ty val, int type)
4388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 /* generate code for the iterator, then each of the ifs,
4390 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004392 comprehension_ty gen;
4393 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004394 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004396 start = compiler_new_block(c);
4397 skip = compiler_new_block(c);
4398 if_cleanup = compiler_new_block(c);
4399 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4402 anchor == NULL)
4403 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004407 if (gen_index == 0) {
4408 /* Receive outermost iter as an implicit argument */
4409 c->u->u_argcount = 1;
4410 ADDOP_I(c, LOAD_FAST, 0);
4411 }
4412 else {
4413 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004414 /* Fast path for the temporary variable assignment idiom:
4415 for y in [f(x)]
4416 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004417 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004418 switch (gen->iter->kind) {
4419 case List_kind:
4420 elts = gen->iter->v.List.elts;
4421 break;
4422 case Tuple_kind:
4423 elts = gen->iter->v.Tuple.elts;
4424 break;
4425 default:
4426 elts = NULL;
4427 }
4428 if (asdl_seq_LEN(elts) == 1) {
4429 expr_ty elt = asdl_seq_GET(elts, 0);
4430 if (elt->kind != Starred_kind) {
4431 VISIT(c, expr, elt);
4432 start = NULL;
4433 }
4434 }
4435 if (start) {
4436 VISIT(c, expr, gen->iter);
4437 ADDOP(c, GET_ITER);
4438 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004439 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004440 if (start) {
4441 depth++;
4442 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004443 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004444 NEXT_BLOCK(c);
4445 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004446 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 /* XXX this needs to be cleaned up...a lot! */
4449 n = asdl_seq_LEN(gen->ifs);
4450 for (i = 0; i < n; i++) {
4451 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004452 if (!compiler_jump_if(c, e, if_cleanup, 0))
4453 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 NEXT_BLOCK(c);
4455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 if (++gen_index < asdl_seq_LEN(generators))
4458 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004459 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 elt, val, type))
4461 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 /* only append after the last for generator */
4464 if (gen_index >= asdl_seq_LEN(generators)) {
4465 /* comprehension specific code */
4466 switch (type) {
4467 case COMP_GENEXP:
4468 VISIT(c, expr, elt);
4469 ADDOP(c, YIELD_VALUE);
4470 ADDOP(c, POP_TOP);
4471 break;
4472 case COMP_LISTCOMP:
4473 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004474 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004475 break;
4476 case COMP_SETCOMP:
4477 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004478 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 break;
4480 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004481 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004483 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004484 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004485 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004486 break;
4487 default:
4488 return 0;
4489 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 compiler_use_next_block(c, skip);
4492 }
4493 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004494 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004495 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004496 compiler_use_next_block(c, anchor);
4497 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498
4499 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004500}
4501
4502static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004503compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004504 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004505 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004506 expr_ty elt, expr_ty val, int type)
4507{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004509 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004510 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004511 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004512 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004513 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004514
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004515 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004516 return 0;
4517 }
4518
4519 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4520
4521 if (gen_index == 0) {
4522 /* Receive outermost iter as an implicit argument */
4523 c->u->u_argcount = 1;
4524 ADDOP_I(c, LOAD_FAST, 0);
4525 }
4526 else {
4527 /* Sub-iter - calculate on the fly */
4528 VISIT(c, expr, gen->iter);
4529 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530 }
4531
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004532 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004533
Mark Shannon582aaf12020-08-04 17:30:11 +01004534 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004535 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004536 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004537 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004538 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004539 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004540
4541 n = asdl_seq_LEN(gen->ifs);
4542 for (i = 0; i < n; i++) {
4543 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004544 if (!compiler_jump_if(c, e, if_cleanup, 0))
4545 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546 NEXT_BLOCK(c);
4547 }
4548
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004549 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004550 if (++gen_index < asdl_seq_LEN(generators))
4551 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004552 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 elt, val, type))
4554 return 0;
4555
4556 /* only append after the last for generator */
4557 if (gen_index >= asdl_seq_LEN(generators)) {
4558 /* comprehension specific code */
4559 switch (type) {
4560 case COMP_GENEXP:
4561 VISIT(c, expr, elt);
4562 ADDOP(c, YIELD_VALUE);
4563 ADDOP(c, POP_TOP);
4564 break;
4565 case COMP_LISTCOMP:
4566 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004567 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004568 break;
4569 case COMP_SETCOMP:
4570 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004571 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004572 break;
4573 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004574 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004575 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004576 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004577 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004578 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004579 break;
4580 default:
4581 return 0;
4582 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004583 }
4584 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004585 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004586
4587 compiler_use_next_block(c, except);
4588 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004589
4590 return 1;
4591}
4592
4593static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004594compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004595 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004596 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004598 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004599 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004600 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004601 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004602 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004603
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004604
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004605 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004606
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004607 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004608 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4609 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004610 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004611 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004612 }
4613
4614 is_async_generator = c->u->u_ste->ste_coroutine;
4615
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004616 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004617 compiler_error(c, "asynchronous comprehension outside of "
4618 "an asynchronous function");
4619 goto error_in_scope;
4620 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 if (type != COMP_GENEXP) {
4623 int op;
4624 switch (type) {
4625 case COMP_LISTCOMP:
4626 op = BUILD_LIST;
4627 break;
4628 case COMP_SETCOMP:
4629 op = BUILD_SET;
4630 break;
4631 case COMP_DICTCOMP:
4632 op = BUILD_MAP;
4633 break;
4634 default:
4635 PyErr_Format(PyExc_SystemError,
4636 "unknown comprehension type %d", type);
4637 goto error_in_scope;
4638 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 ADDOP_I(c, op, 0);
4641 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004642
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004643 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004644 val, type))
4645 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004647 if (type != COMP_GENEXP) {
4648 ADDOP(c, RETURN_VALUE);
4649 }
4650
4651 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004652 qualname = c->u->u_qualname;
4653 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004654 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004655 if (top_level_await && is_async_generator){
4656 c->u->u_ste->ste_coroutine = 1;
4657 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004658 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 goto error;
4660
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004661 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004663 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 Py_DECREF(co);
4665
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004666 VISIT(c, expr, outermost->iter);
4667
4668 if (outermost->is_async) {
4669 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004670 } else {
4671 ADDOP(c, GET_ITER);
4672 }
4673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004674 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004675
4676 if (is_async_generator && type != COMP_GENEXP) {
4677 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004678 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004679 ADDOP(c, YIELD_FROM);
4680 }
4681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004682 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004683error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004684 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004685error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004686 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 Py_XDECREF(co);
4688 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004689}
4690
4691static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004692compiler_genexp(struct compiler *c, expr_ty e)
4693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004694 static identifier name;
4695 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004696 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004697 if (!name)
4698 return 0;
4699 }
4700 assert(e->kind == GeneratorExp_kind);
4701 return compiler_comprehension(c, e, COMP_GENEXP, name,
4702 e->v.GeneratorExp.generators,
4703 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004704}
4705
4706static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004707compiler_listcomp(struct compiler *c, expr_ty e)
4708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004709 static identifier name;
4710 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004711 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004712 if (!name)
4713 return 0;
4714 }
4715 assert(e->kind == ListComp_kind);
4716 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4717 e->v.ListComp.generators,
4718 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004719}
4720
4721static int
4722compiler_setcomp(struct compiler *c, expr_ty e)
4723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004724 static identifier name;
4725 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004726 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004727 if (!name)
4728 return 0;
4729 }
4730 assert(e->kind == SetComp_kind);
4731 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4732 e->v.SetComp.generators,
4733 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004734}
4735
4736
4737static int
4738compiler_dictcomp(struct compiler *c, expr_ty e)
4739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004740 static identifier name;
4741 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004742 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 if (!name)
4744 return 0;
4745 }
4746 assert(e->kind == DictComp_kind);
4747 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4748 e->v.DictComp.generators,
4749 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004750}
4751
4752
4753static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004754compiler_visit_keyword(struct compiler *c, keyword_ty k)
4755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 VISIT(c, expr, k->value);
4757 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004758}
4759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004760/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004761 whether they are true or false.
4762
4763 Return values: 1 for true, 0 for false, -1 for non-constant.
4764 */
4765
4766static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004767expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004768{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004769 if (e->kind == Constant_kind) {
4770 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004771 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004772 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004773}
4774
Mark Shannonfee55262019-11-21 09:11:43 +00004775static int
4776compiler_with_except_finish(struct compiler *c) {
4777 basicblock *exit;
4778 exit = compiler_new_block(c);
4779 if (exit == NULL)
4780 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004781 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004782 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004783 ADDOP(c, RERAISE);
4784 compiler_use_next_block(c, exit);
4785 ADDOP(c, POP_TOP);
4786 ADDOP(c, POP_TOP);
4787 ADDOP(c, POP_TOP);
4788 ADDOP(c, POP_EXCEPT);
4789 ADDOP(c, POP_TOP);
4790 return 1;
4791}
Yury Selivanov75445082015-05-11 22:57:16 -04004792
4793/*
4794 Implements the async with statement.
4795
4796 The semantics outlined in that PEP are as follows:
4797
4798 async with EXPR as VAR:
4799 BLOCK
4800
4801 It is implemented roughly as:
4802
4803 context = EXPR
4804 exit = context.__aexit__ # not calling it
4805 value = await context.__aenter__()
4806 try:
4807 VAR = value # if VAR present in the syntax
4808 BLOCK
4809 finally:
4810 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004811 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004812 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004813 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004814 if not (await exit(*exc)):
4815 raise
4816 */
4817static int
4818compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4819{
Mark Shannonfee55262019-11-21 09:11:43 +00004820 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004821 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4822
4823 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004824 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004825 c->u->u_ste->ste_coroutine = 1;
4826 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004827 return compiler_error(c, "'async with' outside async function");
4828 }
Yury Selivanov75445082015-05-11 22:57:16 -04004829
4830 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004831 final = compiler_new_block(c);
4832 exit = compiler_new_block(c);
4833 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004834 return 0;
4835
4836 /* Evaluate EXPR */
4837 VISIT(c, expr, item->context_expr);
4838
4839 ADDOP(c, BEFORE_ASYNC_WITH);
4840 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004841 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004842 ADDOP(c, YIELD_FROM);
4843
Mark Shannon582aaf12020-08-04 17:30:11 +01004844 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004845
4846 /* SETUP_ASYNC_WITH pushes a finally block. */
4847 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004848 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004849 return 0;
4850 }
4851
4852 if (item->optional_vars) {
4853 VISIT(c, expr, item->optional_vars);
4854 }
4855 else {
4856 /* Discard result from context.__aenter__() */
4857 ADDOP(c, POP_TOP);
4858 }
4859
4860 pos++;
4861 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4862 /* BLOCK code */
4863 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4864 else if (!compiler_async_with(c, s, pos))
4865 return 0;
4866
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004867 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004868 ADDOP(c, POP_BLOCK);
4869 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004870
Mark Shannonfee55262019-11-21 09:11:43 +00004871 /* For successful outcome:
4872 * call __exit__(None, None, None)
4873 */
4874 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004875 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004876 ADDOP(c, GET_AWAITABLE);
4877 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4878 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004879
Mark Shannonfee55262019-11-21 09:11:43 +00004880 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004881
Mark Shannon582aaf12020-08-04 17:30:11 +01004882 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004883
4884 /* For exceptional outcome: */
4885 compiler_use_next_block(c, final);
4886
4887 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004888 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004889 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004890 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004891 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004892
Mark Shannonfee55262019-11-21 09:11:43 +00004893compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004894 return 1;
4895}
4896
4897
Guido van Rossumc2e20742006-02-27 22:32:47 +00004898/*
4899 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004900 with EXPR as VAR:
4901 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004902 is implemented as:
4903 <code for EXPR>
4904 SETUP_WITH E
4905 <code to store to VAR> or POP_TOP
4906 <code for BLOCK>
4907 LOAD_CONST (None, None, None)
4908 CALL_FUNCTION_EX 0
4909 JUMP_FORWARD EXIT
4910 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4911 POP_JUMP_IF_TRUE T:
4912 RERAISE
4913 T: POP_TOP * 3 (remove exception from stack)
4914 POP_EXCEPT
4915 POP_TOP
4916 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004917 */
Mark Shannonfee55262019-11-21 09:11:43 +00004918
Guido van Rossumc2e20742006-02-27 22:32:47 +00004919static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004920compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004921{
Mark Shannonfee55262019-11-21 09:11:43 +00004922 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004923 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004924
4925 assert(s->kind == With_kind);
4926
Guido van Rossumc2e20742006-02-27 22:32:47 +00004927 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004928 final = compiler_new_block(c);
4929 exit = compiler_new_block(c);
4930 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004931 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004932
Thomas Wouters477c8d52006-05-27 19:21:47 +00004933 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004934 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004935 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004936 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004937
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004938 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004939 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004940 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004941 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004942 }
4943
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004944 if (item->optional_vars) {
4945 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004946 }
4947 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004948 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004949 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004950 }
4951
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004952 pos++;
4953 if (pos == asdl_seq_LEN(s->v.With.items))
4954 /* BLOCK code */
4955 VISIT_SEQ(c, stmt, s->v.With.body)
4956 else if (!compiler_with(c, s, pos))
4957 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004958
Guido van Rossumc2e20742006-02-27 22:32:47 +00004959 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004960 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004961
Mark Shannonfee55262019-11-21 09:11:43 +00004962 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004963
Mark Shannonfee55262019-11-21 09:11:43 +00004964 /* For successful outcome:
4965 * call __exit__(None, None, None)
4966 */
4967 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004968 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004969 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004970 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004971
Mark Shannonfee55262019-11-21 09:11:43 +00004972 /* For exceptional outcome: */
4973 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004974
Mark Shannonfee55262019-11-21 09:11:43 +00004975 ADDOP(c, WITH_EXCEPT_START);
4976 compiler_with_except_finish(c);
4977
4978 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004979 return 1;
4980}
4981
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004982static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004983compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004985 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004986 case NamedExpr_kind:
4987 VISIT(c, expr, e->v.NamedExpr.value);
4988 ADDOP(c, DUP_TOP);
4989 VISIT(c, expr, e->v.NamedExpr.target);
4990 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004991 case BoolOp_kind:
4992 return compiler_boolop(c, e);
4993 case BinOp_kind:
4994 VISIT(c, expr, e->v.BinOp.left);
4995 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004996 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 break;
4998 case UnaryOp_kind:
4999 VISIT(c, expr, e->v.UnaryOp.operand);
5000 ADDOP(c, unaryop(e->v.UnaryOp.op));
5001 break;
5002 case Lambda_kind:
5003 return compiler_lambda(c, e);
5004 case IfExp_kind:
5005 return compiler_ifexp(c, e);
5006 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005007 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005009 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005010 case GeneratorExp_kind:
5011 return compiler_genexp(c, e);
5012 case ListComp_kind:
5013 return compiler_listcomp(c, e);
5014 case SetComp_kind:
5015 return compiler_setcomp(c, e);
5016 case DictComp_kind:
5017 return compiler_dictcomp(c, e);
5018 case Yield_kind:
5019 if (c->u->u_ste->ste_type != FunctionBlock)
5020 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005021 if (e->v.Yield.value) {
5022 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005023 }
5024 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005025 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005027 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005029 case YieldFrom_kind:
5030 if (c->u->u_ste->ste_type != FunctionBlock)
5031 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005032
5033 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5034 return compiler_error(c, "'yield from' inside async function");
5035
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005036 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005037 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005038 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005039 ADDOP(c, YIELD_FROM);
5040 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005041 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005042 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005043 if (c->u->u_ste->ste_type != FunctionBlock){
5044 return compiler_error(c, "'await' outside function");
5045 }
Yury Selivanov75445082015-05-11 22:57:16 -04005046
Victor Stinner331a6a52019-05-27 16:39:22 +02005047 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005048 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5049 return compiler_error(c, "'await' outside async function");
5050 }
5051 }
Yury Selivanov75445082015-05-11 22:57:16 -04005052
5053 VISIT(c, expr, e->v.Await.value);
5054 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005055 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005056 ADDOP(c, YIELD_FROM);
5057 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 case Compare_kind:
5059 return compiler_compare(c, e);
5060 case Call_kind:
5061 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005062 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005063 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005064 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005065 case JoinedStr_kind:
5066 return compiler_joined_str(c, e);
5067 case FormattedValue_kind:
5068 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 /* The following exprs can be assignment targets. */
5070 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005071 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005072 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 case Load:
5074 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5075 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005077 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5078 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005079 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5080 break;
5081 case Del:
5082 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5083 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005084 }
5085 break;
5086 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005087 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 case Starred_kind:
5089 switch (e->v.Starred.ctx) {
5090 case Store:
5091 /* In all legitimate cases, the Starred node was already replaced
5092 * by compiler_list/compiler_tuple. XXX: is that okay? */
5093 return compiler_error(c,
5094 "starred assignment target must be in a list or tuple");
5095 default:
5096 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005097 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005098 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005099 break;
5100 case Slice_kind:
5101 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 case Name_kind:
5103 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5104 /* child nodes of List and Tuple will have expr_context set */
5105 case List_kind:
5106 return compiler_list(c, e);
5107 case Tuple_kind:
5108 return compiler_tuple(c, e);
5109 }
5110 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005111}
5112
5113static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005114compiler_visit_expr(struct compiler *c, expr_ty e)
5115{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005116 int old_lineno = c->u->u_lineno;
5117 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005118 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005119 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005120 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005121 c->u->u_col_offset = old_col_offset;
5122 return res;
5123}
5124
5125static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005126compiler_augassign(struct compiler *c, stmt_ty s)
5127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005128 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005129 expr_ty e = s->v.AugAssign.target;
5130
5131 int old_lineno = c->u->u_lineno;
5132 int old_col_offset = c->u->u_col_offset;
5133 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005135 switch (e->kind) {
5136 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005137 VISIT(c, expr, e->v.Attribute.value);
5138 ADDOP(c, DUP_TOP);
5139 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005140 break;
5141 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005142 VISIT(c, expr, e->v.Subscript.value);
5143 VISIT(c, expr, e->v.Subscript.slice);
5144 ADDOP(c, DUP_TOP_TWO);
5145 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 break;
5147 case Name_kind:
5148 if (!compiler_nameop(c, e->v.Name.id, Load))
5149 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005150 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005151 default:
5152 PyErr_Format(PyExc_SystemError,
5153 "invalid node type (%d) for augmented assignment",
5154 e->kind);
5155 return 0;
5156 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005157
5158 c->u->u_lineno = old_lineno;
5159 c->u->u_col_offset = old_col_offset;
5160
5161 VISIT(c, expr, s->v.AugAssign.value);
5162 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5163
5164 SET_LOC(c, e);
5165
5166 switch (e->kind) {
5167 case Attribute_kind:
5168 ADDOP(c, ROT_TWO);
5169 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5170 break;
5171 case Subscript_kind:
5172 ADDOP(c, ROT_THREE);
5173 ADDOP(c, STORE_SUBSCR);
5174 break;
5175 case Name_kind:
5176 return compiler_nameop(c, e->v.Name.id, Store);
5177 default:
5178 Py_UNREACHABLE();
5179 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005180 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005181}
5182
5183static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005184check_ann_expr(struct compiler *c, expr_ty e)
5185{
5186 VISIT(c, expr, e);
5187 ADDOP(c, POP_TOP);
5188 return 1;
5189}
5190
5191static int
5192check_annotation(struct compiler *c, stmt_ty s)
5193{
5194 /* Annotations are only evaluated in a module or class. */
5195 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5196 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5197 return check_ann_expr(c, s->v.AnnAssign.annotation);
5198 }
5199 return 1;
5200}
5201
5202static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005203check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005204{
5205 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005206 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005207 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005208 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005209 return 0;
5210 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005211 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5212 return 0;
5213 }
5214 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5215 return 0;
5216 }
5217 return 1;
5218 case Tuple_kind: {
5219 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005220 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005221 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005222 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005223 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005224 return 0;
5225 }
5226 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005227 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005228 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005229 default:
5230 return check_ann_expr(c, e);
5231 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005232}
5233
5234static int
5235compiler_annassign(struct compiler *c, stmt_ty s)
5236{
5237 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005238 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005239
5240 assert(s->kind == AnnAssign_kind);
5241
5242 /* We perform the actual assignment first. */
5243 if (s->v.AnnAssign.value) {
5244 VISIT(c, expr, s->v.AnnAssign.value);
5245 VISIT(c, expr, targ);
5246 }
5247 switch (targ->kind) {
5248 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005249 if (forbidden_name(c, targ->v.Name.id, Store))
5250 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005251 /* If we have a simple name in a module or class, store annotation. */
5252 if (s->v.AnnAssign.simple &&
5253 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5254 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005255 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005256 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005257 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005258 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005259 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005260 }
5261 break;
5262 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005263 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5264 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005265 if (!s->v.AnnAssign.value &&
5266 !check_ann_expr(c, targ->v.Attribute.value)) {
5267 return 0;
5268 }
5269 break;
5270 case Subscript_kind:
5271 if (!s->v.AnnAssign.value &&
5272 (!check_ann_expr(c, targ->v.Subscript.value) ||
5273 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5274 return 0;
5275 }
5276 break;
5277 default:
5278 PyErr_Format(PyExc_SystemError,
5279 "invalid node type (%d) for annotated assignment",
5280 targ->kind);
5281 return 0;
5282 }
5283 /* Annotation is evaluated last. */
5284 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5285 return 0;
5286 }
5287 return 1;
5288}
5289
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005290/* Raises a SyntaxError and returns 0.
5291 If something goes wrong, a different exception may be raised.
5292*/
5293
5294static int
5295compiler_error(struct compiler *c, const char *errstr)
5296{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005297 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005298 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005299
Victor Stinner14e461d2013-08-26 22:28:21 +02005300 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005301 if (!loc) {
5302 Py_INCREF(Py_None);
5303 loc = Py_None;
5304 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005305 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005306 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005307 if (!u)
5308 goto exit;
5309 v = Py_BuildValue("(zO)", errstr, u);
5310 if (!v)
5311 goto exit;
5312 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005313 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 Py_DECREF(loc);
5315 Py_XDECREF(u);
5316 Py_XDECREF(v);
5317 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005318}
5319
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005320/* Emits a SyntaxWarning and returns 1 on success.
5321 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5322 and returns 0.
5323*/
5324static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005325compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005326{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005327 va_list vargs;
5328#ifdef HAVE_STDARG_PROTOTYPES
5329 va_start(vargs, format);
5330#else
5331 va_start(vargs);
5332#endif
5333 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5334 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005335 if (msg == NULL) {
5336 return 0;
5337 }
5338 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5339 c->u->u_lineno, NULL, NULL) < 0)
5340 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005341 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005342 /* Replace the SyntaxWarning exception with a SyntaxError
5343 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005344 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005345 assert(PyUnicode_AsUTF8(msg) != NULL);
5346 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005347 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005348 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005349 return 0;
5350 }
5351 Py_DECREF(msg);
5352 return 1;
5353}
5354
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005355static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005356compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005357{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005358 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005359 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005360
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005361 if (ctx == Load) {
5362 if (!check_subscripter(c, e->v.Subscript.value)) {
5363 return 0;
5364 }
5365 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5366 return 0;
5367 }
5368 }
5369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005371 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005372 case Store: op = STORE_SUBSCR; break;
5373 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005374 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005375 assert(op);
5376 VISIT(c, expr, e->v.Subscript.value);
5377 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005378 ADDOP(c, op);
5379 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005380}
5381
5382static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005383compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005385 int n = 2;
5386 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 /* only handles the cases where BUILD_SLICE is emitted */
5389 if (s->v.Slice.lower) {
5390 VISIT(c, expr, s->v.Slice.lower);
5391 }
5392 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005393 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 if (s->v.Slice.upper) {
5397 VISIT(c, expr, s->v.Slice.upper);
5398 }
5399 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005400 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 }
5402
5403 if (s->v.Slice.step) {
5404 n++;
5405 VISIT(c, expr, s->v.Slice.step);
5406 }
5407 ADDOP_I(c, BUILD_SLICE, n);
5408 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005409}
5410
Thomas Wouters89f507f2006-12-13 04:49:30 +00005411/* End of the compiler section, beginning of the assembler section */
5412
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005413/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005414 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005415
5416 XXX must handle implicit jumps from one block to next
5417*/
5418
Thomas Wouters89f507f2006-12-13 04:49:30 +00005419struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 PyObject *a_bytecode; /* string containing bytecode */
5421 int a_offset; /* offset into bytecode */
5422 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005423 PyObject *a_lnotab; /* string containing lnotab */
5424 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005425 int a_prevlineno; /* lineno of last emitted line in line table */
5426 int a_lineno; /* lineno of last emitted instruction */
5427 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005428 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005429};
5430
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005431Py_LOCAL_INLINE(void)
5432stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005433{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005434 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005435 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005436 assert(b->b_startdepth < 0);
5437 b->b_startdepth = depth;
5438 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005439 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005440}
5441
5442/* Find the flow path that needs the largest stack. We assume that
5443 * cycles in the flow graph have no net effect on the stack depth.
5444 */
5445static int
5446stackdepth(struct compiler *c)
5447{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005448 basicblock *b, *entryblock = NULL;
5449 basicblock **stack, **sp;
5450 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005451 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005452 b->b_startdepth = INT_MIN;
5453 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005454 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005455 }
5456 if (!entryblock)
5457 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005458 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5459 if (!stack) {
5460 PyErr_NoMemory();
5461 return -1;
5462 }
5463
5464 sp = stack;
5465 stackdepth_push(&sp, entryblock, 0);
5466 while (sp != stack) {
5467 b = *--sp;
5468 int depth = b->b_startdepth;
5469 assert(depth >= 0);
5470 basicblock *next = b->b_next;
5471 for (int i = 0; i < b->b_iused; i++) {
5472 struct instr *instr = &b->b_instr[i];
5473 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5474 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005475 _Py_FatalErrorFormat(__func__,
5476 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005477 }
5478 int new_depth = depth + effect;
5479 if (new_depth > maxdepth) {
5480 maxdepth = new_depth;
5481 }
5482 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005483 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005484 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5485 assert(effect != PY_INVALID_STACK_EFFECT);
5486 int target_depth = depth + effect;
5487 if (target_depth > maxdepth) {
5488 maxdepth = target_depth;
5489 }
5490 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005491 stackdepth_push(&sp, instr->i_target, target_depth);
5492 }
5493 depth = new_depth;
5494 if (instr->i_opcode == JUMP_ABSOLUTE ||
5495 instr->i_opcode == JUMP_FORWARD ||
5496 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005497 instr->i_opcode == RAISE_VARARGS ||
5498 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005499 {
5500 /* remaining code is dead */
5501 next = NULL;
5502 break;
5503 }
5504 }
5505 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005506 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005507 stackdepth_push(&sp, next, depth);
5508 }
5509 }
5510 PyObject_Free(stack);
5511 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005512}
5513
5514static int
5515assemble_init(struct assembler *a, int nblocks, int firstlineno)
5516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005518 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005519 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005520 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005521 if (a->a_bytecode == NULL) {
5522 goto error;
5523 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005524 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005525 if (a->a_lnotab == NULL) {
5526 goto error;
5527 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005528 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005529 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005530 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005531 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005532 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005533error:
5534 Py_XDECREF(a->a_bytecode);
5535 Py_XDECREF(a->a_lnotab);
5536 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005537}
5538
5539static void
5540assemble_free(struct assembler *a)
5541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005542 Py_XDECREF(a->a_bytecode);
5543 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005544}
5545
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005546static int
5547blocksize(basicblock *b)
5548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 int i;
5550 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005552 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005553 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005554 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005555}
5556
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005557static int
Mark Shannon877df852020-11-12 09:43:29 +00005558assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005559{
Mark Shannon877df852020-11-12 09:43:29 +00005560 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005561 if (a->a_lnotab_off + 2 >= len) {
5562 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5563 return 0;
5564 }
Mark Shannon877df852020-11-12 09:43:29 +00005565 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005569 *lnotab++ = bdelta;
5570 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005572}
5573
Mark Shannon877df852020-11-12 09:43:29 +00005574/* Appends a range to the end of the line number table. See
5575 * Objects/lnotab_notes.txt for the description of the line number table. */
5576
5577static int
5578assemble_line_range(struct assembler *a)
5579{
5580 int ldelta, bdelta;
5581 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5582 if (bdelta == 0) {
5583 return 1;
5584 }
5585 if (a->a_lineno < 0) {
5586 ldelta = -128;
5587 }
5588 else {
5589 ldelta = a->a_lineno - a->a_prevlineno;
5590 a->a_prevlineno = a->a_lineno;
5591 while (ldelta > 127) {
5592 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5593 return 0;
5594 }
5595 ldelta -= 127;
5596 }
5597 while (ldelta < -127) {
5598 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5599 return 0;
5600 }
5601 ldelta += 127;
5602 }
5603 }
5604 assert(-128 <= ldelta && ldelta < 128);
5605 while (bdelta > 254) {
5606 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5607 return 0;
5608 }
5609 ldelta = a->a_lineno < 0 ? -128 : 0;
5610 bdelta -= 254;
5611 }
5612 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5613 return 0;
5614 }
5615 a->a_lineno_start = a->a_offset;
5616 return 1;
5617}
5618
5619static int
5620assemble_lnotab(struct assembler *a, struct instr *i)
5621{
5622 if (i->i_lineno == a->a_lineno) {
5623 return 1;
5624 }
5625 if (!assemble_line_range(a)) {
5626 return 0;
5627 }
5628 a->a_lineno = i->i_lineno;
5629 return 1;
5630}
5631
5632
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005633/* assemble_emit()
5634 Extend the bytecode with a new instruction.
5635 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005636*/
5637
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005638static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005639assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005640{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005641 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005643 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005644
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005645 arg = i->i_oparg;
5646 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 if (i->i_lineno && !assemble_lnotab(a, i))
5648 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005649 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005650 if (len > PY_SSIZE_T_MAX / 2)
5651 return 0;
5652 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5653 return 0;
5654 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005655 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005656 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005657 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005659}
5660
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005661static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005662assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005665 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 /* Compute the size of each block and fixup jump args.
5669 Replace block pointer with position in bytecode. */
5670 do {
5671 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005672 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 bsize = blocksize(b);
5674 b->b_offset = totsize;
5675 totsize += bsize;
5676 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005677 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005678 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5679 bsize = b->b_offset;
5680 for (i = 0; i < b->b_iused; i++) {
5681 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005682 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 /* Relative jumps are computed relative to
5684 the instruction pointer after fetching
5685 the jump instruction.
5686 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005687 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005688 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005690 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005691 instr->i_oparg -= bsize;
5692 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005693 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005694 if (instrsize(instr->i_oparg) != isize) {
5695 extended_arg_recompile = 1;
5696 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005698 }
5699 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005701 /* XXX: This is an awful hack that could hurt performance, but
5702 on the bright side it should work until we come up
5703 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 The issue is that in the first loop blocksize() is called
5706 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005707 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005708 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005710 So we loop until we stop seeing new EXTENDED_ARGs.
5711 The only EXTENDED_ARGs that could be popping up are
5712 ones in jump instructions. So this should converge
5713 fairly quickly.
5714 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005715 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005716}
5717
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005718static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005719dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005722 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 tuple = PyTuple_New(size);
5725 if (tuple == NULL)
5726 return NULL;
5727 while (PyDict_Next(dict, &pos, &k, &v)) {
5728 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005729 Py_INCREF(k);
5730 assert((i - offset) < size);
5731 assert((i - offset) >= 0);
5732 PyTuple_SET_ITEM(tuple, i - offset, k);
5733 }
5734 return tuple;
5735}
5736
5737static PyObject *
5738consts_dict_keys_inorder(PyObject *dict)
5739{
5740 PyObject *consts, *k, *v;
5741 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5742
5743 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5744 if (consts == NULL)
5745 return NULL;
5746 while (PyDict_Next(dict, &pos, &k, &v)) {
5747 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005748 /* The keys of the dictionary can be tuples wrapping a contant.
5749 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5750 * the object we want is always second. */
5751 if (PyTuple_CheckExact(k)) {
5752 k = PyTuple_GET_ITEM(k, 1);
5753 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005755 assert(i < size);
5756 assert(i >= 0);
5757 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005758 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005759 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005760}
5761
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005762static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005763compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005765 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005766 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005767 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005768 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005769 if (ste->ste_nested)
5770 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005771 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005772 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005773 if (!ste->ste_generator && ste->ste_coroutine)
5774 flags |= CO_COROUTINE;
5775 if (ste->ste_generator && ste->ste_coroutine)
5776 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 if (ste->ste_varargs)
5778 flags |= CO_VARARGS;
5779 if (ste->ste_varkeywords)
5780 flags |= CO_VARKEYWORDS;
5781 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 /* (Only) inherit compilerflags in PyCF_MASK */
5784 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005785
Pablo Galindo90235812020-03-15 04:29:22 +00005786 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005787 ste->ste_coroutine &&
5788 !ste->ste_generator) {
5789 flags |= CO_COROUTINE;
5790 }
5791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005792 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005793}
5794
INADA Naokic2e16072018-11-26 21:23:22 +09005795// Merge *tuple* with constant cache.
5796// Unlike merge_consts_recursive(), this function doesn't work recursively.
5797static int
5798merge_const_tuple(struct compiler *c, PyObject **tuple)
5799{
5800 assert(PyTuple_CheckExact(*tuple));
5801
5802 PyObject *key = _PyCode_ConstantKey(*tuple);
5803 if (key == NULL) {
5804 return 0;
5805 }
5806
5807 // t is borrowed reference
5808 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5809 Py_DECREF(key);
5810 if (t == NULL) {
5811 return 0;
5812 }
5813 if (t == key) { // tuple is new constant.
5814 return 1;
5815 }
5816
5817 PyObject *u = PyTuple_GET_ITEM(t, 1);
5818 Py_INCREF(u);
5819 Py_DECREF(*tuple);
5820 *tuple = u;
5821 return 1;
5822}
5823
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005824static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005825makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005827 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 PyObject *names = NULL;
5829 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005830 PyObject *name = NULL;
5831 PyObject *freevars = NULL;
5832 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005833 Py_ssize_t nlocals;
5834 int nlocals_int;
5835 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005836 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005838 names = dict_keys_inorder(c->u->u_names, 0);
5839 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005840 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005841 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005842 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5844 if (!cellvars)
5845 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005846 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005847 if (!freevars)
5848 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005849
INADA Naokic2e16072018-11-26 21:23:22 +09005850 if (!merge_const_tuple(c, &names) ||
5851 !merge_const_tuple(c, &varnames) ||
5852 !merge_const_tuple(c, &cellvars) ||
5853 !merge_const_tuple(c, &freevars))
5854 {
5855 goto error;
5856 }
5857
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005858 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005859 assert(nlocals < INT_MAX);
5860 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005862 flags = compute_code_flags(c);
5863 if (flags < 0)
5864 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005865
Mark Shannon6e8128f2020-07-30 10:03:00 +01005866 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5867 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005868 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005869 }
INADA Naokic2e16072018-11-26 21:23:22 +09005870 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005871 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005872 goto error;
5873 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005874
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005875 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005876 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005877 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005878 maxdepth = stackdepth(c);
5879 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005880 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005881 goto error;
5882 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005883 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005884 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005885 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005886 varnames, freevars, cellvars, c->c_filename,
5887 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005888 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005889 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005890 Py_XDECREF(names);
5891 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 Py_XDECREF(name);
5893 Py_XDECREF(freevars);
5894 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005896}
5897
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005898
5899/* For debugging purposes only */
5900#if 0
5901static void
5902dump_instr(const struct instr *i)
5903{
Mark Shannon582aaf12020-08-04 17:30:11 +01005904 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5905 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005906 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005908 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005909 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005910 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005911 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005912 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5913 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005914}
5915
5916static void
5917dump_basicblock(const basicblock *b)
5918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005920 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5921 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005922 if (b->b_instr) {
5923 int i;
5924 for (i = 0; i < b->b_iused; i++) {
5925 fprintf(stderr, " [%02d] ", i);
5926 dump_instr(b->b_instr + i);
5927 }
5928 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005929}
5930#endif
5931
Mark Shannon6e8128f2020-07-30 10:03:00 +01005932static int
5933optimize_cfg(struct assembler *a, PyObject *consts);
5934
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005935static PyCodeObject *
5936assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 basicblock *b, *entryblock;
5939 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005940 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005941 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005942 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005944 /* Make sure every block that falls off the end returns None.
5945 XXX NEXT_BLOCK() isn't quite right, because if the last
5946 block ends with a jump or return b_next shouldn't set.
5947 */
5948 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005949 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005950 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005951 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005952 ADDOP(c, RETURN_VALUE);
5953 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 nblocks = 0;
5956 entryblock = NULL;
5957 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5958 nblocks++;
5959 entryblock = b;
5960 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005962 /* Set firstlineno if it wasn't explicitly set. */
5963 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005964 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005965 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005966 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 c->u->u_firstlineno = 1;
5968 }
5969 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5970 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005971 a.a_entry = entryblock;
5972 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005973
Mark Shannon6e8128f2020-07-30 10:03:00 +01005974 consts = consts_dict_keys_inorder(c->u->u_consts);
5975 if (consts == NULL) {
5976 goto error;
5977 }
5978 if (optimize_cfg(&a, consts)) {
5979 goto error;
5980 }
5981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005982 /* Can't modify the bytecode after computing jump offsets. */
5983 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005984
Mark Shannoncc75ab72020-11-12 19:49:33 +00005985 /* Emit code. */
5986 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005987 for (j = 0; j < b->b_iused; j++)
5988 if (!assemble_emit(&a, &b->b_instr[j]))
5989 goto error;
5990 }
Mark Shannon877df852020-11-12 09:43:29 +00005991 if (!assemble_line_range(&a)) {
5992 return 0;
5993 }
5994 /* Emit sentinel at end of line number table */
5995 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
5996 goto error;
5997 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6000 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006001 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006002 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006003
Mark Shannon6e8128f2020-07-30 10:03:00 +01006004 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006005 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006006 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006007 assemble_free(&a);
6008 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006009}
Georg Brandl8334fd92010-12-04 10:26:46 +00006010
6011#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006012PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006013PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6014 PyArena *arena)
6015{
6016 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6017}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006018
6019
6020/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6021 with LOAD_CONST (c1, c2, ... cn).
6022 The consts table must still be in list form so that the
6023 new constant (c1, c2, ... cn) can be appended.
6024 Called with codestr pointing to the first LOAD_CONST.
6025*/
6026static int
6027fold_tuple_on_constants(struct instr *inst,
6028 int n, PyObject *consts)
6029{
6030 /* Pre-conditions */
6031 assert(PyList_CheckExact(consts));
6032 assert(inst[n].i_opcode == BUILD_TUPLE);
6033 assert(inst[n].i_oparg == n);
6034
6035 for (int i = 0; i < n; i++) {
6036 if (inst[i].i_opcode != LOAD_CONST) {
6037 return 0;
6038 }
6039 }
6040
6041 /* Buildup new tuple of constants */
6042 PyObject *newconst = PyTuple_New(n);
6043 if (newconst == NULL) {
6044 return -1;
6045 }
6046 for (int i = 0; i < n; i++) {
6047 int arg = inst[i].i_oparg;
6048 PyObject *constant = PyList_GET_ITEM(consts, arg);
6049 Py_INCREF(constant);
6050 PyTuple_SET_ITEM(newconst, i, constant);
6051 }
6052 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006053 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006054 Py_DECREF(newconst);
6055 PyErr_SetString(PyExc_OverflowError, "too many constants");
6056 return -1;
6057 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006058 if (PyList_Append(consts, newconst)) {
6059 Py_DECREF(newconst);
6060 return -1;
6061 }
6062 Py_DECREF(newconst);
6063 for (int i = 0; i < n; i++) {
6064 inst[i].i_opcode = NOP;
6065 }
6066 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006067 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006068 return 0;
6069}
6070
Mark Shannoncc75ab72020-11-12 19:49:33 +00006071/* Maximum size of basic block that should be copied in optimizer */
6072#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006073
6074/* Optimization */
6075static int
6076optimize_basic_block(basicblock *bb, PyObject *consts)
6077{
6078 assert(PyList_CheckExact(consts));
6079 struct instr nop;
6080 nop.i_opcode = NOP;
6081 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006082 for (int i = 0; i < bb->b_iused; i++) {
6083 struct instr *inst = &bb->b_instr[i];
6084 int oparg = inst->i_oparg;
6085 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006086 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006087 /* Skip over empty basic blocks. */
6088 while (inst->i_target->b_iused == 0) {
6089 inst->i_target = inst->i_target->b_next;
6090 }
6091 target = &inst->i_target->b_instr[0];
6092 }
6093 else {
6094 target = &nop;
6095 }
6096 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006097 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006098 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006099 {
6100 PyObject* cnt;
6101 int is_true;
6102 int jump_if_true;
6103 switch(nextop) {
6104 case POP_JUMP_IF_FALSE:
6105 case POP_JUMP_IF_TRUE:
6106 cnt = PyList_GET_ITEM(consts, oparg);
6107 is_true = PyObject_IsTrue(cnt);
6108 if (is_true == -1) {
6109 goto error;
6110 }
6111 inst->i_opcode = NOP;
6112 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6113 if (is_true == jump_if_true) {
6114 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6115 bb->b_nofallthrough = 1;
6116 }
6117 else {
6118 bb->b_instr[i+1].i_opcode = NOP;
6119 }
6120 break;
6121 case JUMP_IF_FALSE_OR_POP:
6122 case JUMP_IF_TRUE_OR_POP:
6123 cnt = PyList_GET_ITEM(consts, oparg);
6124 is_true = PyObject_IsTrue(cnt);
6125 if (is_true == -1) {
6126 goto error;
6127 }
6128 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6129 if (is_true == jump_if_true) {
6130 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6131 bb->b_nofallthrough = 1;
6132 }
6133 else {
6134 inst->i_opcode = NOP;
6135 bb->b_instr[i+1].i_opcode = NOP;
6136 }
6137 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006138 }
6139 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006140 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006141
6142 /* Try to fold tuples of constants.
6143 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6144 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6145 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6146 case BUILD_TUPLE:
6147 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6148 switch(oparg) {
6149 case 1:
6150 inst->i_opcode = NOP;
6151 bb->b_instr[i+1].i_opcode = NOP;
6152 break;
6153 case 2:
6154 inst->i_opcode = ROT_TWO;
6155 bb->b_instr[i+1].i_opcode = NOP;
6156 break;
6157 case 3:
6158 inst->i_opcode = ROT_THREE;
6159 bb->b_instr[i+1].i_opcode = ROT_TWO;
6160 }
6161 break;
6162 }
6163 if (i >= oparg) {
6164 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6165 goto error;
6166 }
6167 }
6168 break;
6169
6170 /* Simplify conditional jump to conditional jump where the
6171 result of the first test implies the success of a similar
6172 test or the failure of the opposite test.
6173 Arises in code like:
6174 "a and b or c"
6175 "(a and b) and c"
6176 "(a or b) or c"
6177 "(a or b) and c"
6178 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6179 --> x:JUMP_IF_FALSE_OR_POP z
6180 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6181 --> x:POP_JUMP_IF_FALSE y+1
6182 where y+1 is the instruction following the second test.
6183 */
6184 case JUMP_IF_FALSE_OR_POP:
6185 switch(target->i_opcode) {
6186 case POP_JUMP_IF_FALSE:
6187 *inst = *target;
Mark Shannon266b4622020-11-17 19:30:14 +00006188 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006189 break;
6190 case JUMP_ABSOLUTE:
6191 case JUMP_FORWARD:
6192 case JUMP_IF_FALSE_OR_POP:
Mark Shannon266b4622020-11-17 19:30:14 +00006193 if (inst->i_target != target->i_target) {
6194 inst->i_target = target->i_target;
6195 --i;
6196 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006197 break;
6198 case JUMP_IF_TRUE_OR_POP:
6199 assert (inst->i_target->b_iused == 1);
6200 inst->i_opcode = POP_JUMP_IF_FALSE;
6201 inst->i_target = inst->i_target->b_next;
Mark Shannon266b4622020-11-17 19:30:14 +00006202 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006203 break;
6204 }
6205 break;
6206
6207 case JUMP_IF_TRUE_OR_POP:
6208 switch(target->i_opcode) {
6209 case POP_JUMP_IF_TRUE:
6210 *inst = *target;
Mark Shannon266b4622020-11-17 19:30:14 +00006211 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006212 break;
6213 case JUMP_ABSOLUTE:
6214 case JUMP_FORWARD:
6215 case JUMP_IF_TRUE_OR_POP:
Mark Shannon266b4622020-11-17 19:30:14 +00006216 if (inst->i_target != target->i_target) {
6217 inst->i_target = target->i_target;
6218 --i;
6219 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006220 break;
6221 case JUMP_IF_FALSE_OR_POP:
6222 assert (inst->i_target->b_iused == 1);
6223 inst->i_opcode = POP_JUMP_IF_TRUE;
6224 inst->i_target = inst->i_target->b_next;
Mark Shannon266b4622020-11-17 19:30:14 +00006225 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006226 break;
6227 }
6228 break;
6229
6230 case POP_JUMP_IF_FALSE:
6231 switch(target->i_opcode) {
6232 case JUMP_ABSOLUTE:
6233 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006234 if (inst->i_target != target->i_target) {
6235 inst->i_target = target->i_target;
6236 --i;
6237 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006238 break;
6239 }
6240 break;
6241
6242 case POP_JUMP_IF_TRUE:
6243 switch(target->i_opcode) {
6244 case JUMP_ABSOLUTE:
6245 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006246 if (inst->i_target != target->i_target) {
6247 inst->i_target = target->i_target;
6248 --i;
6249 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006250 break;
6251 }
6252 break;
6253
6254 case JUMP_ABSOLUTE:
6255 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006256 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006257 switch(target->i_opcode) {
6258 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006259 if (inst->i_target != target->i_target) {
6260 inst->i_target = target->i_target;
6261 --i;
6262 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006263 break;
6264 case JUMP_ABSOLUTE:
Mark Shannon266b4622020-11-17 19:30:14 +00006265 if (inst->i_target != target->i_target) {
6266 inst->i_target = target->i_target;
6267 inst->i_opcode = target->i_opcode;
6268 --i;
6269 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006270 break;
6271 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006272 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6273 basicblock *to_copy = inst->i_target;
6274 *inst = to_copy->b_instr[0];
6275 for (i = 1; i < to_copy->b_iused; i++) {
6276 int index = compiler_next_instr(bb);
6277 if (index < 0) {
6278 return -1;
6279 }
6280 bb->b_instr[index] = to_copy->b_instr[i];
6281 }
6282 bb->b_exit = 1;
6283 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006284 break;
6285 }
6286 }
6287 return 0;
6288error:
6289 return -1;
6290}
6291
6292
6293static void
6294clean_basic_block(basicblock *bb) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006295 /* Remove NOPs. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006296 int dest = 0;
Mark Shannon877df852020-11-12 09:43:29 +00006297 int prev_lineno = -1;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006298 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006299 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006300 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006301 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006302 if (lineno < 0) {
6303 continue;
6304 }
Mark Shannon266b4622020-11-17 19:30:14 +00006305 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006306 if (prev_lineno == lineno) {
6307 continue;
6308 }
Mark Shannon266b4622020-11-17 19:30:14 +00006309 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006310 if (src < bb->b_iused - 1) {
6311 int next_lineno = bb->b_instr[src+1].i_lineno;
6312 if (next_lineno < 0 || next_lineno == lineno) {
6313 bb->b_instr[src+1].i_lineno = lineno;
6314 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006315 }
6316 }
Mark Shannon266b4622020-11-17 19:30:14 +00006317 else {
6318 basicblock* next = bb->b_next;
6319 while (next && next->b_iused == 0) {
6320 next = next->b_next;
6321 }
6322 /* or if last instruction in BB and next BB has same line number */
6323 if (next) {
6324 if (lineno == next->b_instr[0].i_lineno) {
6325 continue;
6326 }
6327 }
6328 }
6329
Mark Shannon6e8128f2020-07-30 10:03:00 +01006330 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006331 if (dest != src) {
6332 bb->b_instr[dest] = bb->b_instr[src];
6333 }
6334 dest++;
6335 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006336 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006337 assert(dest <= bb->b_iused);
6338 bb->b_iused = dest;
6339}
6340
Mark Shannon266b4622020-11-17 19:30:14 +00006341
6342static int
6343normalize_basic_block(basicblock *bb) {
6344 /* Mark blocks as exit and/or nofallthrough.
6345 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006346 for (int i = 0; i < bb->b_iused; i++) {
6347 switch(bb->b_instr[i].i_opcode) {
6348 case RETURN_VALUE:
6349 case RAISE_VARARGS:
6350 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006351 bb->b_exit = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006352 /* fall through */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006353 case JUMP_ABSOLUTE:
6354 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006355 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006356 /* fall through */
6357 case POP_JUMP_IF_FALSE:
6358 case POP_JUMP_IF_TRUE:
6359 case JUMP_IF_FALSE_OR_POP:
6360 case JUMP_IF_TRUE_OR_POP:
6361 if (i != bb->b_iused-1) {
6362 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6363 return -1;
6364 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006365 }
6366 }
Mark Shannon266b4622020-11-17 19:30:14 +00006367 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006368}
6369
6370
Mark Shannon6e8128f2020-07-30 10:03:00 +01006371static int
6372mark_reachable(struct assembler *a) {
6373 basicblock **stack, **sp;
6374 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6375 if (stack == NULL) {
6376 return -1;
6377 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006378 a->a_entry->b_reachable = 1;
6379 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006380 while (sp > stack) {
6381 basicblock *b = *(--sp);
Mark Shannoncc75ab72020-11-12 19:49:33 +00006382 if (b->b_next && !b->b_nofallthrough && b->b_next->b_reachable == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006383 b->b_next->b_reachable = 1;
6384 *sp++ = b->b_next;
6385 }
6386 for (int i = 0; i < b->b_iused; i++) {
6387 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006388 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006389 target = b->b_instr[i].i_target;
6390 if (target->b_reachable == 0) {
6391 target->b_reachable = 1;
6392 *sp++ = target;
6393 }
6394 }
6395 }
6396 }
6397 PyObject_Free(stack);
6398 return 0;
6399}
6400
6401
6402/* Perform basic peephole optimizations on a control flow graph.
6403 The consts object should still be in list form to allow new constants
6404 to be appended.
6405
6406 All transformations keep the code size the same or smaller.
6407 For those that reduce size, the gaps are initially filled with
6408 NOPs. Later those NOPs are removed.
6409*/
6410
6411static int
6412optimize_cfg(struct assembler *a, PyObject *consts)
6413{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006414 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon266b4622020-11-17 19:30:14 +00006415 if (normalize_basic_block(b)) {
6416 return -1;
6417 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006418 }
6419 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6420 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006421 return -1;
6422 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006423 clean_basic_block(b);
6424 assert(b->b_reachable == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006425 }
6426 if (mark_reachable(a)) {
6427 return -1;
6428 }
6429 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006430 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6431 if (b->b_reachable == 0) {
6432 b->b_iused = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006433 }
6434 }
6435 return 0;
6436}
6437
6438/* Retained for API compatibility.
6439 * Optimization is now done in optimize_cfg */
6440
6441PyObject *
6442PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6443 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6444{
6445 Py_INCREF(code);
6446 return code;
6447}
6448