blob: 1989b4af320dab485489f3fcac72bb9c6e53f583 [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,
2030 expr_ty annotation, PyObject *names)
2031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002033 PyObject *mangled;
Batuhan Taskaya044a1042020-10-06 23:03:02 +03002034 VISIT(c, annexpr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01002035 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002036 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002037 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002038 if (PyList_Append(names, mangled) < 0) {
2039 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002040 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002041 }
2042 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002044 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002045}
2046
2047static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002048compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Neal Norwitzc1505362006-12-28 06:47:50 +00002049 PyObject *names)
2050{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002051 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 for (i = 0; i < asdl_seq_LEN(args); i++) {
2053 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002054 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 c,
2056 arg->arg,
2057 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002058 names))
2059 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002061 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002062}
2063
2064static int
2065compiler_visit_annotations(struct compiler *c, arguments_ty args,
2066 expr_ty returns)
2067{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002068 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002069 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002070
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002071 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 */
2073 static identifier return_str;
2074 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002075 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 names = PyList_New(0);
2077 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002078 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002079
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002080 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002082 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2083 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002084 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002085 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002086 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002088 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002090 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002091 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002092 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (!return_str) {
2096 return_str = PyUnicode_InternFromString("return");
2097 if (!return_str)
2098 goto error;
2099 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002100 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 goto error;
2102 }
2103
2104 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002106 PyObject *keytuple = PyList_AsTuple(names);
2107 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002108 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002109 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002110 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 else {
2113 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002114 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002115 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002116
2117error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002119 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002120}
2121
2122static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002123compiler_visit_defaults(struct compiler *c, arguments_ty args)
2124{
2125 VISIT_SEQ(c, expr, args->defaults);
2126 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2127 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128}
2129
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002130static Py_ssize_t
2131compiler_default_arguments(struct compiler *c, arguments_ty args)
2132{
2133 Py_ssize_t funcflags = 0;
2134 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002135 if (!compiler_visit_defaults(c, args))
2136 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002137 funcflags |= 0x01;
2138 }
2139 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002140 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002141 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002142 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002143 return -1;
2144 }
2145 else if (res > 0) {
2146 funcflags |= 0x02;
2147 }
2148 }
2149 return funcflags;
2150}
2151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002153forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2154{
2155
2156 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2157 compiler_error(c, "cannot assign to __debug__");
2158 return 1;
2159 }
2160 return 0;
2161}
2162
2163static int
2164compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2165{
2166 if (arg != NULL) {
2167 if (forbidden_name(c, arg->arg, Store))
2168 return 0;
2169 }
2170 return 1;
2171}
2172
2173static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002174compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002175{
2176 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002177 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002178 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2179 return 0;
2180 }
2181 }
2182 return 1;
2183}
2184
2185static int
2186compiler_check_debug_args(struct compiler *c, arguments_ty args)
2187{
2188 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2189 return 0;
2190 if (!compiler_check_debug_args_seq(c, args->args))
2191 return 0;
2192 if (!compiler_check_debug_one_arg(c, args->vararg))
2193 return 0;
2194 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2195 return 0;
2196 if (!compiler_check_debug_one_arg(c, args->kwarg))
2197 return 0;
2198 return 1;
2199}
2200
2201static int
Yury Selivanov75445082015-05-11 22:57:16 -04002202compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002205 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002206 arguments_ty args;
2207 expr_ty returns;
2208 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002209 asdl_expr_seq* decos;
2210 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002211 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002212 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002213 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002214 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002215
Yury Selivanov75445082015-05-11 22:57:16 -04002216 if (is_async) {
2217 assert(s->kind == AsyncFunctionDef_kind);
2218
2219 args = s->v.AsyncFunctionDef.args;
2220 returns = s->v.AsyncFunctionDef.returns;
2221 decos = s->v.AsyncFunctionDef.decorator_list;
2222 name = s->v.AsyncFunctionDef.name;
2223 body = s->v.AsyncFunctionDef.body;
2224
2225 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2226 } else {
2227 assert(s->kind == FunctionDef_kind);
2228
2229 args = s->v.FunctionDef.args;
2230 returns = s->v.FunctionDef.returns;
2231 decos = s->v.FunctionDef.decorator_list;
2232 name = s->v.FunctionDef.name;
2233 body = s->v.FunctionDef.body;
2234
2235 scope_type = COMPILER_SCOPE_FUNCTION;
2236 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002238 if (!compiler_check_debug_args(c, args))
2239 return 0;
2240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (!compiler_decorators(c, decos))
2242 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002243
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002244 firstlineno = s->lineno;
2245 if (asdl_seq_LEN(decos)) {
2246 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2247 }
2248
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002249 funcflags = compiler_default_arguments(c, args);
2250 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002252 }
2253
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002254 annotations = compiler_visit_annotations(c, args, returns);
2255 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002256 return 0;
2257 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002258 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002259 funcflags |= 0x04;
2260 }
2261
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002262 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002263 return 0;
2264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265
INADA Naokicb41b272017-02-23 00:31:59 +09002266 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002267 if (c->c_optimize < 2) {
2268 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002269 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002270 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 compiler_exit_scope(c);
2272 return 0;
2273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002276 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002278 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002279 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002282 qualname = c->u->u_qualname;
2283 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002285 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002286 Py_XDECREF(qualname);
2287 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002289 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002291 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002292 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* decorators */
2296 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2297 ADDOP_I(c, CALL_FUNCTION, 1);
2298 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299
Yury Selivanov75445082015-05-11 22:57:16 -04002300 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301}
2302
2303static int
2304compiler_class(struct compiler *c, stmt_ty s)
2305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 PyCodeObject *co;
2307 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002308 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002309 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (!compiler_decorators(c, decos))
2312 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002313
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002314 firstlineno = s->lineno;
2315 if (asdl_seq_LEN(decos)) {
2316 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2317 }
2318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* ultimately generate code for:
2320 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2321 where:
2322 <func> is a function/closure created from the class body;
2323 it has a single argument (__locals__) where the dict
2324 (or MutableSequence) representing the locals is passed
2325 <name> is the class name
2326 <bases> is the positional arguments and *varargs argument
2327 <keywords> is the keyword arguments and **kwds argument
2328 This borrows from compiler_call.
2329 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002332 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002333 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return 0;
2335 /* this block represents what we do in the new scope */
2336 {
2337 /* use the class name for name mangling */
2338 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002339 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* load (global) __name__ ... */
2341 str = PyUnicode_InternFromString("__name__");
2342 if (!str || !compiler_nameop(c, str, Load)) {
2343 Py_XDECREF(str);
2344 compiler_exit_scope(c);
2345 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002346 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 Py_DECREF(str);
2348 /* ... and store it as __module__ */
2349 str = PyUnicode_InternFromString("__module__");
2350 if (!str || !compiler_nameop(c, str, Store)) {
2351 Py_XDECREF(str);
2352 compiler_exit_scope(c);
2353 return 0;
2354 }
2355 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002356 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002357 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002358 str = PyUnicode_InternFromString("__qualname__");
2359 if (!str || !compiler_nameop(c, str, Store)) {
2360 Py_XDECREF(str);
2361 compiler_exit_scope(c);
2362 return 0;
2363 }
2364 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002366 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 compiler_exit_scope(c);
2368 return 0;
2369 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002370 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002371 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002372 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002373 str = PyUnicode_InternFromString("__class__");
2374 if (str == NULL) {
2375 compiler_exit_scope(c);
2376 return 0;
2377 }
2378 i = compiler_lookup_arg(c->u->u_cellvars, str);
2379 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002380 if (i < 0) {
2381 compiler_exit_scope(c);
2382 return 0;
2383 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002384 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002387 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002388 str = PyUnicode_InternFromString("__classcell__");
2389 if (!str || !compiler_nameop(c, str, Store)) {
2390 Py_XDECREF(str);
2391 compiler_exit_scope(c);
2392 return 0;
2393 }
2394 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002396 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002397 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002398 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002399 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002400 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002401 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* create the code object */
2403 co = assemble(c, 1);
2404 }
2405 /* leave the new scope */
2406 compiler_exit_scope(c);
2407 if (co == NULL)
2408 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* 2. load the 'build_class' function */
2411 ADDOP(c, LOAD_BUILD_CLASS);
2412
2413 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002414 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 Py_DECREF(co);
2416
2417 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002418 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419
2420 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002421 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return 0;
2423
2424 /* 6. apply decorators */
2425 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2426 ADDOP_I(c, CALL_FUNCTION, 1);
2427 }
2428
2429 /* 7. store into <name> */
2430 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2431 return 0;
2432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433}
2434
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002435/* Return 0 if the expression is a constant value except named singletons.
2436 Return 1 otherwise. */
2437static int
2438check_is_arg(expr_ty e)
2439{
2440 if (e->kind != Constant_kind) {
2441 return 1;
2442 }
2443 PyObject *value = e->v.Constant.value;
2444 return (value == Py_None
2445 || value == Py_False
2446 || value == Py_True
2447 || value == Py_Ellipsis);
2448}
2449
2450/* Check operands of identity chacks ("is" and "is not").
2451 Emit a warning if any operand is a constant except named singletons.
2452 Return 0 on error.
2453 */
2454static int
2455check_compare(struct compiler *c, expr_ty e)
2456{
2457 Py_ssize_t i, n;
2458 int left = check_is_arg(e->v.Compare.left);
2459 n = asdl_seq_LEN(e->v.Compare.ops);
2460 for (i = 0; i < n; i++) {
2461 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2462 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2463 if (op == Is || op == IsNot) {
2464 if (!right || !left) {
2465 const char *msg = (op == Is)
2466 ? "\"is\" with a literal. Did you mean \"==\"?"
2467 : "\"is not\" with a literal. Did you mean \"!=\"?";
2468 return compiler_warn(c, msg);
2469 }
2470 }
2471 left = right;
2472 }
2473 return 1;
2474}
2475
Mark Shannon9af0e472020-01-14 10:12:45 +00002476static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002477{
Mark Shannon9af0e472020-01-14 10:12:45 +00002478 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002479 switch (op) {
2480 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002481 cmp = Py_EQ;
2482 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002484 cmp = Py_NE;
2485 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002486 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002487 cmp = Py_LT;
2488 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002489 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002490 cmp = Py_LE;
2491 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002492 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002493 cmp = Py_GT;
2494 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002495 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002496 cmp = Py_GE;
2497 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002498 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002499 ADDOP_I(c, IS_OP, 0);
2500 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002501 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002502 ADDOP_I(c, IS_OP, 1);
2503 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002504 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002505 ADDOP_I(c, CONTAINS_OP, 0);
2506 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002507 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002508 ADDOP_I(c, CONTAINS_OP, 1);
2509 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002510 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002511 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002512 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002513 ADDOP_I(c, COMPARE_OP, cmp);
2514 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002515}
2516
Mark Shannon9af0e472020-01-14 10:12:45 +00002517
2518
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002519static int
2520compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2521{
2522 switch (e->kind) {
2523 case UnaryOp_kind:
2524 if (e->v.UnaryOp.op == Not)
2525 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2526 /* fallback to general implementation */
2527 break;
2528 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002529 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002530 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2531 assert(n >= 0);
2532 int cond2 = e->v.BoolOp.op == Or;
2533 basicblock *next2 = next;
2534 if (!cond2 != !cond) {
2535 next2 = compiler_new_block(c);
2536 if (next2 == NULL)
2537 return 0;
2538 }
2539 for (i = 0; i < n; ++i) {
2540 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2541 return 0;
2542 }
2543 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2544 return 0;
2545 if (next2 != next)
2546 compiler_use_next_block(c, next2);
2547 return 1;
2548 }
2549 case IfExp_kind: {
2550 basicblock *end, *next2;
2551 end = compiler_new_block(c);
2552 if (end == NULL)
2553 return 0;
2554 next2 = compiler_new_block(c);
2555 if (next2 == NULL)
2556 return 0;
2557 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2558 return 0;
2559 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2560 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002561 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002562 compiler_use_next_block(c, next2);
2563 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2564 return 0;
2565 compiler_use_next_block(c, end);
2566 return 1;
2567 }
2568 case Compare_kind: {
2569 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2570 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002571 if (!check_compare(c, e)) {
2572 return 0;
2573 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002574 basicblock *cleanup = compiler_new_block(c);
2575 if (cleanup == NULL)
2576 return 0;
2577 VISIT(c, expr, e->v.Compare.left);
2578 for (i = 0; i < n; i++) {
2579 VISIT(c, expr,
2580 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2581 ADDOP(c, DUP_TOP);
2582 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002583 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002584 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002585 NEXT_BLOCK(c);
2586 }
2587 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002588 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002589 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002590 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002591 basicblock *end = compiler_new_block(c);
2592 if (end == NULL)
2593 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002594 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002595 compiler_use_next_block(c, cleanup);
2596 ADDOP(c, POP_TOP);
2597 if (!cond) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002598 ADDOP_JUMP(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002599 }
2600 compiler_use_next_block(c, end);
2601 return 1;
2602 }
2603 /* fallback to general implementation */
2604 break;
2605 }
2606 default:
2607 /* fallback to general implementation */
2608 break;
2609 }
2610
2611 /* general implementation */
2612 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002613 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002614 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002615 return 1;
2616}
2617
2618static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002619compiler_ifexp(struct compiler *c, expr_ty e)
2620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 basicblock *end, *next;
2622
2623 assert(e->kind == IfExp_kind);
2624 end = compiler_new_block(c);
2625 if (end == NULL)
2626 return 0;
2627 next = compiler_new_block(c);
2628 if (next == NULL)
2629 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002630 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2631 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002633 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 compiler_use_next_block(c, next);
2635 VISIT(c, expr, e->v.IfExp.orelse);
2636 compiler_use_next_block(c, end);
2637 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002638}
2639
2640static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641compiler_lambda(struct compiler *c, expr_ty e)
2642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002644 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002646 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 arguments_ty args = e->v.Lambda.args;
2648 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002649
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002650 if (!compiler_check_debug_args(c, args))
2651 return 0;
2652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (!name) {
2654 name = PyUnicode_InternFromString("<lambda>");
2655 if (!name)
2656 return 0;
2657 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002658
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002659 funcflags = compiler_default_arguments(c, args);
2660 if (funcflags == -1) {
2661 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002663
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002664 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002665 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 /* Make None the first constant, so the lambda can't have a
2669 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002670 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002674 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2676 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2677 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002678 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 }
2680 else {
2681 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002682 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002684 qualname = c->u->u_qualname;
2685 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002687 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002689
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002690 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002691 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 Py_DECREF(co);
2693
2694 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695}
2696
2697static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002698compiler_if(struct compiler *c, stmt_ty s)
2699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 basicblock *end, *next;
2701 int constant;
2702 assert(s->kind == If_kind);
2703 end = compiler_new_block(c);
2704 if (end == NULL)
2705 return 0;
2706
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002707 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002708 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 * constant = 1: "if 1", "if 2", ...
2710 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002711 if (constant == 0) {
2712 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002714 END_DO_NOT_EMIT_BYTECODE
2715 if (s->v.If.orelse) {
2716 VISIT_SEQ(c, stmt, s->v.If.orelse);
2717 }
2718 } else if (constant == 1) {
2719 VISIT_SEQ(c, stmt, s->v.If.body);
2720 if (s->v.If.orelse) {
2721 BEGIN_DO_NOT_EMIT_BYTECODE
2722 VISIT_SEQ(c, stmt, s->v.If.orelse);
2723 END_DO_NOT_EMIT_BYTECODE
2724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002726 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 next = compiler_new_block(c);
2728 if (next == NULL)
2729 return 0;
2730 }
Mark Shannonfee55262019-11-21 09:11:43 +00002731 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002733 }
2734 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002735 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002736 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002738 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002739 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 compiler_use_next_block(c, next);
2741 VISIT_SEQ(c, stmt, s->v.If.orelse);
2742 }
2743 }
2744 compiler_use_next_block(c, end);
2745 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002746}
2747
2748static int
2749compiler_for(struct compiler *c, stmt_ty s)
2750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 start = compiler_new_block(c);
2754 cleanup = compiler_new_block(c);
2755 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002756 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002758 }
2759 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002761 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 VISIT(c, expr, s->v.For.iter);
2763 ADDOP(c, GET_ITER);
2764 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002765 ADDOP_JUMP(c, FOR_ITER, cleanup);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 VISIT(c, expr, s->v.For.target);
2767 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002768 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002770
2771 compiler_pop_fblock(c, FOR_LOOP, start);
2772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 VISIT_SEQ(c, stmt, s->v.For.orelse);
2774 compiler_use_next_block(c, end);
2775 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002776}
2777
Yury Selivanov75445082015-05-11 22:57:16 -04002778
2779static int
2780compiler_async_for(struct compiler *c, stmt_ty s)
2781{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002782 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002783 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002784 c->u->u_ste->ste_coroutine = 1;
2785 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002786 return compiler_error(c, "'async for' outside async function");
2787 }
2788
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002789 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002790 except = compiler_new_block(c);
2791 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002792
Mark Shannonfee55262019-11-21 09:11:43 +00002793 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002794 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002795 }
Yury Selivanov75445082015-05-11 22:57:16 -04002796 VISIT(c, expr, s->v.AsyncFor.iter);
2797 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002798
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002799 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002800 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002801 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002802 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002804 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002805 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002806 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002807 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002808 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002809
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002810 /* Success block for __anext__ */
2811 VISIT(c, expr, s->v.AsyncFor.target);
2812 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002813 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002814
2815 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002816
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002817 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002818 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002819
2820 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002821 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002822
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002823 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002824 VISIT_SEQ(c, stmt, s->v.For.orelse);
2825
2826 compiler_use_next_block(c, end);
2827
2828 return 1;
2829}
2830
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002831static int
2832compiler_while(struct compiler *c, stmt_ty s)
2833{
Mark Shannon266b4622020-11-17 19:30:14 +00002834 basicblock *loop, *body, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002835 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002838 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002839 // Push a dummy block so the VISIT_SEQ knows that we are
2840 // inside a while loop so it can correctly evaluate syntax
2841 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002842 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002843 return 0;
2844 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002845 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002846 // Remove the dummy block now that is not needed.
2847 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002848 END_DO_NOT_EMIT_BYTECODE
2849 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002851 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 return 1;
2853 }
2854 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002855 body = compiler_new_block(c);
2856 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002858 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002862 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 }
Mark Shannon266b4622020-11-17 19:30:14 +00002865 if (constant == -1) {
2866 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2867 return 0;
2868 }
2869 }
2870
2871 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002873 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002874
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002875 compiler_pop_fblock(c, WHILE_LOOP, loop);
2876
Mark Shannon266b4622020-11-17 19:30:14 +00002877 compiler_use_next_block(c, anchor);
2878 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002881 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002884}
2885
2886static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002887compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002889 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002890 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002891 if (c->u->u_ste->ste_type != FunctionBlock)
2892 return compiler_error(c, "'return' outside function");
2893 if (s->v.Return.value != NULL &&
2894 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2895 {
2896 return compiler_error(
2897 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002899 if (preserve_tos) {
2900 VISIT(c, expr, s->v.Return.value);
2901 }
Mark Shannonfee55262019-11-21 09:11:43 +00002902 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2903 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002904 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002905 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002906 }
2907 else if (!preserve_tos) {
2908 VISIT(c, expr, s->v.Return.value);
2909 }
2910 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002911 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002914}
2915
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002916static int
2917compiler_break(struct compiler *c)
2918{
Mark Shannonfee55262019-11-21 09:11:43 +00002919 struct fblockinfo *loop = NULL;
2920 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2921 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002922 }
Mark Shannonfee55262019-11-21 09:11:43 +00002923 if (loop == NULL) {
2924 return compiler_error(c, "'break' outside loop");
2925 }
2926 if (!compiler_unwind_fblock(c, loop, 0)) {
2927 return 0;
2928 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002929 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002930 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002931 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002932}
2933
2934static int
2935compiler_continue(struct compiler *c)
2936{
Mark Shannonfee55262019-11-21 09:11:43 +00002937 struct fblockinfo *loop = NULL;
2938 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2939 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002940 }
Mark Shannonfee55262019-11-21 09:11:43 +00002941 if (loop == NULL) {
2942 return compiler_error(c, "'continue' not properly in loop");
2943 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002944 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002945 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002946 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002947}
2948
2949
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002950/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951
2952 SETUP_FINALLY L
2953 <code for body>
2954 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002955 <code for finalbody>
2956 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002957 L:
2958 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002959 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002961 The special instructions use the block stack. Each block
2962 stack entry contains the instruction that created it (here
2963 SETUP_FINALLY), the level of the value stack at the time the
2964 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 Pushes the current value stack level and the label
2968 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002970 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002972 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002973 when a SETUP_FINALLY entry is found, the raised and the caught
2974 exceptions are pushed onto the value stack (and the exception
2975 condition is cleared), and the interpreter jumps to the label
2976 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977*/
2978
2979static int
2980compiler_try_finally(struct compiler *c, stmt_ty s)
2981{
Mark Shannonfee55262019-11-21 09:11:43 +00002982 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002984 body = compiler_new_block(c);
2985 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002986 exit = compiler_new_block(c);
2987 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002989
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002990 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002991 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002993 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002994 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002995 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2996 if (!compiler_try_except(c, s))
2997 return 0;
2998 }
2999 else {
3000 VISIT_SEQ(c, stmt, s->v.Try.body);
3001 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00003003 compiler_pop_fblock(c, FINALLY_TRY, body);
3004 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon582aaf12020-08-04 17:30:11 +01003005 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00003006 /* `finally` block */
3007 compiler_use_next_block(c, end);
3008 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
3009 return 0;
3010 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3011 compiler_pop_fblock(c, FINALLY_END, end);
3012 ADDOP(c, RERAISE);
3013 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003014 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015}
3016
3017/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003018 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003019 (The contents of the value stack is shown in [], with the top
3020 at the right; 'tb' is trace-back info, 'val' the exception's
3021 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022
3023 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003024 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003025 [] <code for S>
3026 [] POP_BLOCK
3027 [] JUMP_FORWARD L0
3028
3029 [tb, val, exc] L1: DUP )
3030 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003031 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 [tb, val, exc] POP
3033 [tb, val] <assign to V1> (or POP if no V1)
3034 [tb] POP
3035 [] <code for S1>
3036 JUMP_FORWARD L0
3037
3038 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003039 .............................etc.......................
3040
Mark Shannonfee55262019-11-21 09:11:43 +00003041 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042
3043 [] L0: <next statement>
3044
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003045 Of course, parts are not generated if Vi or Ei is not present.
3046*/
3047static int
3048compiler_try_except(struct compiler *c, stmt_ty s)
3049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003051 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003053 body = compiler_new_block(c);
3054 except = compiler_new_block(c);
3055 orelse = compiler_new_block(c);
3056 end = compiler_new_block(c);
3057 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3058 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003059 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003061 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003063 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003064 ADDOP(c, POP_BLOCK);
Mark Shannon02d126a2020-09-25 14:04:19 +01003065 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon582aaf12020-08-04 17:30:11 +01003066 ADDOP_JUMP(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003067 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003069 /* Runtime will push a block here, so we need to account for that */
3070 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3071 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 for (i = 0; i < n; i++) {
3073 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003074 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 if (!handler->v.ExceptHandler.type && i < n-1)
3076 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003077 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 except = compiler_new_block(c);
3079 if (except == NULL)
3080 return 0;
3081 if (handler->v.ExceptHandler.type) {
3082 ADDOP(c, DUP_TOP);
3083 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003084 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003085 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 }
3087 ADDOP(c, POP_TOP);
3088 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003090
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003091 cleanup_end = compiler_new_block(c);
3092 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003093 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003094 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003095 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003096
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003097 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3098 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003100 /*
3101 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003102 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003103 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003104 try:
3105 # body
3106 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003107 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003108 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003112 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003113 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003114 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003117 /* second # body */
3118 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003119 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003120 ADDOP(c, POP_BLOCK);
3121 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003122 /* name = None; del name; # Mark as artificial */
3123 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003124 ADDOP_LOAD_CONST(c, Py_None);
3125 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3126 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003127 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128
Mark Shannonfee55262019-11-21 09:11:43 +00003129 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003130 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131
Mark Shannon877df852020-11-12 09:43:29 +00003132 /* name = None; del name; # Mark as artificial */
3133 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003134 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003135 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003136 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003137
Mark Shannonfee55262019-11-21 09:11:43 +00003138 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 }
3140 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003141 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003143 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003144 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003145 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146
Guido van Rossumb940e112007-01-10 16:19:56 +00003147 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003148 ADDOP(c, POP_TOP);
3149 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003150 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003151 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003153 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003154 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003155 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 compiler_use_next_block(c, except);
3158 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003159 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonfee55262019-11-21 09:11:43 +00003160 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003162 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003163 compiler_use_next_block(c, end);
3164 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003165}
3166
3167static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003168compiler_try(struct compiler *c, stmt_ty s) {
3169 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3170 return compiler_try_finally(c, s);
3171 else
3172 return compiler_try_except(c, s);
3173}
3174
3175
3176static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003177compiler_import_as(struct compiler *c, identifier name, identifier asname)
3178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003179 /* The IMPORT_NAME opcode was already generated. This function
3180 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003182 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003183 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003185 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3186 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003187 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003188 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003189 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003191 while (1) {
3192 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003194 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003195 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003196 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003197 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003199 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003200 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003201 if (dot == -1) {
3202 break;
3203 }
3204 ADDOP(c, ROT_TWO);
3205 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003207 if (!compiler_nameop(c, asname, Store)) {
3208 return 0;
3209 }
3210 ADDOP(c, POP_TOP);
3211 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 }
3213 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214}
3215
3216static int
3217compiler_import(struct compiler *c, stmt_ty s)
3218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003219 /* The Import node stores a module name like a.b.c as a single
3220 string. This is convenient for all cases except
3221 import a.b.c as d
3222 where we need to parse that string to extract the individual
3223 module names.
3224 XXX Perhaps change the representation to make this case simpler?
3225 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003226 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003227
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003228 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 for (i = 0; i < n; i++) {
3230 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3231 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003232
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003233 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003234 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003235 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 if (alias->asname) {
3238 r = compiler_import_as(c, alias->name, alias->asname);
3239 if (!r)
3240 return r;
3241 }
3242 else {
3243 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003244 Py_ssize_t dot = PyUnicode_FindChar(
3245 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003246 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003247 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003248 if (tmp == NULL)
3249 return 0;
3250 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003251 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003252 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003253 Py_DECREF(tmp);
3254 }
3255 if (!r)
3256 return r;
3257 }
3258 }
3259 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003260}
3261
3262static int
3263compiler_from_import(struct compiler *c, stmt_ty s)
3264{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003265 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003266 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 if (!empty_string) {
3270 empty_string = PyUnicode_FromString("");
3271 if (!empty_string)
3272 return 0;
3273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003274
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003275 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003276
3277 names = PyTuple_New(n);
3278 if (!names)
3279 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 /* build up the names */
3282 for (i = 0; i < n; i++) {
3283 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3284 Py_INCREF(alias->name);
3285 PyTuple_SET_ITEM(names, i, alias->name);
3286 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003289 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 Py_DECREF(names);
3291 return compiler_error(c, "from __future__ imports must occur "
3292 "at the beginning of the file");
3293 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003294 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 if (s->v.ImportFrom.module) {
3297 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3298 }
3299 else {
3300 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3301 }
3302 for (i = 0; i < n; i++) {
3303 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3304 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003306 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 assert(n == 1);
3308 ADDOP(c, IMPORT_STAR);
3309 return 1;
3310 }
3311
3312 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3313 store_name = alias->name;
3314 if (alias->asname)
3315 store_name = alias->asname;
3316
3317 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 return 0;
3319 }
3320 }
3321 /* remove imported module */
3322 ADDOP(c, POP_TOP);
3323 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003324}
3325
3326static int
3327compiler_assert(struct compiler *c, stmt_ty s)
3328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003330
Georg Brandl8334fd92010-12-04 10:26:46 +00003331 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003332 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003334 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3335 {
3336 if (!compiler_warn(c, "assertion is always true, "
3337 "perhaps remove parentheses?"))
3338 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003339 return 0;
3340 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003342 end = compiler_new_block(c);
3343 if (end == NULL)
3344 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003345 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3346 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003347 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003348 if (s->v.Assert.msg) {
3349 VISIT(c, expr, s->v.Assert.msg);
3350 ADDOP_I(c, CALL_FUNCTION, 1);
3351 }
3352 ADDOP_I(c, RAISE_VARARGS, 1);
3353 compiler_use_next_block(c, end);
3354 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003355}
3356
3357static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003358compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3359{
3360 if (c->c_interactive && c->c_nestlevel <= 1) {
3361 VISIT(c, expr, value);
3362 ADDOP(c, PRINT_EXPR);
3363 return 1;
3364 }
3365
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003366 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003367 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003368 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003369 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003370 }
3371
3372 VISIT(c, expr, value);
3373 ADDOP(c, POP_TOP);
3374 return 1;
3375}
3376
3377static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003378compiler_visit_stmt(struct compiler *c, stmt_ty s)
3379{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003380 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003382 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003383 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003385 switch (s->kind) {
3386 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003387 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003388 case ClassDef_kind:
3389 return compiler_class(c, s);
3390 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003391 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 case Delete_kind:
3393 VISIT_SEQ(c, expr, s->v.Delete.targets)
3394 break;
3395 case Assign_kind:
3396 n = asdl_seq_LEN(s->v.Assign.targets);
3397 VISIT(c, expr, s->v.Assign.value);
3398 for (i = 0; i < n; i++) {
3399 if (i < n - 1)
3400 ADDOP(c, DUP_TOP);
3401 VISIT(c, expr,
3402 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3403 }
3404 break;
3405 case AugAssign_kind:
3406 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003407 case AnnAssign_kind:
3408 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003409 case For_kind:
3410 return compiler_for(c, s);
3411 case While_kind:
3412 return compiler_while(c, s);
3413 case If_kind:
3414 return compiler_if(c, s);
3415 case Raise_kind:
3416 n = 0;
3417 if (s->v.Raise.exc) {
3418 VISIT(c, expr, s->v.Raise.exc);
3419 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003420 if (s->v.Raise.cause) {
3421 VISIT(c, expr, s->v.Raise.cause);
3422 n++;
3423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003425 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003426 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003427 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003428 case Try_kind:
3429 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 case Assert_kind:
3431 return compiler_assert(c, s);
3432 case Import_kind:
3433 return compiler_import(c, s);
3434 case ImportFrom_kind:
3435 return compiler_from_import(c, s);
3436 case Global_kind:
3437 case Nonlocal_kind:
3438 break;
3439 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003440 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003441 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003442 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003443 break;
3444 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003445 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 case Continue_kind:
3447 return compiler_continue(c);
3448 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003449 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003450 case AsyncFunctionDef_kind:
3451 return compiler_function(c, s, 1);
3452 case AsyncWith_kind:
3453 return compiler_async_with(c, s, 0);
3454 case AsyncFor_kind:
3455 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003456 }
Yury Selivanov75445082015-05-11 22:57:16 -04003457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003458 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003459}
3460
3461static int
3462unaryop(unaryop_ty op)
3463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 switch (op) {
3465 case Invert:
3466 return UNARY_INVERT;
3467 case Not:
3468 return UNARY_NOT;
3469 case UAdd:
3470 return UNARY_POSITIVE;
3471 case USub:
3472 return UNARY_NEGATIVE;
3473 default:
3474 PyErr_Format(PyExc_SystemError,
3475 "unary op %d should not be possible", op);
3476 return 0;
3477 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003478}
3479
3480static int
Andy Lester76d58772020-03-10 21:18:12 -05003481binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003483 switch (op) {
3484 case Add:
3485 return BINARY_ADD;
3486 case Sub:
3487 return BINARY_SUBTRACT;
3488 case Mult:
3489 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003490 case MatMult:
3491 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003492 case Div:
3493 return BINARY_TRUE_DIVIDE;
3494 case Mod:
3495 return BINARY_MODULO;
3496 case Pow:
3497 return BINARY_POWER;
3498 case LShift:
3499 return BINARY_LSHIFT;
3500 case RShift:
3501 return BINARY_RSHIFT;
3502 case BitOr:
3503 return BINARY_OR;
3504 case BitXor:
3505 return BINARY_XOR;
3506 case BitAnd:
3507 return BINARY_AND;
3508 case FloorDiv:
3509 return BINARY_FLOOR_DIVIDE;
3510 default:
3511 PyErr_Format(PyExc_SystemError,
3512 "binary op %d should not be possible", op);
3513 return 0;
3514 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003515}
3516
3517static int
Andy Lester76d58772020-03-10 21:18:12 -05003518inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003520 switch (op) {
3521 case Add:
3522 return INPLACE_ADD;
3523 case Sub:
3524 return INPLACE_SUBTRACT;
3525 case Mult:
3526 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003527 case MatMult:
3528 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003529 case Div:
3530 return INPLACE_TRUE_DIVIDE;
3531 case Mod:
3532 return INPLACE_MODULO;
3533 case Pow:
3534 return INPLACE_POWER;
3535 case LShift:
3536 return INPLACE_LSHIFT;
3537 case RShift:
3538 return INPLACE_RSHIFT;
3539 case BitOr:
3540 return INPLACE_OR;
3541 case BitXor:
3542 return INPLACE_XOR;
3543 case BitAnd:
3544 return INPLACE_AND;
3545 case FloorDiv:
3546 return INPLACE_FLOOR_DIVIDE;
3547 default:
3548 PyErr_Format(PyExc_SystemError,
3549 "inplace binary op %d should not be possible", op);
3550 return 0;
3551 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003552}
3553
3554static int
3555compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3556{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003557 int op, scope;
3558 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003559 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003561 PyObject *dict = c->u->u_names;
3562 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003564 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3565 !_PyUnicode_EqualToASCIIString(name, "True") &&
3566 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003567
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003568 if (forbidden_name(c, name, ctx))
3569 return 0;
3570
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003571 mangled = _Py_Mangle(c->u->u_private, name);
3572 if (!mangled)
3573 return 0;
3574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003575 op = 0;
3576 optype = OP_NAME;
3577 scope = PyST_GetScope(c->u->u_ste, mangled);
3578 switch (scope) {
3579 case FREE:
3580 dict = c->u->u_freevars;
3581 optype = OP_DEREF;
3582 break;
3583 case CELL:
3584 dict = c->u->u_cellvars;
3585 optype = OP_DEREF;
3586 break;
3587 case LOCAL:
3588 if (c->u->u_ste->ste_type == FunctionBlock)
3589 optype = OP_FAST;
3590 break;
3591 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003592 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003593 optype = OP_GLOBAL;
3594 break;
3595 case GLOBAL_EXPLICIT:
3596 optype = OP_GLOBAL;
3597 break;
3598 default:
3599 /* scope can be 0 */
3600 break;
3601 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003603 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003604 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 switch (optype) {
3607 case OP_DEREF:
3608 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003609 case Load:
3610 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3611 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003612 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003613 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 }
3615 break;
3616 case OP_FAST:
3617 switch (ctx) {
3618 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003619 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003621 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003622 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 return 1;
3624 case OP_GLOBAL:
3625 switch (ctx) {
3626 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003627 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 }
3630 break;
3631 case OP_NAME:
3632 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003633 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003634 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003635 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 }
3637 break;
3638 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003640 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003641 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003642 Py_DECREF(mangled);
3643 if (arg < 0)
3644 return 0;
3645 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003646}
3647
3648static int
3649compiler_boolop(struct compiler *c, expr_ty e)
3650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003651 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003652 int jumpi;
3653 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003654 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003656 assert(e->kind == BoolOp_kind);
3657 if (e->v.BoolOp.op == And)
3658 jumpi = JUMP_IF_FALSE_OR_POP;
3659 else
3660 jumpi = JUMP_IF_TRUE_OR_POP;
3661 end = compiler_new_block(c);
3662 if (end == NULL)
3663 return 0;
3664 s = e->v.BoolOp.values;
3665 n = asdl_seq_LEN(s) - 1;
3666 assert(n >= 0);
3667 for (i = 0; i < n; ++i) {
3668 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003669 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003670 basicblock *next = compiler_new_block(c);
3671 if (next == NULL) {
3672 return 0;
3673 }
3674 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003675 }
3676 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3677 compiler_use_next_block(c, end);
3678 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003679}
3680
3681static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003682starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003683 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003684{
3685 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003686 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003687 if (n > 2 && are_all_items_const(elts, 0, n)) {
3688 PyObject *folded = PyTuple_New(n);
3689 if (folded == NULL) {
3690 return 0;
3691 }
3692 PyObject *val;
3693 for (i = 0; i < n; i++) {
3694 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3695 Py_INCREF(val);
3696 PyTuple_SET_ITEM(folded, i, val);
3697 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003698 if (tuple) {
3699 ADDOP_LOAD_CONST_NEW(c, folded);
3700 } else {
3701 if (add == SET_ADD) {
3702 Py_SETREF(folded, PyFrozenSet_New(folded));
3703 if (folded == NULL) {
3704 return 0;
3705 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003706 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003707 ADDOP_I(c, build, pushed);
3708 ADDOP_LOAD_CONST_NEW(c, folded);
3709 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003710 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003711 return 1;
3712 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003713
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003714 for (i = 0; i < n; i++) {
3715 expr_ty elt = asdl_seq_GET(elts, i);
3716 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003717 seen_star = 1;
3718 }
3719 }
3720 if (seen_star) {
3721 seen_star = 0;
3722 for (i = 0; i < n; i++) {
3723 expr_ty elt = asdl_seq_GET(elts, i);
3724 if (elt->kind == Starred_kind) {
3725 if (seen_star == 0) {
3726 ADDOP_I(c, build, i+pushed);
3727 seen_star = 1;
3728 }
3729 VISIT(c, expr, elt->v.Starred.value);
3730 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003731 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003732 else {
3733 VISIT(c, expr, elt);
3734 if (seen_star) {
3735 ADDOP_I(c, add, 1);
3736 }
3737 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003738 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003739 assert(seen_star);
3740 if (tuple) {
3741 ADDOP(c, LIST_TO_TUPLE);
3742 }
3743 }
3744 else {
3745 for (i = 0; i < n; i++) {
3746 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003747 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003748 }
3749 if (tuple) {
3750 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3751 } else {
3752 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003753 }
3754 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003755 return 1;
3756}
3757
3758static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003759assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003760{
3761 Py_ssize_t n = asdl_seq_LEN(elts);
3762 Py_ssize_t i;
3763 int seen_star = 0;
3764 for (i = 0; i < n; i++) {
3765 expr_ty elt = asdl_seq_GET(elts, i);
3766 if (elt->kind == Starred_kind && !seen_star) {
3767 if ((i >= (1 << 8)) ||
3768 (n-i-1 >= (INT_MAX >> 8)))
3769 return compiler_error(c,
3770 "too many expressions in "
3771 "star-unpacking assignment");
3772 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3773 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003774 }
3775 else if (elt->kind == Starred_kind) {
3776 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003777 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003778 }
3779 }
3780 if (!seen_star) {
3781 ADDOP_I(c, UNPACK_SEQUENCE, n);
3782 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003783 for (i = 0; i < n; i++) {
3784 expr_ty elt = asdl_seq_GET(elts, i);
3785 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3786 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003787 return 1;
3788}
3789
3790static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003791compiler_list(struct compiler *c, expr_ty e)
3792{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003793 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003794 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003796 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003797 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003798 return starunpack_helper(c, elts, 0, BUILD_LIST,
3799 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003800 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003801 else
3802 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003804}
3805
3806static int
3807compiler_tuple(struct compiler *c, expr_ty e)
3808{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003809 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003810 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003811 return assignment_helper(c, elts);
3812 }
3813 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003814 return starunpack_helper(c, elts, 0, BUILD_LIST,
3815 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003816 }
3817 else
3818 VISIT_SEQ(c, expr, elts);
3819 return 1;
3820}
3821
3822static int
3823compiler_set(struct compiler *c, expr_ty e)
3824{
Mark Shannon13bc1392020-01-23 09:25:17 +00003825 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3826 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003827}
3828
3829static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003830are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003831{
3832 Py_ssize_t i;
3833 for (i = begin; i < end; i++) {
3834 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003835 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003836 return 0;
3837 }
3838 return 1;
3839}
3840
3841static int
3842compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3843{
3844 Py_ssize_t i, n = end - begin;
3845 PyObject *keys, *key;
3846 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3847 for (i = begin; i < end; i++) {
3848 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3849 }
3850 keys = PyTuple_New(n);
3851 if (keys == NULL) {
3852 return 0;
3853 }
3854 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003855 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003856 Py_INCREF(key);
3857 PyTuple_SET_ITEM(keys, i - begin, key);
3858 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003859 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003860 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3861 }
3862 else {
3863 for (i = begin; i < end; i++) {
3864 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3865 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3866 }
3867 ADDOP_I(c, BUILD_MAP, n);
3868 }
3869 return 1;
3870}
3871
3872static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003873compiler_dict(struct compiler *c, expr_ty e)
3874{
Victor Stinner976bb402016-03-23 11:36:19 +01003875 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003876 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003877 int is_unpacking = 0;
3878 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003879 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003880 elements = 0;
3881 for (i = 0; i < n; i++) {
3882 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003883 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003884 if (elements) {
3885 if (!compiler_subdict(c, e, i - elements, i)) {
3886 return 0;
3887 }
3888 if (have_dict) {
3889 ADDOP_I(c, DICT_UPDATE, 1);
3890 }
3891 have_dict = 1;
3892 elements = 0;
3893 }
3894 if (have_dict == 0) {
3895 ADDOP_I(c, BUILD_MAP, 0);
3896 have_dict = 1;
3897 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003898 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003899 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003900 }
3901 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003902 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003903 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003904 return 0;
3905 }
3906 if (have_dict) {
3907 ADDOP_I(c, DICT_UPDATE, 1);
3908 }
3909 have_dict = 1;
3910 elements = 0;
3911 }
3912 else {
3913 elements++;
3914 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003915 }
3916 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003917 if (elements) {
3918 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003919 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003920 }
3921 if (have_dict) {
3922 ADDOP_I(c, DICT_UPDATE, 1);
3923 }
3924 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003925 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003926 if (!have_dict) {
3927 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 }
3929 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003930}
3931
3932static int
3933compiler_compare(struct compiler *c, expr_ty e)
3934{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003935 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003936
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003937 if (!check_compare(c, e)) {
3938 return 0;
3939 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003941 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3942 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3943 if (n == 0) {
3944 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003945 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003946 }
3947 else {
3948 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003949 if (cleanup == NULL)
3950 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003951 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 VISIT(c, expr,
3953 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003954 ADDOP(c, DUP_TOP);
3955 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003956 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003957 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003958 NEXT_BLOCK(c);
3959 }
3960 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003961 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003962 basicblock *end = compiler_new_block(c);
3963 if (end == NULL)
3964 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003965 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003966 compiler_use_next_block(c, cleanup);
3967 ADDOP(c, ROT_TWO);
3968 ADDOP(c, POP_TOP);
3969 compiler_use_next_block(c, end);
3970 }
3971 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003972}
3973
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003974static PyTypeObject *
3975infer_type(expr_ty e)
3976{
3977 switch (e->kind) {
3978 case Tuple_kind:
3979 return &PyTuple_Type;
3980 case List_kind:
3981 case ListComp_kind:
3982 return &PyList_Type;
3983 case Dict_kind:
3984 case DictComp_kind:
3985 return &PyDict_Type;
3986 case Set_kind:
3987 case SetComp_kind:
3988 return &PySet_Type;
3989 case GeneratorExp_kind:
3990 return &PyGen_Type;
3991 case Lambda_kind:
3992 return &PyFunction_Type;
3993 case JoinedStr_kind:
3994 case FormattedValue_kind:
3995 return &PyUnicode_Type;
3996 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003997 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003998 default:
3999 return NULL;
4000 }
4001}
4002
4003static int
4004check_caller(struct compiler *c, expr_ty e)
4005{
4006 switch (e->kind) {
4007 case Constant_kind:
4008 case Tuple_kind:
4009 case List_kind:
4010 case ListComp_kind:
4011 case Dict_kind:
4012 case DictComp_kind:
4013 case Set_kind:
4014 case SetComp_kind:
4015 case GeneratorExp_kind:
4016 case JoinedStr_kind:
4017 case FormattedValue_kind:
4018 return compiler_warn(c, "'%.200s' object is not callable; "
4019 "perhaps you missed a comma?",
4020 infer_type(e)->tp_name);
4021 default:
4022 return 1;
4023 }
4024}
4025
4026static int
4027check_subscripter(struct compiler *c, expr_ty e)
4028{
4029 PyObject *v;
4030
4031 switch (e->kind) {
4032 case Constant_kind:
4033 v = e->v.Constant.value;
4034 if (!(v == Py_None || v == Py_Ellipsis ||
4035 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4036 PyAnySet_Check(v)))
4037 {
4038 return 1;
4039 }
4040 /* fall through */
4041 case Set_kind:
4042 case SetComp_kind:
4043 case GeneratorExp_kind:
4044 case Lambda_kind:
4045 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4046 "perhaps you missed a comma?",
4047 infer_type(e)->tp_name);
4048 default:
4049 return 1;
4050 }
4051}
4052
4053static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004054check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004055{
4056 PyObject *v;
4057
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004058 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004059 if (index_type == NULL
4060 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4061 || index_type == &PySlice_Type) {
4062 return 1;
4063 }
4064
4065 switch (e->kind) {
4066 case Constant_kind:
4067 v = e->v.Constant.value;
4068 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4069 return 1;
4070 }
4071 /* fall through */
4072 case Tuple_kind:
4073 case List_kind:
4074 case ListComp_kind:
4075 case JoinedStr_kind:
4076 case FormattedValue_kind:
4077 return compiler_warn(c, "%.200s indices must be integers or slices, "
4078 "not %.200s; "
4079 "perhaps you missed a comma?",
4080 infer_type(e)->tp_name,
4081 index_type->tp_name);
4082 default:
4083 return 1;
4084 }
4085}
4086
Zackery Spytz97f5de02019-03-22 01:30:32 -06004087// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004088static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004089maybe_optimize_method_call(struct compiler *c, expr_ty e)
4090{
4091 Py_ssize_t argsl, i;
4092 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004093 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004094
4095 /* Check that the call node is an attribute access, and that
4096 the call doesn't have keyword parameters. */
4097 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4098 asdl_seq_LEN(e->v.Call.keywords))
4099 return -1;
4100
4101 /* Check that there are no *varargs types of arguments. */
4102 argsl = asdl_seq_LEN(args);
4103 for (i = 0; i < argsl; i++) {
4104 expr_ty elt = asdl_seq_GET(args, i);
4105 if (elt->kind == Starred_kind) {
4106 return -1;
4107 }
4108 }
4109
4110 /* Alright, we can optimize the code. */
4111 VISIT(c, expr, meth->v.Attribute.value);
4112 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4113 VISIT_SEQ(c, expr, e->v.Call.args);
4114 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4115 return 1;
4116}
4117
4118static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004119validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004120{
4121 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4122 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004123 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4124 if (key->arg == NULL) {
4125 continue;
4126 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004127 if (forbidden_name(c, key->arg, Store)) {
4128 return -1;
4129 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004130 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004131 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4132 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4133 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4134 if (msg == NULL) {
4135 return -1;
4136 }
4137 c->u->u_col_offset = other->col_offset;
4138 compiler_error(c, PyUnicode_AsUTF8(msg));
4139 Py_DECREF(msg);
4140 return -1;
4141 }
4142 }
4143 }
4144 return 0;
4145}
4146
4147static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004148compiler_call(struct compiler *c, expr_ty e)
4149{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004150 int ret = maybe_optimize_method_call(c, e);
4151 if (ret >= 0) {
4152 return ret;
4153 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004154 if (!check_caller(c, e->v.Call.func)) {
4155 return 0;
4156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004157 VISIT(c, expr, e->v.Call.func);
4158 return compiler_call_helper(c, 0,
4159 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004160 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004161}
4162
Eric V. Smith235a6f02015-09-19 14:51:32 -04004163static int
4164compiler_joined_str(struct compiler *c, expr_ty e)
4165{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004166 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004167 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4168 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004169 return 1;
4170}
4171
Eric V. Smitha78c7952015-11-03 12:45:05 -05004172/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004173static int
4174compiler_formatted_value(struct compiler *c, expr_ty e)
4175{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004176 /* Our oparg encodes 2 pieces of information: the conversion
4177 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004178
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004179 Convert the conversion char to 3 bits:
4180 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004181 !s : 001 0x1 FVC_STR
4182 !r : 010 0x2 FVC_REPR
4183 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004184
Eric V. Smitha78c7952015-11-03 12:45:05 -05004185 next bit is whether or not we have a format spec:
4186 yes : 100 0x4
4187 no : 000 0x0
4188 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004189
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004190 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004191 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004192
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004193 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004194 VISIT(c, expr, e->v.FormattedValue.value);
4195
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004196 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004197 case 's': oparg = FVC_STR; break;
4198 case 'r': oparg = FVC_REPR; break;
4199 case 'a': oparg = FVC_ASCII; break;
4200 case -1: oparg = FVC_NONE; break;
4201 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004202 PyErr_Format(PyExc_SystemError,
4203 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004204 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004205 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004206 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004207 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004208 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004209 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004210 }
4211
Eric V. Smitha78c7952015-11-03 12:45:05 -05004212 /* And push our opcode and oparg */
4213 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004214
Eric V. Smith235a6f02015-09-19 14:51:32 -04004215 return 1;
4216}
4217
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004218static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004219compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004220{
4221 Py_ssize_t i, n = end - begin;
4222 keyword_ty kw;
4223 PyObject *keys, *key;
4224 assert(n > 0);
4225 if (n > 1) {
4226 for (i = begin; i < end; i++) {
4227 kw = asdl_seq_GET(keywords, i);
4228 VISIT(c, expr, kw->value);
4229 }
4230 keys = PyTuple_New(n);
4231 if (keys == NULL) {
4232 return 0;
4233 }
4234 for (i = begin; i < end; i++) {
4235 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4236 Py_INCREF(key);
4237 PyTuple_SET_ITEM(keys, i - begin, key);
4238 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004239 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004240 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4241 }
4242 else {
4243 /* a for loop only executes once */
4244 for (i = begin; i < end; i++) {
4245 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004246 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004247 VISIT(c, expr, kw->value);
4248 }
4249 ADDOP_I(c, BUILD_MAP, n);
4250 }
4251 return 1;
4252}
4253
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004254/* shared code between compiler_call and compiler_class */
4255static int
4256compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004257 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004258 asdl_expr_seq *args,
4259 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004260{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004261 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004262
Pablo Galindo254ec782020-04-03 20:37:13 +01004263 if (validate_keywords(c, keywords) == -1) {
4264 return 0;
4265 }
4266
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004267 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004268 nkwelts = asdl_seq_LEN(keywords);
4269
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004270 for (i = 0; i < nelts; i++) {
4271 expr_ty elt = asdl_seq_GET(args, i);
4272 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004273 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004274 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004275 }
4276 for (i = 0; i < nkwelts; i++) {
4277 keyword_ty kw = asdl_seq_GET(keywords, i);
4278 if (kw->arg == NULL) {
4279 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004281 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004282
Mark Shannon13bc1392020-01-23 09:25:17 +00004283 /* No * or ** args, so can use faster calling sequence */
4284 for (i = 0; i < nelts; i++) {
4285 expr_ty elt = asdl_seq_GET(args, i);
4286 assert(elt->kind != Starred_kind);
4287 VISIT(c, expr, elt);
4288 }
4289 if (nkwelts) {
4290 PyObject *names;
4291 VISIT_SEQ(c, keyword, keywords);
4292 names = PyTuple_New(nkwelts);
4293 if (names == NULL) {
4294 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004295 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004296 for (i = 0; i < nkwelts; i++) {
4297 keyword_ty kw = asdl_seq_GET(keywords, i);
4298 Py_INCREF(kw->arg);
4299 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004300 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004301 ADDOP_LOAD_CONST_NEW(c, names);
4302 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4303 return 1;
4304 }
4305 else {
4306 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4307 return 1;
4308 }
4309
4310ex_call:
4311
4312 /* Do positional arguments. */
4313 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4314 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4315 }
4316 else if (starunpack_helper(c, args, n, BUILD_LIST,
4317 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4318 return 0;
4319 }
4320 /* Then keyword arguments */
4321 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004322 /* Has a new dict been pushed */
4323 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004324
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004325 nseen = 0; /* the number of keyword arguments on the stack following */
4326 for (i = 0; i < nkwelts; i++) {
4327 keyword_ty kw = asdl_seq_GET(keywords, i);
4328 if (kw->arg == NULL) {
4329 /* A keyword argument unpacking. */
4330 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004331 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004332 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004333 }
Mark Shannondb64f122020-06-01 10:42:42 +01004334 if (have_dict) {
4335 ADDOP_I(c, DICT_MERGE, 1);
4336 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004337 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004338 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004339 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004340 if (!have_dict) {
4341 ADDOP_I(c, BUILD_MAP, 0);
4342 have_dict = 1;
4343 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004344 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004345 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004346 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004347 else {
4348 nseen++;
4349 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004350 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004351 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004352 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004353 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004354 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004355 }
4356 if (have_dict) {
4357 ADDOP_I(c, DICT_MERGE, 1);
4358 }
4359 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004360 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004361 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004362 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004363 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4364 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365}
4366
Nick Coghlan650f0d02007-04-15 12:05:43 +00004367
4368/* List and set comprehensions and generator expressions work by creating a
4369 nested function to perform the actual iteration. This means that the
4370 iteration variables don't leak into the current scope.
4371 The defined function is called immediately following its definition, with the
4372 result of that call being the result of the expression.
4373 The LC/SC version returns the populated container, while the GE version is
4374 flagged in symtable.c as a generator, so it returns the generator object
4375 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004376
4377 Possible cleanups:
4378 - iterate over the generator sequence instead of using recursion
4379*/
4380
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004381
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004382static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004384 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004385 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004387{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004388 comprehension_ty gen;
4389 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4390 if (gen->is_async) {
4391 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004392 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004393 } else {
4394 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004395 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004396 }
4397}
4398
4399static int
4400compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004401 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004402 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004403 expr_ty elt, expr_ty val, int type)
4404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004405 /* generate code for the iterator, then each of the ifs,
4406 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 comprehension_ty gen;
4409 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004410 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004412 start = compiler_new_block(c);
4413 skip = compiler_new_block(c);
4414 if_cleanup = compiler_new_block(c);
4415 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4418 anchor == NULL)
4419 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004421 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004423 if (gen_index == 0) {
4424 /* Receive outermost iter as an implicit argument */
4425 c->u->u_argcount = 1;
4426 ADDOP_I(c, LOAD_FAST, 0);
4427 }
4428 else {
4429 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004430 /* Fast path for the temporary variable assignment idiom:
4431 for y in [f(x)]
4432 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004433 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004434 switch (gen->iter->kind) {
4435 case List_kind:
4436 elts = gen->iter->v.List.elts;
4437 break;
4438 case Tuple_kind:
4439 elts = gen->iter->v.Tuple.elts;
4440 break;
4441 default:
4442 elts = NULL;
4443 }
4444 if (asdl_seq_LEN(elts) == 1) {
4445 expr_ty elt = asdl_seq_GET(elts, 0);
4446 if (elt->kind != Starred_kind) {
4447 VISIT(c, expr, elt);
4448 start = NULL;
4449 }
4450 }
4451 if (start) {
4452 VISIT(c, expr, gen->iter);
4453 ADDOP(c, GET_ITER);
4454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004455 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004456 if (start) {
4457 depth++;
4458 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004459 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004460 NEXT_BLOCK(c);
4461 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004462 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 /* XXX this needs to be cleaned up...a lot! */
4465 n = asdl_seq_LEN(gen->ifs);
4466 for (i = 0; i < n; i++) {
4467 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004468 if (!compiler_jump_if(c, e, if_cleanup, 0))
4469 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 NEXT_BLOCK(c);
4471 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 if (++gen_index < asdl_seq_LEN(generators))
4474 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004475 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 elt, val, type))
4477 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 /* only append after the last for generator */
4480 if (gen_index >= asdl_seq_LEN(generators)) {
4481 /* comprehension specific code */
4482 switch (type) {
4483 case COMP_GENEXP:
4484 VISIT(c, expr, elt);
4485 ADDOP(c, YIELD_VALUE);
4486 ADDOP(c, POP_TOP);
4487 break;
4488 case COMP_LISTCOMP:
4489 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004490 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004491 break;
4492 case COMP_SETCOMP:
4493 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004494 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004495 break;
4496 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004497 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004500 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004501 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 break;
4503 default:
4504 return 0;
4505 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 compiler_use_next_block(c, skip);
4508 }
4509 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004510 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004511 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004512 compiler_use_next_block(c, anchor);
4513 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004514
4515 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004516}
4517
4518static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004519compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004520 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004521 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004522 expr_ty elt, expr_ty val, int type)
4523{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004525 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004526 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004527 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004531 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004532 return 0;
4533 }
4534
4535 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4536
4537 if (gen_index == 0) {
4538 /* Receive outermost iter as an implicit argument */
4539 c->u->u_argcount = 1;
4540 ADDOP_I(c, LOAD_FAST, 0);
4541 }
4542 else {
4543 /* Sub-iter - calculate on the fly */
4544 VISIT(c, expr, gen->iter);
4545 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546 }
4547
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004548 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004549
Mark Shannon582aaf12020-08-04 17:30:11 +01004550 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004551 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004552 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004555 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004556
4557 n = asdl_seq_LEN(gen->ifs);
4558 for (i = 0; i < n; i++) {
4559 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004560 if (!compiler_jump_if(c, e, if_cleanup, 0))
4561 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004562 NEXT_BLOCK(c);
4563 }
4564
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004565 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004566 if (++gen_index < asdl_seq_LEN(generators))
4567 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004568 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004569 elt, val, type))
4570 return 0;
4571
4572 /* only append after the last for generator */
4573 if (gen_index >= asdl_seq_LEN(generators)) {
4574 /* comprehension specific code */
4575 switch (type) {
4576 case COMP_GENEXP:
4577 VISIT(c, expr, elt);
4578 ADDOP(c, YIELD_VALUE);
4579 ADDOP(c, POP_TOP);
4580 break;
4581 case COMP_LISTCOMP:
4582 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004583 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004584 break;
4585 case COMP_SETCOMP:
4586 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004587 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004588 break;
4589 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004590 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004591 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004592 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004593 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004594 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004595 break;
4596 default:
4597 return 0;
4598 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004599 }
4600 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004601 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004602
4603 compiler_use_next_block(c, except);
4604 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004605
4606 return 1;
4607}
4608
4609static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004610compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004611 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004612 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004614 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004615 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004616 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004617 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004618 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004619
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004620
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004621 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004622
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004623 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004624 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4625 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004626 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004627 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004628 }
4629
4630 is_async_generator = c->u->u_ste->ste_coroutine;
4631
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004632 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004633 compiler_error(c, "asynchronous comprehension outside of "
4634 "an asynchronous function");
4635 goto error_in_scope;
4636 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 if (type != COMP_GENEXP) {
4639 int op;
4640 switch (type) {
4641 case COMP_LISTCOMP:
4642 op = BUILD_LIST;
4643 break;
4644 case COMP_SETCOMP:
4645 op = BUILD_SET;
4646 break;
4647 case COMP_DICTCOMP:
4648 op = BUILD_MAP;
4649 break;
4650 default:
4651 PyErr_Format(PyExc_SystemError,
4652 "unknown comprehension type %d", type);
4653 goto error_in_scope;
4654 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 ADDOP_I(c, op, 0);
4657 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004658
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004659 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 val, type))
4661 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 if (type != COMP_GENEXP) {
4664 ADDOP(c, RETURN_VALUE);
4665 }
4666
4667 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004668 qualname = c->u->u_qualname;
4669 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004670 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004671 if (top_level_await && is_async_generator){
4672 c->u->u_ste->ste_coroutine = 1;
4673 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004674 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 goto error;
4676
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004677 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004679 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004680 Py_DECREF(co);
4681
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004682 VISIT(c, expr, outermost->iter);
4683
4684 if (outermost->is_async) {
4685 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004686 } else {
4687 ADDOP(c, GET_ITER);
4688 }
4689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004691
4692 if (is_async_generator && type != COMP_GENEXP) {
4693 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004694 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004695 ADDOP(c, YIELD_FROM);
4696 }
4697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004699error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004700 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004701error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004702 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 Py_XDECREF(co);
4704 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004705}
4706
4707static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004708compiler_genexp(struct compiler *c, expr_ty e)
4709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004710 static identifier name;
4711 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004712 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 if (!name)
4714 return 0;
4715 }
4716 assert(e->kind == GeneratorExp_kind);
4717 return compiler_comprehension(c, e, COMP_GENEXP, name,
4718 e->v.GeneratorExp.generators,
4719 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004720}
4721
4722static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004723compiler_listcomp(struct compiler *c, expr_ty e)
4724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004725 static identifier name;
4726 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004727 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 if (!name)
4729 return 0;
4730 }
4731 assert(e->kind == ListComp_kind);
4732 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4733 e->v.ListComp.generators,
4734 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004735}
4736
4737static int
4738compiler_setcomp(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("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 if (!name)
4744 return 0;
4745 }
4746 assert(e->kind == SetComp_kind);
4747 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4748 e->v.SetComp.generators,
4749 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004750}
4751
4752
4753static int
4754compiler_dictcomp(struct compiler *c, expr_ty e)
4755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004756 static identifier name;
4757 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004758 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 if (!name)
4760 return 0;
4761 }
4762 assert(e->kind == DictComp_kind);
4763 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4764 e->v.DictComp.generators,
4765 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004766}
4767
4768
4769static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004770compiler_visit_keyword(struct compiler *c, keyword_ty k)
4771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004772 VISIT(c, expr, k->value);
4773 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004774}
4775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004776/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004777 whether they are true or false.
4778
4779 Return values: 1 for true, 0 for false, -1 for non-constant.
4780 */
4781
4782static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004783expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004784{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004785 if (e->kind == Constant_kind) {
4786 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004787 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004788 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004789}
4790
Mark Shannonfee55262019-11-21 09:11:43 +00004791static int
4792compiler_with_except_finish(struct compiler *c) {
4793 basicblock *exit;
4794 exit = compiler_new_block(c);
4795 if (exit == NULL)
4796 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004797 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004798 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004799 ADDOP(c, RERAISE);
4800 compiler_use_next_block(c, exit);
4801 ADDOP(c, POP_TOP);
4802 ADDOP(c, POP_TOP);
4803 ADDOP(c, POP_TOP);
4804 ADDOP(c, POP_EXCEPT);
4805 ADDOP(c, POP_TOP);
4806 return 1;
4807}
Yury Selivanov75445082015-05-11 22:57:16 -04004808
4809/*
4810 Implements the async with statement.
4811
4812 The semantics outlined in that PEP are as follows:
4813
4814 async with EXPR as VAR:
4815 BLOCK
4816
4817 It is implemented roughly as:
4818
4819 context = EXPR
4820 exit = context.__aexit__ # not calling it
4821 value = await context.__aenter__()
4822 try:
4823 VAR = value # if VAR present in the syntax
4824 BLOCK
4825 finally:
4826 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004827 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004828 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004829 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004830 if not (await exit(*exc)):
4831 raise
4832 */
4833static int
4834compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4835{
Mark Shannonfee55262019-11-21 09:11:43 +00004836 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004837 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4838
4839 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004840 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004841 c->u->u_ste->ste_coroutine = 1;
4842 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004843 return compiler_error(c, "'async with' outside async function");
4844 }
Yury Selivanov75445082015-05-11 22:57:16 -04004845
4846 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004847 final = compiler_new_block(c);
4848 exit = compiler_new_block(c);
4849 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004850 return 0;
4851
4852 /* Evaluate EXPR */
4853 VISIT(c, expr, item->context_expr);
4854
4855 ADDOP(c, BEFORE_ASYNC_WITH);
4856 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004857 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004858 ADDOP(c, YIELD_FROM);
4859
Mark Shannon582aaf12020-08-04 17:30:11 +01004860 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004861
4862 /* SETUP_ASYNC_WITH pushes a finally block. */
4863 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004864 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004865 return 0;
4866 }
4867
4868 if (item->optional_vars) {
4869 VISIT(c, expr, item->optional_vars);
4870 }
4871 else {
4872 /* Discard result from context.__aenter__() */
4873 ADDOP(c, POP_TOP);
4874 }
4875
4876 pos++;
4877 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4878 /* BLOCK code */
4879 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4880 else if (!compiler_async_with(c, s, pos))
4881 return 0;
4882
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004883 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004884 ADDOP(c, POP_BLOCK);
4885 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004886
Mark Shannonfee55262019-11-21 09:11:43 +00004887 /* For successful outcome:
4888 * call __exit__(None, None, None)
4889 */
4890 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004891 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004892 ADDOP(c, GET_AWAITABLE);
4893 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4894 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004895
Mark Shannonfee55262019-11-21 09:11:43 +00004896 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004897
Mark Shannon582aaf12020-08-04 17:30:11 +01004898 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004899
4900 /* For exceptional outcome: */
4901 compiler_use_next_block(c, final);
4902
4903 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004904 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004905 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004906 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004907 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004908
Mark Shannonfee55262019-11-21 09:11:43 +00004909compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004910 return 1;
4911}
4912
4913
Guido van Rossumc2e20742006-02-27 22:32:47 +00004914/*
4915 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004916 with EXPR as VAR:
4917 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004918 is implemented as:
4919 <code for EXPR>
4920 SETUP_WITH E
4921 <code to store to VAR> or POP_TOP
4922 <code for BLOCK>
4923 LOAD_CONST (None, None, None)
4924 CALL_FUNCTION_EX 0
4925 JUMP_FORWARD EXIT
4926 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4927 POP_JUMP_IF_TRUE T:
4928 RERAISE
4929 T: POP_TOP * 3 (remove exception from stack)
4930 POP_EXCEPT
4931 POP_TOP
4932 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004933 */
Mark Shannonfee55262019-11-21 09:11:43 +00004934
Guido van Rossumc2e20742006-02-27 22:32:47 +00004935static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004936compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004937{
Mark Shannonfee55262019-11-21 09:11:43 +00004938 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004939 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004940
4941 assert(s->kind == With_kind);
4942
Guido van Rossumc2e20742006-02-27 22:32:47 +00004943 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004944 final = compiler_new_block(c);
4945 exit = compiler_new_block(c);
4946 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004947 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004948
Thomas Wouters477c8d52006-05-27 19:21:47 +00004949 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004950 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004951 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004952 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004953
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004954 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004955 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004956 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004957 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004958 }
4959
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004960 if (item->optional_vars) {
4961 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004962 }
4963 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004964 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004965 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004966 }
4967
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004968 pos++;
4969 if (pos == asdl_seq_LEN(s->v.With.items))
4970 /* BLOCK code */
4971 VISIT_SEQ(c, stmt, s->v.With.body)
4972 else if (!compiler_with(c, s, pos))
4973 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004974
Guido van Rossumc2e20742006-02-27 22:32:47 +00004975 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004976 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004977
Mark Shannonfee55262019-11-21 09:11:43 +00004978 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004979
Mark Shannonfee55262019-11-21 09:11:43 +00004980 /* For successful outcome:
4981 * call __exit__(None, None, None)
4982 */
4983 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004984 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004985 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004986 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004987
Mark Shannonfee55262019-11-21 09:11:43 +00004988 /* For exceptional outcome: */
4989 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004990
Mark Shannonfee55262019-11-21 09:11:43 +00004991 ADDOP(c, WITH_EXCEPT_START);
4992 compiler_with_except_finish(c);
4993
4994 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004995 return 1;
4996}
4997
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004998static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004999compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005001 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07005002 case NamedExpr_kind:
5003 VISIT(c, expr, e->v.NamedExpr.value);
5004 ADDOP(c, DUP_TOP);
5005 VISIT(c, expr, e->v.NamedExpr.target);
5006 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005007 case BoolOp_kind:
5008 return compiler_boolop(c, e);
5009 case BinOp_kind:
5010 VISIT(c, expr, e->v.BinOp.left);
5011 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05005012 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 break;
5014 case UnaryOp_kind:
5015 VISIT(c, expr, e->v.UnaryOp.operand);
5016 ADDOP(c, unaryop(e->v.UnaryOp.op));
5017 break;
5018 case Lambda_kind:
5019 return compiler_lambda(c, e);
5020 case IfExp_kind:
5021 return compiler_ifexp(c, e);
5022 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005023 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005024 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005025 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 case GeneratorExp_kind:
5027 return compiler_genexp(c, e);
5028 case ListComp_kind:
5029 return compiler_listcomp(c, e);
5030 case SetComp_kind:
5031 return compiler_setcomp(c, e);
5032 case DictComp_kind:
5033 return compiler_dictcomp(c, e);
5034 case Yield_kind:
5035 if (c->u->u_ste->ste_type != FunctionBlock)
5036 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005037 if (e->v.Yield.value) {
5038 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005039 }
5040 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005041 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005043 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005045 case YieldFrom_kind:
5046 if (c->u->u_ste->ste_type != FunctionBlock)
5047 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005048
5049 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5050 return compiler_error(c, "'yield from' inside async function");
5051
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005052 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005053 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005054 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005055 ADDOP(c, YIELD_FROM);
5056 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005057 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005058 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005059 if (c->u->u_ste->ste_type != FunctionBlock){
5060 return compiler_error(c, "'await' outside function");
5061 }
Yury Selivanov75445082015-05-11 22:57:16 -04005062
Victor Stinner331a6a52019-05-27 16:39:22 +02005063 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005064 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5065 return compiler_error(c, "'await' outside async function");
5066 }
5067 }
Yury Selivanov75445082015-05-11 22:57:16 -04005068
5069 VISIT(c, expr, e->v.Await.value);
5070 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005071 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005072 ADDOP(c, YIELD_FROM);
5073 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005074 case Compare_kind:
5075 return compiler_compare(c, e);
5076 case Call_kind:
5077 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005078 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005079 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005080 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005081 case JoinedStr_kind:
5082 return compiler_joined_str(c, e);
5083 case FormattedValue_kind:
5084 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005085 /* The following exprs can be assignment targets. */
5086 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005087 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005088 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005089 case Load:
5090 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5091 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005092 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005093 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5094 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005095 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5096 break;
5097 case Del:
5098 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5099 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 }
5101 break;
5102 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005103 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 case Starred_kind:
5105 switch (e->v.Starred.ctx) {
5106 case Store:
5107 /* In all legitimate cases, the Starred node was already replaced
5108 * by compiler_list/compiler_tuple. XXX: is that okay? */
5109 return compiler_error(c,
5110 "starred assignment target must be in a list or tuple");
5111 default:
5112 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005113 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005114 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005115 break;
5116 case Slice_kind:
5117 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005118 case Name_kind:
5119 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5120 /* child nodes of List and Tuple will have expr_context set */
5121 case List_kind:
5122 return compiler_list(c, e);
5123 case Tuple_kind:
5124 return compiler_tuple(c, e);
5125 }
5126 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005127}
5128
5129static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005130compiler_visit_expr(struct compiler *c, expr_ty e)
5131{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005132 int old_lineno = c->u->u_lineno;
5133 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005134 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005135 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005136 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005137 c->u->u_col_offset = old_col_offset;
5138 return res;
5139}
5140
5141static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005142compiler_augassign(struct compiler *c, stmt_ty s)
5143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005144 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005145 expr_ty e = s->v.AugAssign.target;
5146
5147 int old_lineno = c->u->u_lineno;
5148 int old_col_offset = c->u->u_col_offset;
5149 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005151 switch (e->kind) {
5152 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005153 VISIT(c, expr, e->v.Attribute.value);
5154 ADDOP(c, DUP_TOP);
5155 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005156 break;
5157 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005158 VISIT(c, expr, e->v.Subscript.value);
5159 VISIT(c, expr, e->v.Subscript.slice);
5160 ADDOP(c, DUP_TOP_TWO);
5161 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005162 break;
5163 case Name_kind:
5164 if (!compiler_nameop(c, e->v.Name.id, Load))
5165 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005166 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005167 default:
5168 PyErr_Format(PyExc_SystemError,
5169 "invalid node type (%d) for augmented assignment",
5170 e->kind);
5171 return 0;
5172 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005173
5174 c->u->u_lineno = old_lineno;
5175 c->u->u_col_offset = old_col_offset;
5176
5177 VISIT(c, expr, s->v.AugAssign.value);
5178 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5179
5180 SET_LOC(c, e);
5181
5182 switch (e->kind) {
5183 case Attribute_kind:
5184 ADDOP(c, ROT_TWO);
5185 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5186 break;
5187 case Subscript_kind:
5188 ADDOP(c, ROT_THREE);
5189 ADDOP(c, STORE_SUBSCR);
5190 break;
5191 case Name_kind:
5192 return compiler_nameop(c, e->v.Name.id, Store);
5193 default:
5194 Py_UNREACHABLE();
5195 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005196 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005197}
5198
5199static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005200check_ann_expr(struct compiler *c, expr_ty e)
5201{
5202 VISIT(c, expr, e);
5203 ADDOP(c, POP_TOP);
5204 return 1;
5205}
5206
5207static int
5208check_annotation(struct compiler *c, stmt_ty s)
5209{
5210 /* Annotations are only evaluated in a module or class. */
5211 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5212 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5213 return check_ann_expr(c, s->v.AnnAssign.annotation);
5214 }
5215 return 1;
5216}
5217
5218static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005219check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005220{
5221 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005222 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005223 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005224 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005225 return 0;
5226 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005227 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5228 return 0;
5229 }
5230 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5231 return 0;
5232 }
5233 return 1;
5234 case Tuple_kind: {
5235 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005236 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005237 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005238 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005239 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005240 return 0;
5241 }
5242 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005243 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005244 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005245 default:
5246 return check_ann_expr(c, e);
5247 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005248}
5249
5250static int
5251compiler_annassign(struct compiler *c, stmt_ty s)
5252{
5253 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005254 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005255
5256 assert(s->kind == AnnAssign_kind);
5257
5258 /* We perform the actual assignment first. */
5259 if (s->v.AnnAssign.value) {
5260 VISIT(c, expr, s->v.AnnAssign.value);
5261 VISIT(c, expr, targ);
5262 }
5263 switch (targ->kind) {
5264 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005265 if (forbidden_name(c, targ->v.Name.id, Store))
5266 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005267 /* If we have a simple name in a module or class, store annotation. */
5268 if (s->v.AnnAssign.simple &&
5269 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5270 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005271 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005272 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005273 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005274 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005275 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005276 }
5277 break;
5278 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005279 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5280 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005281 if (!s->v.AnnAssign.value &&
5282 !check_ann_expr(c, targ->v.Attribute.value)) {
5283 return 0;
5284 }
5285 break;
5286 case Subscript_kind:
5287 if (!s->v.AnnAssign.value &&
5288 (!check_ann_expr(c, targ->v.Subscript.value) ||
5289 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5290 return 0;
5291 }
5292 break;
5293 default:
5294 PyErr_Format(PyExc_SystemError,
5295 "invalid node type (%d) for annotated assignment",
5296 targ->kind);
5297 return 0;
5298 }
5299 /* Annotation is evaluated last. */
5300 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5301 return 0;
5302 }
5303 return 1;
5304}
5305
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005306/* Raises a SyntaxError and returns 0.
5307 If something goes wrong, a different exception may be raised.
5308*/
5309
5310static int
5311compiler_error(struct compiler *c, const char *errstr)
5312{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005313 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005314 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005315
Victor Stinner14e461d2013-08-26 22:28:21 +02005316 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005317 if (!loc) {
5318 Py_INCREF(Py_None);
5319 loc = Py_None;
5320 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005321 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005322 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005323 if (!u)
5324 goto exit;
5325 v = Py_BuildValue("(zO)", errstr, u);
5326 if (!v)
5327 goto exit;
5328 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005329 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005330 Py_DECREF(loc);
5331 Py_XDECREF(u);
5332 Py_XDECREF(v);
5333 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005334}
5335
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005336/* Emits a SyntaxWarning and returns 1 on success.
5337 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5338 and returns 0.
5339*/
5340static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005341compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005342{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005343 va_list vargs;
5344#ifdef HAVE_STDARG_PROTOTYPES
5345 va_start(vargs, format);
5346#else
5347 va_start(vargs);
5348#endif
5349 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5350 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005351 if (msg == NULL) {
5352 return 0;
5353 }
5354 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5355 c->u->u_lineno, NULL, NULL) < 0)
5356 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005357 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005358 /* Replace the SyntaxWarning exception with a SyntaxError
5359 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005360 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005361 assert(PyUnicode_AsUTF8(msg) != NULL);
5362 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005363 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005364 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005365 return 0;
5366 }
5367 Py_DECREF(msg);
5368 return 1;
5369}
5370
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005371static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005372compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005374 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005375 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005376
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005377 if (ctx == Load) {
5378 if (!check_subscripter(c, e->v.Subscript.value)) {
5379 return 0;
5380 }
5381 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5382 return 0;
5383 }
5384 }
5385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005387 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 case Store: op = STORE_SUBSCR; break;
5389 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005391 assert(op);
5392 VISIT(c, expr, e->v.Subscript.value);
5393 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 ADDOP(c, op);
5395 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005396}
5397
5398static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005399compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005401 int n = 2;
5402 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005404 /* only handles the cases where BUILD_SLICE is emitted */
5405 if (s->v.Slice.lower) {
5406 VISIT(c, expr, s->v.Slice.lower);
5407 }
5408 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005409 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005410 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 if (s->v.Slice.upper) {
5413 VISIT(c, expr, s->v.Slice.upper);
5414 }
5415 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005416 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005417 }
5418
5419 if (s->v.Slice.step) {
5420 n++;
5421 VISIT(c, expr, s->v.Slice.step);
5422 }
5423 ADDOP_I(c, BUILD_SLICE, n);
5424 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005425}
5426
Thomas Wouters89f507f2006-12-13 04:49:30 +00005427/* End of the compiler section, beginning of the assembler section */
5428
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005429/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005430 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431
5432 XXX must handle implicit jumps from one block to next
5433*/
5434
Thomas Wouters89f507f2006-12-13 04:49:30 +00005435struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 PyObject *a_bytecode; /* string containing bytecode */
5437 int a_offset; /* offset into bytecode */
5438 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005439 PyObject *a_lnotab; /* string containing lnotab */
5440 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005441 int a_prevlineno; /* lineno of last emitted line in line table */
5442 int a_lineno; /* lineno of last emitted instruction */
5443 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005444 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005445};
5446
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005447Py_LOCAL_INLINE(void)
5448stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005449{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005450 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005451 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005452 assert(b->b_startdepth < 0);
5453 b->b_startdepth = depth;
5454 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005456}
5457
5458/* Find the flow path that needs the largest stack. We assume that
5459 * cycles in the flow graph have no net effect on the stack depth.
5460 */
5461static int
5462stackdepth(struct compiler *c)
5463{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005464 basicblock *b, *entryblock = NULL;
5465 basicblock **stack, **sp;
5466 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005467 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005468 b->b_startdepth = INT_MIN;
5469 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005470 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005471 }
5472 if (!entryblock)
5473 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005474 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5475 if (!stack) {
5476 PyErr_NoMemory();
5477 return -1;
5478 }
5479
5480 sp = stack;
5481 stackdepth_push(&sp, entryblock, 0);
5482 while (sp != stack) {
5483 b = *--sp;
5484 int depth = b->b_startdepth;
5485 assert(depth >= 0);
5486 basicblock *next = b->b_next;
5487 for (int i = 0; i < b->b_iused; i++) {
5488 struct instr *instr = &b->b_instr[i];
5489 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5490 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005491 _Py_FatalErrorFormat(__func__,
5492 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005493 }
5494 int new_depth = depth + effect;
5495 if (new_depth > maxdepth) {
5496 maxdepth = new_depth;
5497 }
5498 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005499 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005500 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5501 assert(effect != PY_INVALID_STACK_EFFECT);
5502 int target_depth = depth + effect;
5503 if (target_depth > maxdepth) {
5504 maxdepth = target_depth;
5505 }
5506 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005507 stackdepth_push(&sp, instr->i_target, target_depth);
5508 }
5509 depth = new_depth;
5510 if (instr->i_opcode == JUMP_ABSOLUTE ||
5511 instr->i_opcode == JUMP_FORWARD ||
5512 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005513 instr->i_opcode == RAISE_VARARGS ||
5514 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005515 {
5516 /* remaining code is dead */
5517 next = NULL;
5518 break;
5519 }
5520 }
5521 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005522 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005523 stackdepth_push(&sp, next, depth);
5524 }
5525 }
5526 PyObject_Free(stack);
5527 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005528}
5529
5530static int
5531assemble_init(struct assembler *a, int nblocks, int firstlineno)
5532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005533 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005534 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005535 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005536 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005537 if (a->a_bytecode == NULL) {
5538 goto error;
5539 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005541 if (a->a_lnotab == NULL) {
5542 goto error;
5543 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005544 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005545 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005546 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005547 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005549error:
5550 Py_XDECREF(a->a_bytecode);
5551 Py_XDECREF(a->a_lnotab);
5552 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005553}
5554
5555static void
5556assemble_free(struct assembler *a)
5557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005558 Py_XDECREF(a->a_bytecode);
5559 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005560}
5561
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005562static int
5563blocksize(basicblock *b)
5564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005565 int i;
5566 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005568 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005569 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005570 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005571}
5572
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005573static int
Mark Shannon877df852020-11-12 09:43:29 +00005574assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005575{
Mark Shannon877df852020-11-12 09:43:29 +00005576 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005577 if (a->a_lnotab_off + 2 >= len) {
5578 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5579 return 0;
5580 }
Mark Shannon877df852020-11-12 09:43:29 +00005581 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005582 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005584 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005585 *lnotab++ = bdelta;
5586 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005587 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005588}
5589
Mark Shannon877df852020-11-12 09:43:29 +00005590/* Appends a range to the end of the line number table. See
5591 * Objects/lnotab_notes.txt for the description of the line number table. */
5592
5593static int
5594assemble_line_range(struct assembler *a)
5595{
5596 int ldelta, bdelta;
5597 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5598 if (bdelta == 0) {
5599 return 1;
5600 }
5601 if (a->a_lineno < 0) {
5602 ldelta = -128;
5603 }
5604 else {
5605 ldelta = a->a_lineno - a->a_prevlineno;
5606 a->a_prevlineno = a->a_lineno;
5607 while (ldelta > 127) {
5608 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5609 return 0;
5610 }
5611 ldelta -= 127;
5612 }
5613 while (ldelta < -127) {
5614 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5615 return 0;
5616 }
5617 ldelta += 127;
5618 }
5619 }
5620 assert(-128 <= ldelta && ldelta < 128);
5621 while (bdelta > 254) {
5622 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5623 return 0;
5624 }
5625 ldelta = a->a_lineno < 0 ? -128 : 0;
5626 bdelta -= 254;
5627 }
5628 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5629 return 0;
5630 }
5631 a->a_lineno_start = a->a_offset;
5632 return 1;
5633}
5634
5635static int
5636assemble_lnotab(struct assembler *a, struct instr *i)
5637{
5638 if (i->i_lineno == a->a_lineno) {
5639 return 1;
5640 }
5641 if (!assemble_line_range(a)) {
5642 return 0;
5643 }
5644 a->a_lineno = i->i_lineno;
5645 return 1;
5646}
5647
5648
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005649/* assemble_emit()
5650 Extend the bytecode with a new instruction.
5651 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005652*/
5653
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005654static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005655assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005656{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005657 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005659 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005660
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005661 arg = i->i_oparg;
5662 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 if (i->i_lineno && !assemble_lnotab(a, i))
5664 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005665 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 if (len > PY_SSIZE_T_MAX / 2)
5667 return 0;
5668 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5669 return 0;
5670 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005671 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005672 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005673 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005675}
5676
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005677static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005678assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005681 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005684 /* Compute the size of each block and fixup jump args.
5685 Replace block pointer with position in bytecode. */
5686 do {
5687 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005688 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005689 bsize = blocksize(b);
5690 b->b_offset = totsize;
5691 totsize += bsize;
5692 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005693 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005694 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5695 bsize = b->b_offset;
5696 for (i = 0; i < b->b_iused; i++) {
5697 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005698 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005699 /* Relative jumps are computed relative to
5700 the instruction pointer after fetching
5701 the jump instruction.
5702 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005703 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005704 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005705 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005706 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005707 instr->i_oparg -= bsize;
5708 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005709 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005710 if (instrsize(instr->i_oparg) != isize) {
5711 extended_arg_recompile = 1;
5712 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 }
5715 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005717 /* XXX: This is an awful hack that could hurt performance, but
5718 on the bright side it should work until we come up
5719 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 The issue is that in the first loop blocksize() is called
5722 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005723 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005724 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005726 So we loop until we stop seeing new EXTENDED_ARGs.
5727 The only EXTENDED_ARGs that could be popping up are
5728 ones in jump instructions. So this should converge
5729 fairly quickly.
5730 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005731 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005732}
5733
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005734static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005735dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005737 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005738 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005740 tuple = PyTuple_New(size);
5741 if (tuple == NULL)
5742 return NULL;
5743 while (PyDict_Next(dict, &pos, &k, &v)) {
5744 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005745 Py_INCREF(k);
5746 assert((i - offset) < size);
5747 assert((i - offset) >= 0);
5748 PyTuple_SET_ITEM(tuple, i - offset, k);
5749 }
5750 return tuple;
5751}
5752
5753static PyObject *
5754consts_dict_keys_inorder(PyObject *dict)
5755{
5756 PyObject *consts, *k, *v;
5757 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5758
5759 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5760 if (consts == NULL)
5761 return NULL;
5762 while (PyDict_Next(dict, &pos, &k, &v)) {
5763 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005764 /* The keys of the dictionary can be tuples wrapping a contant.
5765 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5766 * the object we want is always second. */
5767 if (PyTuple_CheckExact(k)) {
5768 k = PyTuple_GET_ITEM(k, 1);
5769 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005770 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005771 assert(i < size);
5772 assert(i >= 0);
5773 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005774 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005775 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005776}
5777
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005778static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005779compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005781 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005782 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005783 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005784 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005785 if (ste->ste_nested)
5786 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005787 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005788 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005789 if (!ste->ste_generator && ste->ste_coroutine)
5790 flags |= CO_COROUTINE;
5791 if (ste->ste_generator && ste->ste_coroutine)
5792 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 if (ste->ste_varargs)
5794 flags |= CO_VARARGS;
5795 if (ste->ste_varkeywords)
5796 flags |= CO_VARKEYWORDS;
5797 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 /* (Only) inherit compilerflags in PyCF_MASK */
5800 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005801
Pablo Galindo90235812020-03-15 04:29:22 +00005802 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005803 ste->ste_coroutine &&
5804 !ste->ste_generator) {
5805 flags |= CO_COROUTINE;
5806 }
5807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005808 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005809}
5810
INADA Naokic2e16072018-11-26 21:23:22 +09005811// Merge *tuple* with constant cache.
5812// Unlike merge_consts_recursive(), this function doesn't work recursively.
5813static int
5814merge_const_tuple(struct compiler *c, PyObject **tuple)
5815{
5816 assert(PyTuple_CheckExact(*tuple));
5817
5818 PyObject *key = _PyCode_ConstantKey(*tuple);
5819 if (key == NULL) {
5820 return 0;
5821 }
5822
5823 // t is borrowed reference
5824 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5825 Py_DECREF(key);
5826 if (t == NULL) {
5827 return 0;
5828 }
5829 if (t == key) { // tuple is new constant.
5830 return 1;
5831 }
5832
5833 PyObject *u = PyTuple_GET_ITEM(t, 1);
5834 Py_INCREF(u);
5835 Py_DECREF(*tuple);
5836 *tuple = u;
5837 return 1;
5838}
5839
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005840static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005841makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 PyObject *names = NULL;
5845 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005846 PyObject *name = NULL;
5847 PyObject *freevars = NULL;
5848 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005849 Py_ssize_t nlocals;
5850 int nlocals_int;
5851 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005852 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005854 names = dict_keys_inorder(c->u->u_names, 0);
5855 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005856 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005857 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005858 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005859 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5860 if (!cellvars)
5861 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005862 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005863 if (!freevars)
5864 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005865
INADA Naokic2e16072018-11-26 21:23:22 +09005866 if (!merge_const_tuple(c, &names) ||
5867 !merge_const_tuple(c, &varnames) ||
5868 !merge_const_tuple(c, &cellvars) ||
5869 !merge_const_tuple(c, &freevars))
5870 {
5871 goto error;
5872 }
5873
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005874 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005875 assert(nlocals < INT_MAX);
5876 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005878 flags = compute_code_flags(c);
5879 if (flags < 0)
5880 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005881
Mark Shannon6e8128f2020-07-30 10:03:00 +01005882 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5883 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005884 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005885 }
INADA Naokic2e16072018-11-26 21:23:22 +09005886 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005887 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005888 goto error;
5889 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005890
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005891 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005892 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005893 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005894 maxdepth = stackdepth(c);
5895 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005896 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005897 goto error;
5898 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005899 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005900 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005901 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005902 varnames, freevars, cellvars, c->c_filename,
5903 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005904 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005905 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005906 Py_XDECREF(names);
5907 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005908 Py_XDECREF(name);
5909 Py_XDECREF(freevars);
5910 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005911 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005912}
5913
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005914
5915/* For debugging purposes only */
5916#if 0
5917static void
5918dump_instr(const struct instr *i)
5919{
Mark Shannon582aaf12020-08-04 17:30:11 +01005920 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5921 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005922 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005924 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005925 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005927 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5929 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005930}
5931
5932static void
5933dump_basicblock(const basicblock *b)
5934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005935 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005936 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5937 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005938 if (b->b_instr) {
5939 int i;
5940 for (i = 0; i < b->b_iused; i++) {
5941 fprintf(stderr, " [%02d] ", i);
5942 dump_instr(b->b_instr + i);
5943 }
5944 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005945}
5946#endif
5947
Mark Shannon6e8128f2020-07-30 10:03:00 +01005948static int
5949optimize_cfg(struct assembler *a, PyObject *consts);
5950
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005951static PyCodeObject *
5952assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005954 basicblock *b, *entryblock;
5955 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005956 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005958 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005960 /* Make sure every block that falls off the end returns None.
5961 XXX NEXT_BLOCK() isn't quite right, because if the last
5962 block ends with a jump or return b_next shouldn't set.
5963 */
5964 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005965 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005966 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005967 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005968 ADDOP(c, RETURN_VALUE);
5969 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005971 nblocks = 0;
5972 entryblock = NULL;
5973 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5974 nblocks++;
5975 entryblock = b;
5976 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005978 /* Set firstlineno if it wasn't explicitly set. */
5979 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005980 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005982 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005983 c->u->u_firstlineno = 1;
5984 }
5985 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5986 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005987 a.a_entry = entryblock;
5988 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005989
Mark Shannon6e8128f2020-07-30 10:03:00 +01005990 consts = consts_dict_keys_inorder(c->u->u_consts);
5991 if (consts == NULL) {
5992 goto error;
5993 }
5994 if (optimize_cfg(&a, consts)) {
5995 goto error;
5996 }
5997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005998 /* Can't modify the bytecode after computing jump offsets. */
5999 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006000
Mark Shannoncc75ab72020-11-12 19:49:33 +00006001 /* Emit code. */
6002 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006003 for (j = 0; j < b->b_iused; j++)
6004 if (!assemble_emit(&a, &b->b_instr[j]))
6005 goto error;
6006 }
Mark Shannon877df852020-11-12 09:43:29 +00006007 if (!assemble_line_range(&a)) {
6008 return 0;
6009 }
6010 /* Emit sentinel at end of line number table */
6011 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
6012 goto error;
6013 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006015 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6016 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006017 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006018 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006019
Mark Shannon6e8128f2020-07-30 10:03:00 +01006020 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006021 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006022 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006023 assemble_free(&a);
6024 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006025}
Georg Brandl8334fd92010-12-04 10:26:46 +00006026
6027#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006028PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006029PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6030 PyArena *arena)
6031{
6032 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6033}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006034
6035
6036/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6037 with LOAD_CONST (c1, c2, ... cn).
6038 The consts table must still be in list form so that the
6039 new constant (c1, c2, ... cn) can be appended.
6040 Called with codestr pointing to the first LOAD_CONST.
6041*/
6042static int
6043fold_tuple_on_constants(struct instr *inst,
6044 int n, PyObject *consts)
6045{
6046 /* Pre-conditions */
6047 assert(PyList_CheckExact(consts));
6048 assert(inst[n].i_opcode == BUILD_TUPLE);
6049 assert(inst[n].i_oparg == n);
6050
6051 for (int i = 0; i < n; i++) {
6052 if (inst[i].i_opcode != LOAD_CONST) {
6053 return 0;
6054 }
6055 }
6056
6057 /* Buildup new tuple of constants */
6058 PyObject *newconst = PyTuple_New(n);
6059 if (newconst == NULL) {
6060 return -1;
6061 }
6062 for (int i = 0; i < n; i++) {
6063 int arg = inst[i].i_oparg;
6064 PyObject *constant = PyList_GET_ITEM(consts, arg);
6065 Py_INCREF(constant);
6066 PyTuple_SET_ITEM(newconst, i, constant);
6067 }
6068 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006069 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006070 Py_DECREF(newconst);
6071 PyErr_SetString(PyExc_OverflowError, "too many constants");
6072 return -1;
6073 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006074 if (PyList_Append(consts, newconst)) {
6075 Py_DECREF(newconst);
6076 return -1;
6077 }
6078 Py_DECREF(newconst);
6079 for (int i = 0; i < n; i++) {
6080 inst[i].i_opcode = NOP;
6081 }
6082 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006083 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006084 return 0;
6085}
6086
Mark Shannoncc75ab72020-11-12 19:49:33 +00006087/* Maximum size of basic block that should be copied in optimizer */
6088#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006089
6090/* Optimization */
6091static int
6092optimize_basic_block(basicblock *bb, PyObject *consts)
6093{
6094 assert(PyList_CheckExact(consts));
6095 struct instr nop;
6096 nop.i_opcode = NOP;
6097 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006098 for (int i = 0; i < bb->b_iused; i++) {
6099 struct instr *inst = &bb->b_instr[i];
6100 int oparg = inst->i_oparg;
6101 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006102 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006103 /* Skip over empty basic blocks. */
6104 while (inst->i_target->b_iused == 0) {
6105 inst->i_target = inst->i_target->b_next;
6106 }
6107 target = &inst->i_target->b_instr[0];
6108 }
6109 else {
6110 target = &nop;
6111 }
6112 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006113 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006114 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006115 {
6116 PyObject* cnt;
6117 int is_true;
6118 int jump_if_true;
6119 switch(nextop) {
6120 case POP_JUMP_IF_FALSE:
6121 case POP_JUMP_IF_TRUE:
6122 cnt = PyList_GET_ITEM(consts, oparg);
6123 is_true = PyObject_IsTrue(cnt);
6124 if (is_true == -1) {
6125 goto error;
6126 }
6127 inst->i_opcode = NOP;
6128 jump_if_true = nextop == POP_JUMP_IF_TRUE;
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 bb->b_instr[i+1].i_opcode = NOP;
6135 }
6136 break;
6137 case JUMP_IF_FALSE_OR_POP:
6138 case JUMP_IF_TRUE_OR_POP:
6139 cnt = PyList_GET_ITEM(consts, oparg);
6140 is_true = PyObject_IsTrue(cnt);
6141 if (is_true == -1) {
6142 goto error;
6143 }
6144 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6145 if (is_true == jump_if_true) {
6146 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6147 bb->b_nofallthrough = 1;
6148 }
6149 else {
6150 inst->i_opcode = NOP;
6151 bb->b_instr[i+1].i_opcode = NOP;
6152 }
6153 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006154 }
6155 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006156 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006157
6158 /* Try to fold tuples of constants.
6159 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6160 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6161 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6162 case BUILD_TUPLE:
6163 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6164 switch(oparg) {
6165 case 1:
6166 inst->i_opcode = NOP;
6167 bb->b_instr[i+1].i_opcode = NOP;
6168 break;
6169 case 2:
6170 inst->i_opcode = ROT_TWO;
6171 bb->b_instr[i+1].i_opcode = NOP;
6172 break;
6173 case 3:
6174 inst->i_opcode = ROT_THREE;
6175 bb->b_instr[i+1].i_opcode = ROT_TWO;
6176 }
6177 break;
6178 }
6179 if (i >= oparg) {
6180 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6181 goto error;
6182 }
6183 }
6184 break;
6185
6186 /* Simplify conditional jump to conditional jump where the
6187 result of the first test implies the success of a similar
6188 test or the failure of the opposite test.
6189 Arises in code like:
6190 "a and b or c"
6191 "(a and b) and c"
6192 "(a or b) or c"
6193 "(a or b) and c"
6194 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6195 --> x:JUMP_IF_FALSE_OR_POP z
6196 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6197 --> x:POP_JUMP_IF_FALSE y+1
6198 where y+1 is the instruction following the second test.
6199 */
6200 case JUMP_IF_FALSE_OR_POP:
6201 switch(target->i_opcode) {
6202 case POP_JUMP_IF_FALSE:
6203 *inst = *target;
Mark Shannon266b4622020-11-17 19:30:14 +00006204 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006205 break;
6206 case JUMP_ABSOLUTE:
6207 case JUMP_FORWARD:
6208 case JUMP_IF_FALSE_OR_POP:
Mark Shannon266b4622020-11-17 19:30:14 +00006209 if (inst->i_target != target->i_target) {
6210 inst->i_target = target->i_target;
6211 --i;
6212 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006213 break;
6214 case JUMP_IF_TRUE_OR_POP:
6215 assert (inst->i_target->b_iused == 1);
6216 inst->i_opcode = POP_JUMP_IF_FALSE;
6217 inst->i_target = inst->i_target->b_next;
Mark Shannon266b4622020-11-17 19:30:14 +00006218 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006219 break;
6220 }
6221 break;
6222
6223 case JUMP_IF_TRUE_OR_POP:
6224 switch(target->i_opcode) {
6225 case POP_JUMP_IF_TRUE:
6226 *inst = *target;
Mark Shannon266b4622020-11-17 19:30:14 +00006227 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006228 break;
6229 case JUMP_ABSOLUTE:
6230 case JUMP_FORWARD:
6231 case JUMP_IF_TRUE_OR_POP:
Mark Shannon266b4622020-11-17 19:30:14 +00006232 if (inst->i_target != target->i_target) {
6233 inst->i_target = target->i_target;
6234 --i;
6235 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006236 break;
6237 case JUMP_IF_FALSE_OR_POP:
6238 assert (inst->i_target->b_iused == 1);
6239 inst->i_opcode = POP_JUMP_IF_TRUE;
6240 inst->i_target = inst->i_target->b_next;
Mark Shannon266b4622020-11-17 19:30:14 +00006241 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006242 break;
6243 }
6244 break;
6245
6246 case POP_JUMP_IF_FALSE:
6247 switch(target->i_opcode) {
6248 case JUMP_ABSOLUTE:
6249 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006250 if (inst->i_target != target->i_target) {
6251 inst->i_target = target->i_target;
6252 --i;
6253 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006254 break;
6255 }
6256 break;
6257
6258 case POP_JUMP_IF_TRUE:
6259 switch(target->i_opcode) {
6260 case JUMP_ABSOLUTE:
6261 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006262 if (inst->i_target != target->i_target) {
6263 inst->i_target = target->i_target;
6264 --i;
6265 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006266 break;
6267 }
6268 break;
6269
6270 case JUMP_ABSOLUTE:
6271 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006272 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006273 switch(target->i_opcode) {
6274 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006275 if (inst->i_target != target->i_target) {
6276 inst->i_target = target->i_target;
6277 --i;
6278 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006279 break;
6280 case JUMP_ABSOLUTE:
Mark Shannon266b4622020-11-17 19:30:14 +00006281 if (inst->i_target != target->i_target) {
6282 inst->i_target = target->i_target;
6283 inst->i_opcode = target->i_opcode;
6284 --i;
6285 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006286 break;
6287 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006288 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6289 basicblock *to_copy = inst->i_target;
6290 *inst = to_copy->b_instr[0];
6291 for (i = 1; i < to_copy->b_iused; i++) {
6292 int index = compiler_next_instr(bb);
6293 if (index < 0) {
6294 return -1;
6295 }
6296 bb->b_instr[index] = to_copy->b_instr[i];
6297 }
6298 bb->b_exit = 1;
6299 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006300 break;
6301 }
6302 }
6303 return 0;
6304error:
6305 return -1;
6306}
6307
6308
6309static void
6310clean_basic_block(basicblock *bb) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006311 /* Remove NOPs. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006312 int dest = 0;
Mark Shannon877df852020-11-12 09:43:29 +00006313 int prev_lineno = -1;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006314 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006315 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006316 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006317 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006318 if (lineno < 0) {
6319 continue;
6320 }
Mark Shannon266b4622020-11-17 19:30:14 +00006321 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006322 if (prev_lineno == lineno) {
6323 continue;
6324 }
Mark Shannon266b4622020-11-17 19:30:14 +00006325 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006326 if (src < bb->b_iused - 1) {
6327 int next_lineno = bb->b_instr[src+1].i_lineno;
6328 if (next_lineno < 0 || next_lineno == lineno) {
6329 bb->b_instr[src+1].i_lineno = lineno;
6330 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006331 }
6332 }
Mark Shannon266b4622020-11-17 19:30:14 +00006333 else {
6334 basicblock* next = bb->b_next;
6335 while (next && next->b_iused == 0) {
6336 next = next->b_next;
6337 }
6338 /* or if last instruction in BB and next BB has same line number */
6339 if (next) {
6340 if (lineno == next->b_instr[0].i_lineno) {
6341 continue;
6342 }
6343 }
6344 }
6345
Mark Shannon6e8128f2020-07-30 10:03:00 +01006346 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006347 if (dest != src) {
6348 bb->b_instr[dest] = bb->b_instr[src];
6349 }
6350 dest++;
6351 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006352 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006353 assert(dest <= bb->b_iused);
6354 bb->b_iused = dest;
6355}
6356
Mark Shannon266b4622020-11-17 19:30:14 +00006357
6358static int
6359normalize_basic_block(basicblock *bb) {
6360 /* Mark blocks as exit and/or nofallthrough.
6361 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006362 for (int i = 0; i < bb->b_iused; i++) {
6363 switch(bb->b_instr[i].i_opcode) {
6364 case RETURN_VALUE:
6365 case RAISE_VARARGS:
6366 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006367 bb->b_exit = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006368 /* fall through */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006369 case JUMP_ABSOLUTE:
6370 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006371 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006372 /* fall through */
6373 case POP_JUMP_IF_FALSE:
6374 case POP_JUMP_IF_TRUE:
6375 case JUMP_IF_FALSE_OR_POP:
6376 case JUMP_IF_TRUE_OR_POP:
6377 if (i != bb->b_iused-1) {
6378 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6379 return -1;
6380 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006381 }
6382 }
Mark Shannon266b4622020-11-17 19:30:14 +00006383 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006384}
6385
6386
Mark Shannon6e8128f2020-07-30 10:03:00 +01006387static int
6388mark_reachable(struct assembler *a) {
6389 basicblock **stack, **sp;
6390 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6391 if (stack == NULL) {
6392 return -1;
6393 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006394 a->a_entry->b_reachable = 1;
6395 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006396 while (sp > stack) {
6397 basicblock *b = *(--sp);
Mark Shannoncc75ab72020-11-12 19:49:33 +00006398 if (b->b_next && !b->b_nofallthrough && b->b_next->b_reachable == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006399 b->b_next->b_reachable = 1;
6400 *sp++ = b->b_next;
6401 }
6402 for (int i = 0; i < b->b_iused; i++) {
6403 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006404 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006405 target = b->b_instr[i].i_target;
6406 if (target->b_reachable == 0) {
6407 target->b_reachable = 1;
6408 *sp++ = target;
6409 }
6410 }
6411 }
6412 }
6413 PyObject_Free(stack);
6414 return 0;
6415}
6416
6417
6418/* Perform basic peephole optimizations on a control flow graph.
6419 The consts object should still be in list form to allow new constants
6420 to be appended.
6421
6422 All transformations keep the code size the same or smaller.
6423 For those that reduce size, the gaps are initially filled with
6424 NOPs. Later those NOPs are removed.
6425*/
6426
6427static int
6428optimize_cfg(struct assembler *a, PyObject *consts)
6429{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006430 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannon266b4622020-11-17 19:30:14 +00006431 if (normalize_basic_block(b)) {
6432 return -1;
6433 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006434 }
6435 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6436 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006437 return -1;
6438 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006439 clean_basic_block(b);
6440 assert(b->b_reachable == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006441 }
6442 if (mark_reachable(a)) {
6443 return -1;
6444 }
6445 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006446 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6447 if (b->b_reachable == 0) {
6448 b->b_iused = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006449 }
6450 }
6451 return 0;
6452}
6453
6454/* Retained for API compatibility.
6455 * Optimization is now done in optimize_cfg */
6456
6457PyObject *
6458PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6459 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6460{
6461 Py_INCREF(code);
6462 return code;
6463}
6464