blob: 4ba91400001aa982b93171fea2ac788552fce326 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Mark Shannon6e8128f2020-07-30 10:03:00 +010012 * 5. Optimize the byte code (peephole optimizations).
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Victor Stinnerc9bc2902020-10-27 02:24:34 +010025#include "pycore_long.h" // _PyLong_GetZero()
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Mark Shannon582aaf12020-08-04 17:30:11 +010031#define NEED_OPCODE_JUMP_TABLES
Guido van Rossum10dc2e81990-11-18 17:27:39 +000032#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030033#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035#define DEFAULT_BLOCK_SIZE 16
36#define DEFAULT_BLOCKS 8
37#define DEFAULT_CODE_SIZE 128
38#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000039
Nick Coghlan650f0d02007-04-15 12:05:43 +000040#define COMP_GENEXP 0
41#define COMP_LISTCOMP 1
42#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000043#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000044
Pablo Galindo90235812020-03-15 04:29:22 +000045#define IS_TOP_LEVEL_AWAIT(c) ( \
46 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
47 && (c->u->u_ste->ste_type == ModuleBlock))
48
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000049struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Mark Shannon582aaf12020-08-04 17:30:11 +010056#define LOG_BITS_PER_INT 5
57#define MASK_LOW_LOG_BITS 31
58
59static inline int
60is_bit_set_in_table(uint32_t *table, int bitindex) {
61 /* Is the relevant bit set in the relevant word? */
62 /* 256 bits fit into 8 32-bits words.
63 * Word is indexed by (bitindex>>ln(size of int in bits)).
64 * Bit within word is the low bits of bitindex.
65 */
66 uint32_t word = table[bitindex >> LOG_BITS_PER_INT];
67 return (word >> (bitindex & MASK_LOW_LOG_BITS)) & 1;
68}
69
70static inline int
71is_relative_jump(struct instr *i)
72{
73 return is_bit_set_in_table(_PyOpcode_RelativeJump, i->i_opcode);
74}
75
76static inline int
77is_jump(struct instr *i)
78{
79 return is_bit_set_in_table(_PyOpcode_Jump, i->i_opcode);
80}
81
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000083 /* Each basicblock in a compilation unit is linked via b_list in the
84 reverse order that the block are allocated. b_list points to the next
85 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 struct basicblock_ *b_list;
87 /* number of instructions used */
88 int b_iused;
89 /* length of instruction array (b_instr) */
90 int b_ialloc;
91 /* pointer to an array of instructions, initially NULL */
92 struct instr *b_instr;
93 /* If b_next is non-NULL, it is a pointer to the next
94 block reached by normal control flow. */
95 struct basicblock_ *b_next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 /* b_return is true if a RETURN_VALUE opcode is inserted. */
97 unsigned b_return : 1;
Mark Shannon6e8128f2020-07-30 10:03:00 +010098 unsigned b_reachable : 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +000099 /* Basic block has no fall through (it ends with a return, raise or jump) */
100 unsigned b_nofallthrough : 1;
101 /* Basic block exits scope (it ends with a return or raise) */
102 unsigned b_exit : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 /* depth of stack upon entry of block, computed by stackdepth() */
104 int b_startdepth;
105 /* instruction offset for block, computed by assemble_jump_offsets() */
106 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107} basicblock;
108
109/* fblockinfo tracks the current frame block.
110
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000111A frame block is used to handle loops, try/except, and try/finally.
112It's called a frame block to distinguish it from a basic block in the
113compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114*/
115
Mark Shannon02d126a2020-09-25 14:04:19 +0100116enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
117 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118
119struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 enum fblocktype fb_type;
121 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200122 /* (optional) type-specific exit or cleanup block */
123 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +0000124 /* (optional) additional information required for unwinding */
125 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126};
127
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100128enum {
129 COMPILER_SCOPE_MODULE,
130 COMPILER_SCOPE_CLASS,
131 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400132 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400133 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100134 COMPILER_SCOPE_COMPREHENSION,
135};
136
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137/* The following items change on entry and exit of code blocks.
138 They must be saved and restored when returning to a block.
139*/
140struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400144 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100145 int u_scope_type;
146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 /* The following fields are dicts that map objects to
148 the index of them in co_XXX. The index is used as
149 the argument for opcodes that refer to those collections.
150 */
151 PyObject *u_consts; /* all constants */
152 PyObject *u_names; /* all names */
153 PyObject *u_varnames; /* local variables */
154 PyObject *u_cellvars; /* cell variables */
155 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Victor Stinnerf8e32212013-11-19 23:56:34 +0100159 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100160 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100161 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* Pointer to the most recently allocated block. By following b_list
163 members, you can reach all early allocated blocks. */
164 basicblock *u_blocks;
165 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 int u_nfblocks;
168 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 int u_firstlineno; /* the first lineno of the block */
171 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000172 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173};
174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000177The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000179managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000180
181Note that we don't track recursion levels during compilation - the
182task of detecting and rejecting excessive levels of nesting is
183handled by the symbol analysis pass.
184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185*/
186
187struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200188 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 struct symtable *c_st;
190 PyFutureFeatures *c_future; /* pointer to module's __future__ */
191 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
Georg Brandl8334fd92010-12-04 10:26:46 +0000193 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 int c_interactive; /* true if in interactive mode */
195 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100196 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
197 if this value is different from zero.
198 This can be used to temporarily visit
199 nodes without emitting bytecode to
200 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201
INADA Naokic2e16072018-11-26 21:23:22 +0900202 PyObject *c_const_cache; /* Python dict holding all constants,
203 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 struct compiler_unit *u; /* compiler state for current block */
205 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
206 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207};
208
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100209static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210static void compiler_free(struct compiler *);
211static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500212static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100214static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100215static int compiler_addop_j(struct compiler *, int, basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200217static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
219
220static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
221static int compiler_visit_stmt(struct compiler *, stmt_ty);
222static int compiler_visit_keyword(struct compiler *, keyword_ty);
223static int compiler_visit_expr(struct compiler *, expr_ty);
224static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700225static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200226static int compiler_subscript(struct compiler *, expr_ty);
227static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228
Andy Lester76d58772020-03-10 21:18:12 -0500229static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100230static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Mark Shannon8473cf82020-12-15 11:07:50 +0000231
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500233static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400234static int compiler_async_with(struct compiler *, stmt_ty, int);
235static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100236static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100237 asdl_expr_seq *args,
238 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500239static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400240static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000241
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700242static int compiler_sync_comprehension_generator(
243 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100244 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200245 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700246 expr_ty elt, expr_ty val, int type);
247
248static int compiler_async_comprehension_generator(
249 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100250 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200251 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700252 expr_ty elt, expr_ty val, int type);
253
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000255static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400257#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000260_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* Name mangling: __private becomes _classname__private.
263 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 PyObject *result;
265 size_t nlen, plen, ipriv;
266 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200268 PyUnicode_READ_CHAR(ident, 0) != '_' ||
269 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 Py_INCREF(ident);
271 return ident;
272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200273 nlen = PyUnicode_GET_LENGTH(ident);
274 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 The only time a name with a dot can occur is when
278 we are compiling an import statement that has a
279 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 TODO(jhylton): Decide whether we want to support
282 mangling of the module name, e.g. __M.X.
283 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200284 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
285 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
286 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Py_INCREF(ident);
288 return ident; /* Don't mangle __whatever__ */
289 }
290 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200291 ipriv = 0;
292 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
293 ipriv++;
294 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_INCREF(ident);
296 return ident; /* Don't mangle if class is just underscores */
297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200298 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000299
Antoine Pitrou55bff892013-04-06 21:21:04 +0200300 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
301 PyErr_SetString(PyExc_OverflowError,
302 "private identifier too large to be mangled");
303 return NULL;
304 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200306 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
307 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
308 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
309
310 result = PyUnicode_New(1 + nlen + plen, maxchar);
311 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200313 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
314 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200315 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
316 Py_DECREF(result);
317 return NULL;
318 }
319 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
320 Py_DECREF(result);
321 return NULL;
322 }
Victor Stinner8f825062012-04-27 13:55:39 +0200323 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200324 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000325}
326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327static int
328compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000331
INADA Naokic2e16072018-11-26 21:23:22 +0900332 c->c_const_cache = PyDict_New();
333 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900335 }
336
337 c->c_stack = PyList_New(0);
338 if (!c->c_stack) {
339 Py_CLEAR(c->c_const_cache);
340 return 0;
341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344}
345
346PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200347PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
348 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 struct compiler c;
351 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200352 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (!__doc__) {
356 __doc__ = PyUnicode_InternFromString("__doc__");
357 if (!__doc__)
358 return NULL;
359 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000360 if (!__annotations__) {
361 __annotations__ = PyUnicode_InternFromString("__annotations__");
362 if (!__annotations__)
363 return NULL;
364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (!compiler_init(&c))
366 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200367 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 c.c_filename = filename;
369 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200370 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c.c_future == NULL)
372 goto finally;
373 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 flags = &local_flags;
375 }
376 merged = c.c_future->ff_features | flags->cf_flags;
377 c.c_future->ff_features = merged;
378 flags->cf_flags = merged;
379 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200380 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100382 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383
Pablo Galindod112c602020-03-18 23:02:09 +0000384 _PyASTOptimizeState state;
385 state.optimize = c.c_optimize;
386 state.ff_features = merged;
387
388 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900389 goto finally;
390 }
391
Victor Stinner14e461d2013-08-26 22:28:21 +0200392 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (c.c_st == NULL) {
394 if (!PyErr_Occurred())
395 PyErr_SetString(PyExc_SystemError, "no symtable");
396 goto finally;
397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400
Thomas Wouters1175c432006-02-27 22:49:54 +0000401 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 compiler_free(&c);
403 assert(co || PyErr_Occurred());
404 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405}
406
407PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200408PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
409 int optimize, PyArena *arena)
410{
411 PyObject *filename;
412 PyCodeObject *co;
413 filename = PyUnicode_DecodeFSDefault(filename_str);
414 if (filename == NULL)
415 return NULL;
416 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
417 Py_DECREF(filename);
418 return co;
419
420}
421
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000422static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (c->c_st)
426 PySymtable_Free(c->c_st);
427 if (c->c_future)
428 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200429 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900430 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000432}
433
Guido van Rossum79f25d91997-04-29 20:08:16 +0000434static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 Py_ssize_t i, n;
438 PyObject *v, *k;
439 PyObject *dict = PyDict_New();
440 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 n = PyList_Size(list);
443 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100444 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (!v) {
446 Py_DECREF(dict);
447 return NULL;
448 }
449 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300450 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 Py_DECREF(v);
452 Py_DECREF(dict);
453 return NULL;
454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(v);
456 }
457 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458}
459
460/* Return new dict containing names from src that match scope(s).
461
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000462src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464values are integers, starting at offset and increasing by one for
465each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466*/
467
468static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100469dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700471 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500473 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 assert(offset >= 0);
476 if (dest == NULL)
477 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478
Meador Inge2ca63152012-07-18 14:20:11 -0500479 /* Sort the keys so that we have a deterministic order on the indexes
480 saved in the returned dictionary. These indexes are used as indexes
481 into the free and cell var storage. Therefore if they aren't
482 deterministic, then the generated bytecode is not deterministic.
483 */
484 sorted_keys = PyDict_Keys(src);
485 if (sorted_keys == NULL)
486 return NULL;
487 if (PyList_Sort(sorted_keys) != 0) {
488 Py_DECREF(sorted_keys);
489 return NULL;
490 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500491 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500492
493 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* XXX this should probably be a macro in symtable.h */
495 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500496 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200497 v = PyDict_GetItemWithError(src, k);
498 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 vi = PyLong_AS_LONG(v);
500 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300503 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500505 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_DECREF(dest);
507 return NULL;
508 }
509 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300510 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500511 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_DECREF(item);
513 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return NULL;
515 }
516 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 }
518 }
Meador Inge2ca63152012-07-18 14:20:11 -0500519 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000521}
522
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523static void
524compiler_unit_check(struct compiler_unit *u)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 basicblock *block;
527 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700528 assert((uintptr_t)block != 0xcbcbcbcbU);
529 assert((uintptr_t)block != 0xfbfbfbfbU);
530 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (block->b_instr != NULL) {
532 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100533 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 assert(block->b_ialloc >= block->b_iused);
535 }
536 else {
537 assert (block->b_iused == 0);
538 assert (block->b_ialloc == 0);
539 }
540 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541}
542
543static void
544compiler_unit_free(struct compiler_unit *u)
545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 compiler_unit_check(u);
549 b = u->u_blocks;
550 while (b != NULL) {
551 if (b->b_instr)
552 PyObject_Free((void *)b->b_instr);
553 next = b->b_list;
554 PyObject_Free((void *)b);
555 b = next;
556 }
557 Py_CLEAR(u->u_ste);
558 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400559 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 Py_CLEAR(u->u_consts);
561 Py_CLEAR(u->u_names);
562 Py_CLEAR(u->u_varnames);
563 Py_CLEAR(u->u_freevars);
564 Py_CLEAR(u->u_cellvars);
565 Py_CLEAR(u->u_private);
566 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567}
568
569static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100570compiler_enter_scope(struct compiler *c, identifier name,
571 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100574 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575
Andy Lester7668a8b2020-03-24 23:26:44 -0500576 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 struct compiler_unit));
578 if (!u) {
579 PyErr_NoMemory();
580 return 0;
581 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100582 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100584 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 u->u_kwonlyargcount = 0;
586 u->u_ste = PySymtable_Lookup(c->c_st, key);
587 if (!u->u_ste) {
588 compiler_unit_free(u);
589 return 0;
590 }
591 Py_INCREF(name);
592 u->u_name = name;
593 u->u_varnames = list2dict(u->u_ste->ste_varnames);
594 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
595 if (!u->u_varnames || !u->u_cellvars) {
596 compiler_unit_free(u);
597 return 0;
598 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500599 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000600 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500601 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300602 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500603 int res;
604 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200605 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500606 name = _PyUnicode_FromId(&PyId___class__);
607 if (!name) {
608 compiler_unit_free(u);
609 return 0;
610 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100611 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500612 if (res < 0) {
613 compiler_unit_free(u);
614 return 0;
615 }
616 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200619 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (!u->u_freevars) {
621 compiler_unit_free(u);
622 return 0;
623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 u->u_blocks = NULL;
626 u->u_nfblocks = 0;
627 u->u_firstlineno = lineno;
628 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000629 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 u->u_consts = PyDict_New();
631 if (!u->u_consts) {
632 compiler_unit_free(u);
633 return 0;
634 }
635 u->u_names = PyDict_New();
636 if (!u->u_names) {
637 compiler_unit_free(u);
638 return 0;
639 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 /* Push the old compiler_unit on the stack. */
644 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400645 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
647 Py_XDECREF(capsule);
648 compiler_unit_free(u);
649 return 0;
650 }
651 Py_DECREF(capsule);
652 u->u_private = c->u->u_private;
653 Py_XINCREF(u->u_private);
654 }
655 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100658
659 block = compiler_new_block(c);
660 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100662 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400664 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
665 if (!compiler_set_qualname(c))
666 return 0;
667 }
668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000672static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673compiler_exit_scope(struct compiler *c)
674{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100675 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 c->c_nestlevel--;
679 compiler_unit_free(c->u);
680 /* Restore c->u to the parent unit. */
681 n = PyList_GET_SIZE(c->c_stack) - 1;
682 if (n >= 0) {
683 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400684 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 assert(c->u);
686 /* we are deleting from a list so this really shouldn't fail */
687 if (PySequence_DelItem(c->c_stack, n) < 0)
688 Py_FatalError("compiler_exit_scope()");
689 compiler_unit_check(c->u);
690 }
691 else
692 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000693
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694}
695
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696static int
697compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100699 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400700 _Py_static_string(dot_locals, ".<locals>");
701 Py_ssize_t stack_size;
702 struct compiler_unit *u = c->u;
703 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100704
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400707 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400708 if (stack_size > 1) {
709 int scope, force_global = 0;
710 struct compiler_unit *parent;
711 PyObject *mangled, *capsule;
712
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400713 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400714 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400715 assert(parent);
716
Yury Selivanov75445082015-05-11 22:57:16 -0400717 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
718 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
719 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 assert(u->u_name);
721 mangled = _Py_Mangle(parent->u_private, u->u_name);
722 if (!mangled)
723 return 0;
724 scope = PyST_GetScope(parent->u_ste, mangled);
725 Py_DECREF(mangled);
726 assert(scope != GLOBAL_IMPLICIT);
727 if (scope == GLOBAL_EXPLICIT)
728 force_global = 1;
729 }
730
731 if (!force_global) {
732 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400733 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400734 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
735 dot_locals_str = _PyUnicode_FromId(&dot_locals);
736 if (dot_locals_str == NULL)
737 return 0;
738 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
739 if (base == NULL)
740 return 0;
741 }
742 else {
743 Py_INCREF(parent->u_qualname);
744 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400745 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100746 }
747 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400748
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400749 if (base != NULL) {
750 dot_str = _PyUnicode_FromId(&dot);
751 if (dot_str == NULL) {
752 Py_DECREF(base);
753 return 0;
754 }
755 name = PyUnicode_Concat(base, dot_str);
756 Py_DECREF(base);
757 if (name == NULL)
758 return 0;
759 PyUnicode_Append(&name, u->u_name);
760 if (name == NULL)
761 return 0;
762 }
763 else {
764 Py_INCREF(u->u_name);
765 name = u->u_name;
766 }
767 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100768
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400769 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100770}
771
Eric V. Smith235a6f02015-09-19 14:51:32 -0400772
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773/* Allocate a new block and return a pointer to it.
774 Returns NULL on error.
775*/
776
777static basicblock *
778compiler_new_block(struct compiler *c)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 basicblock *b;
781 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500784 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (b == NULL) {
786 PyErr_NoMemory();
787 return NULL;
788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 /* Extend the singly linked list of blocks with new block. */
790 b->b_list = u->u_blocks;
791 u->u_blocks = b;
792 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796compiler_next_block(struct compiler *c)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 basicblock *block = compiler_new_block(c);
799 if (block == NULL)
800 return NULL;
801 c->u->u_curblock->b_next = block;
802 c->u->u_curblock = block;
803 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000804}
805
806static basicblock *
807compiler_use_next_block(struct compiler *c, basicblock *block)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(block != NULL);
810 c->u->u_curblock->b_next = block;
811 c->u->u_curblock = block;
812 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813}
814
Mark Shannon5977a792020-12-02 13:31:40 +0000815static basicblock *
816compiler_copy_block(struct compiler *c, basicblock *block)
817{
818 /* Cannot copy a block if it has a fallthrough, since
819 * a block can only have one fallthrough predecessor.
820 */
821 assert(block->b_nofallthrough);
822 basicblock *result = compiler_next_block(c);
823 if (result == NULL) {
824 return NULL;
825 }
826 for (int i = 0; i < block->b_iused; i++) {
827 int n = compiler_next_instr(result);
828 if (n < 0) {
829 return NULL;
830 }
831 result->b_instr[n] = block->b_instr[i];
832 }
833 result->b_exit = block->b_exit;
834 return result;
835}
836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837/* Returns the offset of the next instruction in the current block's
838 b_instr array. Resizes the b_instr as necessary.
839 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000840*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841
842static int
Andy Lester76d58772020-03-10 21:18:12 -0500843compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 assert(b != NULL);
846 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500847 b->b_instr = (struct instr *)PyObject_Calloc(
848 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (b->b_instr == NULL) {
850 PyErr_NoMemory();
851 return -1;
852 }
853 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 }
855 else if (b->b_iused == b->b_ialloc) {
856 struct instr *tmp;
857 size_t oldsize, newsize;
858 oldsize = b->b_ialloc * sizeof(struct instr);
859 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000860
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700861 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyErr_NoMemory();
863 return -1;
864 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (newsize == 0) {
867 PyErr_NoMemory();
868 return -1;
869 }
870 b->b_ialloc <<= 1;
871 tmp = (struct instr *)PyObject_Realloc(
872 (void *)b->b_instr, newsize);
873 if (tmp == NULL) {
874 PyErr_NoMemory();
875 return -1;
876 }
877 b->b_instr = tmp;
878 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
879 }
880 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000881}
882
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200883/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000884
Christian Heimes2202f872008-02-06 14:31:34 +0000885 The line number is reset in the following cases:
886 - when entering a new scope
887 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200888 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200889 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200892#define SET_LOC(c, x) \
893 (c)->u->u_lineno = (x)->lineno; \
894 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200896/* Return the stack effect of opcode with argument oparg.
897
898 Some opcodes have different stack effect when jump to the target and
899 when not jump. The 'jump' parameter specifies the case:
900
901 * 0 -- when not jump
902 * 1 -- when jump
903 * -1 -- maximal
904 */
905/* XXX Make the stack effect of WITH_CLEANUP_START and
906 WITH_CLEANUP_FINISH deterministic. */
907static int
908stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300911 case NOP:
912 case EXTENDED_ARG:
913 return 0;
914
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200915 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case POP_TOP:
917 return -1;
918 case ROT_TWO:
919 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200920 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 return 0;
922 case DUP_TOP:
923 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000924 case DUP_TOP_TWO:
925 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200927 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case UNARY_POSITIVE:
929 case UNARY_NEGATIVE:
930 case UNARY_NOT:
931 case UNARY_INVERT:
932 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case SET_ADD:
935 case LIST_APPEND:
936 return -1;
937 case MAP_ADD:
938 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000939
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200940 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case BINARY_POWER:
942 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400943 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 case BINARY_MODULO:
945 case BINARY_ADD:
946 case BINARY_SUBTRACT:
947 case BINARY_SUBSCR:
948 case BINARY_FLOOR_DIVIDE:
949 case BINARY_TRUE_DIVIDE:
950 return -1;
951 case INPLACE_FLOOR_DIVIDE:
952 case INPLACE_TRUE_DIVIDE:
953 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 case INPLACE_ADD:
956 case INPLACE_SUBTRACT:
957 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400958 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 case INPLACE_MODULO:
960 return -1;
961 case STORE_SUBSCR:
962 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 case DELETE_SUBSCR:
964 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case BINARY_LSHIFT:
967 case BINARY_RSHIFT:
968 case BINARY_AND:
969 case BINARY_XOR:
970 case BINARY_OR:
971 return -1;
972 case INPLACE_POWER:
973 return -1;
974 case GET_ITER:
975 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case PRINT_EXPR:
978 return -1;
979 case LOAD_BUILD_CLASS:
980 return 1;
981 case INPLACE_LSHIFT:
982 case INPLACE_RSHIFT:
983 case INPLACE_AND:
984 case INPLACE_XOR:
985 case INPLACE_OR:
986 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200989 /* 1 in the normal flow.
990 * Restore the stack position and push 6 values before jumping to
991 * the handler if an exception be raised. */
992 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case RETURN_VALUE:
994 return -1;
995 case IMPORT_STAR:
996 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700997 case SETUP_ANNOTATIONS:
998 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case YIELD_VALUE:
1000 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05001001 case YIELD_FROM:
1002 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 case POP_BLOCK:
1004 return 0;
1005 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001006 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case STORE_NAME:
1009 return -1;
1010 case DELETE_NAME:
1011 return 0;
1012 case UNPACK_SEQUENCE:
1013 return oparg-1;
1014 case UNPACK_EX:
1015 return (oparg&0xFF) + (oparg>>8);
1016 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001017 /* -1 at end of iterator, 1 if continue iterating. */
1018 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case STORE_ATTR:
1021 return -2;
1022 case DELETE_ATTR:
1023 return -1;
1024 case STORE_GLOBAL:
1025 return -1;
1026 case DELETE_GLOBAL:
1027 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case LOAD_CONST:
1029 return 1;
1030 case LOAD_NAME:
1031 return 1;
1032 case BUILD_TUPLE:
1033 case BUILD_LIST:
1034 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001035 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 return 1-oparg;
1037 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001038 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001039 case BUILD_CONST_KEY_MAP:
1040 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case LOAD_ATTR:
1042 return 0;
1043 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001044 case IS_OP:
1045 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001047 case JUMP_IF_NOT_EXC_MATCH:
1048 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case IMPORT_NAME:
1050 return -1;
1051 case IMPORT_FROM:
1052 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001053
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001054 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 case JUMP_ABSOLUTE:
1057 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001059 case JUMP_IF_TRUE_OR_POP:
1060 case JUMP_IF_FALSE_OR_POP:
1061 return jump ? 0 : -1;
1062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 case POP_JUMP_IF_FALSE:
1064 case POP_JUMP_IF_TRUE:
1065 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case LOAD_GLOBAL:
1068 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001070 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001072 /* 0 in the normal flow.
1073 * Restore the stack position and push 6 values before jumping to
1074 * the handler if an exception be raised. */
1075 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001076 case RERAISE:
1077 return -3;
1078
1079 case WITH_EXCEPT_START:
1080 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 case LOAD_FAST:
1083 return 1;
1084 case STORE_FAST:
1085 return -1;
1086 case DELETE_FAST:
1087 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 case RAISE_VARARGS:
1090 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001091
1092 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001094 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001095 case CALL_METHOD:
1096 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001098 return -oparg-1;
1099 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001100 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001101 case MAKE_FUNCTION:
1102 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1103 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 case BUILD_SLICE:
1105 if (oparg == 3)
1106 return -2;
1107 else
1108 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001110 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 case LOAD_CLOSURE:
1112 return 1;
1113 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001114 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 return 1;
1116 case STORE_DEREF:
1117 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001118 case DELETE_DEREF:
1119 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001120
1121 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001122 case GET_AWAITABLE:
1123 return 0;
1124 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001125 /* 0 in the normal flow.
1126 * Restore the stack position to the position before the result
1127 * of __aenter__ and push 6 values before jumping to the handler
1128 * if an exception be raised. */
1129 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001130 case BEFORE_ASYNC_WITH:
1131 return 1;
1132 case GET_AITER:
1133 return 0;
1134 case GET_ANEXT:
1135 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001136 case GET_YIELD_FROM_ITER:
1137 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001138 case END_ASYNC_FOR:
1139 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001140 case FORMAT_VALUE:
1141 /* If there's a fmt_spec on the stack, we go from 2->1,
1142 else 1->1. */
1143 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001144 case LOAD_METHOD:
1145 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001146 case LOAD_ASSERTION_ERROR:
1147 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001148 case LIST_TO_TUPLE:
1149 return 0;
1150 case LIST_EXTEND:
1151 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001152 case DICT_MERGE:
1153 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001154 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001156 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 }
Larry Hastings3a907972013-11-23 14:49:22 -08001158 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159}
1160
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001161int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001162PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1163{
1164 return stack_effect(opcode, oparg, jump);
1165}
1166
1167int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001168PyCompile_OpcodeStackEffect(int opcode, int oparg)
1169{
1170 return stack_effect(opcode, oparg, -1);
1171}
1172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173/* Add an opcode with no argument.
1174 Returns 0 on failure, 1 on success.
1175*/
1176
1177static int
1178compiler_addop(struct compiler *c, int opcode)
1179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 basicblock *b;
1181 struct instr *i;
1182 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001183 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001184 if (c->c_do_not_emit_bytecode) {
1185 return 1;
1186 }
Andy Lester76d58772020-03-10 21:18:12 -05001187 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (off < 0)
1189 return 0;
1190 b = c->u->u_curblock;
1191 i = &b->b_instr[off];
1192 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001193 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (opcode == RETURN_VALUE)
1195 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001196 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198}
1199
Victor Stinnerf8e32212013-11-19 23:56:34 +01001200static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001201compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001203 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001206 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001208 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001210 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001211 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001212 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return -1;
1215 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001216 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 Py_DECREF(v);
1218 return -1;
1219 }
1220 Py_DECREF(v);
1221 }
1222 else
1223 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001224 return arg;
1225}
1226
INADA Naokic2e16072018-11-26 21:23:22 +09001227// Merge const *o* recursively and return constant key object.
1228static PyObject*
1229merge_consts_recursive(struct compiler *c, PyObject *o)
1230{
1231 // None and Ellipsis are singleton, and key is the singleton.
1232 // No need to merge object and key.
1233 if (o == Py_None || o == Py_Ellipsis) {
1234 Py_INCREF(o);
1235 return o;
1236 }
1237
1238 PyObject *key = _PyCode_ConstantKey(o);
1239 if (key == NULL) {
1240 return NULL;
1241 }
1242
1243 // t is borrowed reference
1244 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1245 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001246 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001247 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001248 Py_DECREF(key);
1249 return t;
1250 }
1251
INADA Naokif7e4d362018-11-29 00:58:46 +09001252 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001253 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001254 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001255 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001256 Py_ssize_t len = PyTuple_GET_SIZE(o);
1257 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001258 PyObject *item = PyTuple_GET_ITEM(o, i);
1259 PyObject *u = merge_consts_recursive(c, item);
1260 if (u == NULL) {
1261 Py_DECREF(key);
1262 return NULL;
1263 }
1264
1265 // See _PyCode_ConstantKey()
1266 PyObject *v; // borrowed
1267 if (PyTuple_CheckExact(u)) {
1268 v = PyTuple_GET_ITEM(u, 1);
1269 }
1270 else {
1271 v = u;
1272 }
1273 if (v != item) {
1274 Py_INCREF(v);
1275 PyTuple_SET_ITEM(o, i, v);
1276 Py_DECREF(item);
1277 }
1278
1279 Py_DECREF(u);
1280 }
1281 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001282 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001283 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001284 // constant keys.
1285 // See _PyCode_ConstantKey() for detail.
1286 assert(PyTuple_CheckExact(key));
1287 assert(PyTuple_GET_SIZE(key) == 2);
1288
1289 Py_ssize_t len = PySet_GET_SIZE(o);
1290 if (len == 0) { // empty frozenset should not be re-created.
1291 return key;
1292 }
1293 PyObject *tuple = PyTuple_New(len);
1294 if (tuple == NULL) {
1295 Py_DECREF(key);
1296 return NULL;
1297 }
1298 Py_ssize_t i = 0, pos = 0;
1299 PyObject *item;
1300 Py_hash_t hash;
1301 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1302 PyObject *k = merge_consts_recursive(c, item);
1303 if (k == NULL) {
1304 Py_DECREF(tuple);
1305 Py_DECREF(key);
1306 return NULL;
1307 }
1308 PyObject *u;
1309 if (PyTuple_CheckExact(k)) {
1310 u = PyTuple_GET_ITEM(k, 1);
1311 Py_INCREF(u);
1312 Py_DECREF(k);
1313 }
1314 else {
1315 u = k;
1316 }
1317 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1318 i++;
1319 }
1320
1321 // Instead of rewriting o, we create new frozenset and embed in the
1322 // key tuple. Caller should get merged frozenset from the key tuple.
1323 PyObject *new = PyFrozenSet_New(tuple);
1324 Py_DECREF(tuple);
1325 if (new == NULL) {
1326 Py_DECREF(key);
1327 return NULL;
1328 }
1329 assert(PyTuple_GET_ITEM(key, 1) == o);
1330 Py_DECREF(o);
1331 PyTuple_SET_ITEM(key, 1, new);
1332 }
INADA Naokic2e16072018-11-26 21:23:22 +09001333
1334 return key;
1335}
1336
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001337static Py_ssize_t
1338compiler_add_const(struct compiler *c, PyObject *o)
1339{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001340 if (c->c_do_not_emit_bytecode) {
1341 return 0;
1342 }
1343
INADA Naokic2e16072018-11-26 21:23:22 +09001344 PyObject *key = merge_consts_recursive(c, o);
1345 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001346 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001347 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001348
Andy Lester76d58772020-03-10 21:18:12 -05001349 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001350 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352}
1353
1354static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001355compiler_addop_load_const(struct compiler *c, PyObject *o)
1356{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001357 if (c->c_do_not_emit_bytecode) {
1358 return 1;
1359 }
1360
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001361 Py_ssize_t arg = compiler_add_const(c, o);
1362 if (arg < 0)
1363 return 0;
1364 return compiler_addop_i(c, LOAD_CONST, arg);
1365}
1366
1367static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001371 if (c->c_do_not_emit_bytecode) {
1372 return 1;
1373 }
1374
Andy Lester76d58772020-03-10 21:18:12 -05001375 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001377 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378 return compiler_addop_i(c, opcode, arg);
1379}
1380
1381static int
1382compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001385 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001386
1387 if (c->c_do_not_emit_bytecode) {
1388 return 1;
1389 }
1390
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1392 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001393 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001394 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395 Py_DECREF(mangled);
1396 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001397 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 return compiler_addop_i(c, opcode, arg);
1399}
1400
1401/* Add an opcode with an integer argument.
1402 Returns 0 on failure, 1 on success.
1403*/
1404
1405static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001406compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 struct instr *i;
1409 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001410
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001411 if (c->c_do_not_emit_bytecode) {
1412 return 1;
1413 }
1414
Victor Stinner2ad474b2016-03-01 23:34:47 +01001415 /* oparg value is unsigned, but a signed C int is usually used to store
1416 it in the C code (like Python/ceval.c).
1417
1418 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1419
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001420 The argument of a concrete bytecode instruction is limited to 8-bit.
1421 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1422 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001423 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001424
Andy Lester76d58772020-03-10 21:18:12 -05001425 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (off < 0)
1427 return 0;
1428 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001429 i->i_opcode = opcode;
1430 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001431 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433}
1434
Mark Shannon28b75c82020-12-23 11:43:10 +00001435static int add_jump_to_block(basicblock *b, int opcode, int lineno, basicblock *target)
1436{
1437 assert(HAS_ARG(opcode));
1438 assert(b != NULL);
1439 assert(target != NULL);
1440
1441 int off = compiler_next_instr(b);
1442 struct instr *i = &b->b_instr[off];
1443 if (off < 0) {
1444 return 0;
1445 }
1446 i->i_opcode = opcode;
1447 i->i_target = target;
1448 i->i_lineno = lineno;
1449 return 1;
1450}
1451
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001452static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001453compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001454{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001455 if (c->c_do_not_emit_bytecode) {
1456 return 1;
1457 }
Mark Shannon28b75c82020-12-23 11:43:10 +00001458 return add_jump_to_block(c->u->u_curblock, opcode, c->u->u_lineno, b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459}
1460
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001461/* NEXT_BLOCK() creates an implicit jump from the current block
1462 to the new block.
1463
1464 The returns inside this macro make it impossible to decref objects
1465 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001467#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (compiler_next_block((C)) == NULL) \
1469 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470}
1471
1472#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (!compiler_addop((C), (OP))) \
1474 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475}
1476
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001477#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 if (!compiler_addop((C), (OP))) { \
1479 compiler_exit_scope(c); \
1480 return 0; \
1481 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001482}
1483
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001484#define ADDOP_LOAD_CONST(C, O) { \
1485 if (!compiler_addop_load_const((C), (O))) \
1486 return 0; \
1487}
1488
1489/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1490#define ADDOP_LOAD_CONST_NEW(C, O) { \
1491 PyObject *__new_const = (O); \
1492 if (__new_const == NULL) { \
1493 return 0; \
1494 } \
1495 if (!compiler_addop_load_const((C), __new_const)) { \
1496 Py_DECREF(__new_const); \
1497 return 0; \
1498 } \
1499 Py_DECREF(__new_const); \
1500}
1501
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001502#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1504 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001505}
1506
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001507/* Same as ADDOP_O, but steals a reference. */
1508#define ADDOP_N(C, OP, O, TYPE) { \
1509 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1510 Py_DECREF((O)); \
1511 return 0; \
1512 } \
1513 Py_DECREF((O)); \
1514}
1515
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001516#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1518 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519}
1520
1521#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (!compiler_addop_i((C), (OP), (O))) \
1523 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524}
1525
Mark Shannon582aaf12020-08-04 17:30:11 +01001526#define ADDOP_JUMP(C, OP, O) { \
1527 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529}
1530
Mark Shannon9af0e472020-01-14 10:12:45 +00001531#define ADDOP_COMPARE(C, CMP) { \
1532 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1533 return 0; \
1534}
1535
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001536/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1537 the ASDL name to synthesize the name of the C type and the visit function.
1538*/
1539
1540#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 if (!compiler_visit_ ## TYPE((C), (V))) \
1542 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001543}
1544
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001545#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (!compiler_visit_ ## TYPE((C), (V))) { \
1547 compiler_exit_scope(c); \
1548 return 0; \
1549 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001550}
1551
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001552#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 if (!compiler_visit_slice((C), (V), (CTX))) \
1554 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001555}
1556
1557#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001559 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1561 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1562 if (!compiler_visit_ ## TYPE((C), elt)) \
1563 return 0; \
1564 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565}
1566
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001567#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001569 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1571 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1572 if (!compiler_visit_ ## TYPE((C), elt)) { \
1573 compiler_exit_scope(c); \
1574 return 0; \
1575 } \
1576 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001577}
1578
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001579/* Search if variable annotations are present statically in a block. */
1580
1581static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001582find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001583{
1584 int i, j, res = 0;
1585 stmt_ty st;
1586
1587 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1588 st = (stmt_ty)asdl_seq_GET(stmts, i);
1589 switch (st->kind) {
1590 case AnnAssign_kind:
1591 return 1;
1592 case For_kind:
1593 res = find_ann(st->v.For.body) ||
1594 find_ann(st->v.For.orelse);
1595 break;
1596 case AsyncFor_kind:
1597 res = find_ann(st->v.AsyncFor.body) ||
1598 find_ann(st->v.AsyncFor.orelse);
1599 break;
1600 case While_kind:
1601 res = find_ann(st->v.While.body) ||
1602 find_ann(st->v.While.orelse);
1603 break;
1604 case If_kind:
1605 res = find_ann(st->v.If.body) ||
1606 find_ann(st->v.If.orelse);
1607 break;
1608 case With_kind:
1609 res = find_ann(st->v.With.body);
1610 break;
1611 case AsyncWith_kind:
1612 res = find_ann(st->v.AsyncWith.body);
1613 break;
1614 case Try_kind:
1615 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1616 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1617 st->v.Try.handlers, j);
1618 if (find_ann(handler->v.ExceptHandler.body)) {
1619 return 1;
1620 }
1621 }
1622 res = find_ann(st->v.Try.body) ||
1623 find_ann(st->v.Try.finalbody) ||
1624 find_ann(st->v.Try.orelse);
1625 break;
1626 default:
1627 res = 0;
1628 }
1629 if (res) {
1630 break;
1631 }
1632 }
1633 return res;
1634}
1635
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001636/*
1637 * Frame block handling functions
1638 */
1639
1640static int
1641compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001642 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001643{
1644 struct fblockinfo *f;
1645 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001646 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001647 }
1648 f = &c->u->u_fblock[c->u->u_nfblocks++];
1649 f->fb_type = t;
1650 f->fb_block = b;
1651 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001652 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001653 return 1;
1654}
1655
1656static void
1657compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1658{
1659 struct compiler_unit *u = c->u;
1660 assert(u->u_nfblocks > 0);
1661 u->u_nfblocks--;
1662 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1663 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1664}
1665
Mark Shannonfee55262019-11-21 09:11:43 +00001666static int
1667compiler_call_exit_with_nones(struct compiler *c) {
1668 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1669 ADDOP(c, DUP_TOP);
1670 ADDOP(c, DUP_TOP);
1671 ADDOP_I(c, CALL_FUNCTION, 3);
1672 return 1;
1673}
1674
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001675/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001676 * popping the blocks will be restored afterwards, unless another
1677 * return, break or continue is found. In which case, the TOS will
1678 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001679 */
1680static int
1681compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1682 int preserve_tos)
1683{
1684 switch (info->fb_type) {
1685 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001686 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001687 return 1;
1688
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001689 case FOR_LOOP:
1690 /* Pop the iterator */
1691 if (preserve_tos) {
1692 ADDOP(c, ROT_TWO);
1693 }
1694 ADDOP(c, POP_TOP);
1695 return 1;
1696
Mark Shannon02d126a2020-09-25 14:04:19 +01001697 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001698 ADDOP(c, POP_BLOCK);
1699 return 1;
1700
1701 case FINALLY_TRY:
Mark Shannon5274b682020-12-16 13:07:01 +00001702 /* This POP_BLOCK gets the line number of the unwinding statement */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001703 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001704 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001705 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1706 return 0;
1707 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001708 }
Mark Shannon5274b682020-12-16 13:07:01 +00001709 /* Emit the finally block */
Mark Shannonfee55262019-11-21 09:11:43 +00001710 VISIT_SEQ(c, stmt, info->fb_datum);
1711 if (preserve_tos) {
1712 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001713 }
Mark Shannon5274b682020-12-16 13:07:01 +00001714 /* The finally block should appear to execute after the
1715 * statement causing the unwinding, so make the unwinding
1716 * instruction artificial */
1717 c->u->u_lineno = -1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001718 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001719
Mark Shannonfee55262019-11-21 09:11:43 +00001720 case FINALLY_END:
1721 if (preserve_tos) {
1722 ADDOP(c, ROT_FOUR);
1723 }
1724 ADDOP(c, POP_TOP);
1725 ADDOP(c, POP_TOP);
1726 ADDOP(c, POP_TOP);
1727 if (preserve_tos) {
1728 ADDOP(c, ROT_FOUR);
1729 }
1730 ADDOP(c, POP_EXCEPT);
1731 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001732
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001733 case WITH:
1734 case ASYNC_WITH:
1735 ADDOP(c, POP_BLOCK);
1736 if (preserve_tos) {
1737 ADDOP(c, ROT_TWO);
1738 }
Mark Shannonfee55262019-11-21 09:11:43 +00001739 if(!compiler_call_exit_with_nones(c)) {
1740 return 0;
1741 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001742 if (info->fb_type == ASYNC_WITH) {
1743 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001744 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001745 ADDOP(c, YIELD_FROM);
1746 }
Mark Shannonfee55262019-11-21 09:11:43 +00001747 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001748 return 1;
1749
1750 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001751 if (info->fb_datum) {
1752 ADDOP(c, POP_BLOCK);
1753 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001754 if (preserve_tos) {
1755 ADDOP(c, ROT_FOUR);
1756 }
Mark Shannonfee55262019-11-21 09:11:43 +00001757 ADDOP(c, POP_EXCEPT);
1758 if (info->fb_datum) {
1759 ADDOP_LOAD_CONST(c, Py_None);
1760 compiler_nameop(c, info->fb_datum, Store);
1761 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001762 }
Mark Shannonfee55262019-11-21 09:11:43 +00001763 return 1;
1764
1765 case POP_VALUE:
1766 if (preserve_tos) {
1767 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001768 }
Mark Shannonfee55262019-11-21 09:11:43 +00001769 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001770 return 1;
1771 }
1772 Py_UNREACHABLE();
1773}
1774
Mark Shannonfee55262019-11-21 09:11:43 +00001775/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1776static int
1777compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1778 if (c->u->u_nfblocks == 0) {
1779 return 1;
1780 }
1781 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1782 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1783 *loop = top;
1784 return 1;
1785 }
1786 struct fblockinfo copy = *top;
1787 c->u->u_nfblocks--;
1788 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1789 return 0;
1790 }
1791 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1792 return 0;
1793 }
1794 c->u->u_fblock[c->u->u_nfblocks] = copy;
1795 c->u->u_nfblocks++;
1796 return 1;
1797}
1798
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001799/* Compile a sequence of statements, checking for a docstring
1800 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801
1802static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001803compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001805 int i = 0;
1806 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001807 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001808
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001809 /* Set current line number to the line number of first statement.
1810 This way line number for SETUP_ANNOTATIONS will always
1811 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301812 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001813 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001814 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001815 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001816 }
1817 /* Every annotated class and module should have __annotations__. */
1818 if (find_ann(stmts)) {
1819 ADDOP(c, SETUP_ANNOTATIONS);
1820 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001821 if (!asdl_seq_LEN(stmts))
1822 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001823 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001824 if (c->c_optimize < 2) {
1825 docstring = _PyAST_GetDocString(stmts);
1826 if (docstring) {
1827 i = 1;
1828 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1829 assert(st->kind == Expr_kind);
1830 VISIT(c, expr, st->v.Expr.value);
1831 if (!compiler_nameop(c, __doc__, Store))
1832 return 0;
1833 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001835 for (; i < asdl_seq_LEN(stmts); i++)
1836 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838}
1839
1840static PyCodeObject *
1841compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyCodeObject *co;
1844 int addNone = 1;
1845 static PyObject *module;
1846 if (!module) {
1847 module = PyUnicode_InternFromString("<module>");
1848 if (!module)
1849 return NULL;
1850 }
1851 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001852 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 return NULL;
1854 switch (mod->kind) {
1855 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001856 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 compiler_exit_scope(c);
1858 return 0;
1859 }
1860 break;
1861 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001862 if (find_ann(mod->v.Interactive.body)) {
1863 ADDOP(c, SETUP_ANNOTATIONS);
1864 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001866 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 break;
1868 case Expression_kind:
1869 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1870 addNone = 0;
1871 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 default:
1873 PyErr_Format(PyExc_SystemError,
1874 "module kind %d should not be possible",
1875 mod->kind);
1876 return 0;
1877 }
1878 co = assemble(c, addNone);
1879 compiler_exit_scope(c);
1880 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001881}
1882
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883/* The test for LOCAL must come before the test for FREE in order to
1884 handle classes where name is both local and free. The local var is
1885 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001886*/
1887
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888static int
1889get_ref_type(struct compiler *c, PyObject *name)
1890{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001891 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001892 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001893 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001894 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001895 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001897 _Py_FatalErrorFormat(__func__,
1898 "unknown scope for %.100s in %.100s(%s)\n"
1899 "symbols: %s\nlocals: %s\nglobals: %s",
1900 PyUnicode_AsUTF8(name),
1901 PyUnicode_AsUTF8(c->u->u_name),
1902 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1903 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1904 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1905 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909}
1910
1911static int
1912compiler_lookup_arg(PyObject *dict, PyObject *name)
1913{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001914 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001915 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001917 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001918 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919}
1920
1921static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001922compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001924 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001925 if (qualname == NULL)
1926 qualname = co->co_name;
1927
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001928 if (free) {
1929 for (i = 0; i < free; ++i) {
1930 /* Bypass com_addop_varname because it will generate
1931 LOAD_DEREF but LOAD_CLOSURE is needed.
1932 */
1933 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1934 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001935
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001936 /* Special case: If a class contains a method with a
1937 free variable that has the same name as a method,
1938 the name will be considered free *and* local in the
1939 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001940 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 */
1942 reftype = get_ref_type(c, name);
1943 if (reftype == CELL)
1944 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1945 else /* (reftype == FREE) */
1946 arg = compiler_lookup_arg(c->u->u_freevars, name);
1947 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001948 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001949 "lookup %s in %s %d %d\n"
1950 "freevars of %s: %s\n",
1951 PyUnicode_AsUTF8(PyObject_Repr(name)),
1952 PyUnicode_AsUTF8(c->u->u_name),
1953 reftype, arg,
1954 PyUnicode_AsUTF8(co->co_name),
1955 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001956 }
1957 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001959 flags |= 0x08;
1960 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001962 ADDOP_LOAD_CONST(c, (PyObject*)co);
1963 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001964 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001966}
1967
1968static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001969compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (!decos)
1974 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1977 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1978 }
1979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001980}
1981
1982static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001983compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1984 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001985{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001986 /* Push a dict of keyword-only default values.
1987
1988 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1989 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001990 int i;
1991 PyObject *keys = NULL;
1992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1994 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1995 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1996 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001997 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001998 if (!mangled) {
1999 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002001 if (keys == NULL) {
2002 keys = PyList_New(1);
2003 if (keys == NULL) {
2004 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002005 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002006 }
2007 PyList_SET_ITEM(keys, 0, mangled);
2008 }
2009 else {
2010 int res = PyList_Append(keys, mangled);
2011 Py_DECREF(mangled);
2012 if (res == -1) {
2013 goto error;
2014 }
2015 }
2016 if (!compiler_visit_expr(c, default_)) {
2017 goto error;
2018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 }
2020 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002021 if (keys != NULL) {
2022 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2023 PyObject *keys_tuple = PyList_AsTuple(keys);
2024 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002025 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002026 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002027 assert(default_count > 0);
2028 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002029 }
2030 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002031 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002032 }
2033
2034error:
2035 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002036 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002037}
2038
2039static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002040compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2041{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002042 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002043 return 1;
2044}
2045
2046static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002047compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002048 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002051 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002052 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002053 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002054
2055 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002056 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002057 VISIT(c, annexpr, annotation);
2058 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002060 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002061}
2062
2063static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002064compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002065 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002066{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002067 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 for (i = 0; i < asdl_seq_LEN(args); i++) {
2069 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002070 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 c,
2072 arg->arg,
2073 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002074 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002075 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002077 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002078}
2079
2080static int
2081compiler_visit_annotations(struct compiler *c, arguments_ty args,
2082 expr_ty returns)
2083{
Yurii Karabas73019792020-11-25 12:43:18 +02002084 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002085 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002086
Yurii Karabas73019792020-11-25 12:43:18 +02002087 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 */
2089 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002090 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002091
Yurii Karabas73019792020-11-25 12:43:18 +02002092 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2093 return 0;
2094 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2095 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002096 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002097 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002098 args->vararg->annotation, &annotations_len))
2099 return 0;
2100 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2101 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002102 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002103 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002104 args->kwarg->annotation, &annotations_len))
2105 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (!return_str) {
2108 return_str = PyUnicode_InternFromString("return");
2109 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002110 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 }
Yurii Karabas73019792020-11-25 12:43:18 +02002112 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2113 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 }
2115
Yurii Karabas73019792020-11-25 12:43:18 +02002116 if (annotations_len) {
2117 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002118 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002120
Yurii Karabas73019792020-11-25 12:43:18 +02002121 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002122}
2123
2124static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002125compiler_visit_defaults(struct compiler *c, arguments_ty args)
2126{
2127 VISIT_SEQ(c, expr, args->defaults);
2128 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2129 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002130}
2131
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002132static Py_ssize_t
2133compiler_default_arguments(struct compiler *c, arguments_ty args)
2134{
2135 Py_ssize_t funcflags = 0;
2136 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002137 if (!compiler_visit_defaults(c, args))
2138 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002139 funcflags |= 0x01;
2140 }
2141 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002142 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002143 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002144 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002145 return -1;
2146 }
2147 else if (res > 0) {
2148 funcflags |= 0x02;
2149 }
2150 }
2151 return funcflags;
2152}
2153
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002154static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002155forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2156{
2157
2158 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2159 compiler_error(c, "cannot assign to __debug__");
2160 return 1;
2161 }
2162 return 0;
2163}
2164
2165static int
2166compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2167{
2168 if (arg != NULL) {
2169 if (forbidden_name(c, arg->arg, Store))
2170 return 0;
2171 }
2172 return 1;
2173}
2174
2175static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002176compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002177{
2178 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002179 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002180 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2181 return 0;
2182 }
2183 }
2184 return 1;
2185}
2186
2187static int
2188compiler_check_debug_args(struct compiler *c, arguments_ty args)
2189{
2190 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2191 return 0;
2192 if (!compiler_check_debug_args_seq(c, args->args))
2193 return 0;
2194 if (!compiler_check_debug_one_arg(c, args->vararg))
2195 return 0;
2196 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2197 return 0;
2198 if (!compiler_check_debug_one_arg(c, args->kwarg))
2199 return 0;
2200 return 1;
2201}
2202
2203static int
Yury Selivanov75445082015-05-11 22:57:16 -04002204compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002207 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002208 arguments_ty args;
2209 expr_ty returns;
2210 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002211 asdl_expr_seq* decos;
2212 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002213 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002214 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002215 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002216 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002217
Yury Selivanov75445082015-05-11 22:57:16 -04002218 if (is_async) {
2219 assert(s->kind == AsyncFunctionDef_kind);
2220
2221 args = s->v.AsyncFunctionDef.args;
2222 returns = s->v.AsyncFunctionDef.returns;
2223 decos = s->v.AsyncFunctionDef.decorator_list;
2224 name = s->v.AsyncFunctionDef.name;
2225 body = s->v.AsyncFunctionDef.body;
2226
2227 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2228 } else {
2229 assert(s->kind == FunctionDef_kind);
2230
2231 args = s->v.FunctionDef.args;
2232 returns = s->v.FunctionDef.returns;
2233 decos = s->v.FunctionDef.decorator_list;
2234 name = s->v.FunctionDef.name;
2235 body = s->v.FunctionDef.body;
2236
2237 scope_type = COMPILER_SCOPE_FUNCTION;
2238 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002239
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002240 if (!compiler_check_debug_args(c, args))
2241 return 0;
2242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (!compiler_decorators(c, decos))
2244 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002245
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002246 firstlineno = s->lineno;
2247 if (asdl_seq_LEN(decos)) {
2248 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2249 }
2250
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002251 funcflags = compiler_default_arguments(c, args);
2252 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002254 }
2255
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002256 annotations = compiler_visit_annotations(c, args, returns);
2257 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002258 return 0;
2259 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002260 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002261 funcflags |= 0x04;
2262 }
2263
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002264 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002265 return 0;
2266 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002267
INADA Naokicb41b272017-02-23 00:31:59 +09002268 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002269 if (c->c_optimize < 2) {
2270 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002271 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002272 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 compiler_exit_scope(c);
2274 return 0;
2275 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002278 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002280 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002281 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002282 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002284 qualname = c->u->u_qualname;
2285 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002287 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002288 Py_XDECREF(qualname);
2289 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002291 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002293 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002294 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 /* decorators */
2298 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2299 ADDOP_I(c, CALL_FUNCTION, 1);
2300 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301
Yury Selivanov75445082015-05-11 22:57:16 -04002302 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303}
2304
2305static int
2306compiler_class(struct compiler *c, stmt_ty s)
2307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 PyCodeObject *co;
2309 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002310 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002311 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 if (!compiler_decorators(c, decos))
2314 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002315
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002316 firstlineno = s->lineno;
2317 if (asdl_seq_LEN(decos)) {
2318 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2319 }
2320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 /* ultimately generate code for:
2322 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2323 where:
2324 <func> is a function/closure created from the class body;
2325 it has a single argument (__locals__) where the dict
2326 (or MutableSequence) representing the locals is passed
2327 <name> is the class name
2328 <bases> is the positional arguments and *varargs argument
2329 <keywords> is the keyword arguments and **kwds argument
2330 This borrows from compiler_call.
2331 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002334 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002335 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 return 0;
2337 /* this block represents what we do in the new scope */
2338 {
2339 /* use the class name for name mangling */
2340 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002341 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* load (global) __name__ ... */
2343 str = PyUnicode_InternFromString("__name__");
2344 if (!str || !compiler_nameop(c, str, Load)) {
2345 Py_XDECREF(str);
2346 compiler_exit_scope(c);
2347 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 Py_DECREF(str);
2350 /* ... and store it as __module__ */
2351 str = PyUnicode_InternFromString("__module__");
2352 if (!str || !compiler_nameop(c, str, Store)) {
2353 Py_XDECREF(str);
2354 compiler_exit_scope(c);
2355 return 0;
2356 }
2357 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002358 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002359 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002360 str = PyUnicode_InternFromString("__qualname__");
2361 if (!str || !compiler_nameop(c, str, Store)) {
2362 Py_XDECREF(str);
2363 compiler_exit_scope(c);
2364 return 0;
2365 }
2366 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002368 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 compiler_exit_scope(c);
2370 return 0;
2371 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002372 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002373 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002374 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002375 str = PyUnicode_InternFromString("__class__");
2376 if (str == NULL) {
2377 compiler_exit_scope(c);
2378 return 0;
2379 }
2380 i = compiler_lookup_arg(c->u->u_cellvars, str);
2381 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002382 if (i < 0) {
2383 compiler_exit_scope(c);
2384 return 0;
2385 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002386 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002389 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002390 str = PyUnicode_InternFromString("__classcell__");
2391 if (!str || !compiler_nameop(c, str, Store)) {
2392 Py_XDECREF(str);
2393 compiler_exit_scope(c);
2394 return 0;
2395 }
2396 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002398 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002399 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002400 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002401 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002402 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002403 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* create the code object */
2405 co = assemble(c, 1);
2406 }
2407 /* leave the new scope */
2408 compiler_exit_scope(c);
2409 if (co == NULL)
2410 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 /* 2. load the 'build_class' function */
2413 ADDOP(c, LOAD_BUILD_CLASS);
2414
2415 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002416 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 Py_DECREF(co);
2418
2419 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002420 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421
2422 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002423 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 return 0;
2425
2426 /* 6. apply decorators */
2427 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2428 ADDOP_I(c, CALL_FUNCTION, 1);
2429 }
2430
2431 /* 7. store into <name> */
2432 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2433 return 0;
2434 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002435}
2436
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002437/* Return 0 if the expression is a constant value except named singletons.
2438 Return 1 otherwise. */
2439static int
2440check_is_arg(expr_ty e)
2441{
2442 if (e->kind != Constant_kind) {
2443 return 1;
2444 }
2445 PyObject *value = e->v.Constant.value;
2446 return (value == Py_None
2447 || value == Py_False
2448 || value == Py_True
2449 || value == Py_Ellipsis);
2450}
2451
2452/* Check operands of identity chacks ("is" and "is not").
2453 Emit a warning if any operand is a constant except named singletons.
2454 Return 0 on error.
2455 */
2456static int
2457check_compare(struct compiler *c, expr_ty e)
2458{
2459 Py_ssize_t i, n;
2460 int left = check_is_arg(e->v.Compare.left);
2461 n = asdl_seq_LEN(e->v.Compare.ops);
2462 for (i = 0; i < n; i++) {
2463 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2464 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2465 if (op == Is || op == IsNot) {
2466 if (!right || !left) {
2467 const char *msg = (op == Is)
2468 ? "\"is\" with a literal. Did you mean \"==\"?"
2469 : "\"is not\" with a literal. Did you mean \"!=\"?";
2470 return compiler_warn(c, msg);
2471 }
2472 }
2473 left = right;
2474 }
2475 return 1;
2476}
2477
Mark Shannon9af0e472020-01-14 10:12:45 +00002478static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002479{
Mark Shannon9af0e472020-01-14 10:12:45 +00002480 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002481 switch (op) {
2482 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002483 cmp = Py_EQ;
2484 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002486 cmp = Py_NE;
2487 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002488 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002489 cmp = Py_LT;
2490 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002491 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002492 cmp = Py_LE;
2493 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002494 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002495 cmp = Py_GT;
2496 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002497 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002498 cmp = Py_GE;
2499 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002500 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002501 ADDOP_I(c, IS_OP, 0);
2502 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002503 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002504 ADDOP_I(c, IS_OP, 1);
2505 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002506 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002507 ADDOP_I(c, CONTAINS_OP, 0);
2508 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002509 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002510 ADDOP_I(c, CONTAINS_OP, 1);
2511 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002512 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002513 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002514 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002515 ADDOP_I(c, COMPARE_OP, cmp);
2516 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002517}
2518
Mark Shannon9af0e472020-01-14 10:12:45 +00002519
2520
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002521static int
2522compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2523{
2524 switch (e->kind) {
2525 case UnaryOp_kind:
2526 if (e->v.UnaryOp.op == Not)
2527 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2528 /* fallback to general implementation */
2529 break;
2530 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002531 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002532 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2533 assert(n >= 0);
2534 int cond2 = e->v.BoolOp.op == Or;
2535 basicblock *next2 = next;
2536 if (!cond2 != !cond) {
2537 next2 = compiler_new_block(c);
2538 if (next2 == NULL)
2539 return 0;
2540 }
2541 for (i = 0; i < n; ++i) {
2542 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2543 return 0;
2544 }
2545 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2546 return 0;
2547 if (next2 != next)
2548 compiler_use_next_block(c, next2);
2549 return 1;
2550 }
2551 case IfExp_kind: {
2552 basicblock *end, *next2;
2553 end = compiler_new_block(c);
2554 if (end == NULL)
2555 return 0;
2556 next2 = compiler_new_block(c);
2557 if (next2 == NULL)
2558 return 0;
2559 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2560 return 0;
2561 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2562 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002563 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002564 compiler_use_next_block(c, next2);
2565 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2566 return 0;
2567 compiler_use_next_block(c, end);
2568 return 1;
2569 }
2570 case Compare_kind: {
2571 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2572 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002573 if (!check_compare(c, e)) {
2574 return 0;
2575 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002576 basicblock *cleanup = compiler_new_block(c);
2577 if (cleanup == NULL)
2578 return 0;
2579 VISIT(c, expr, e->v.Compare.left);
2580 for (i = 0; i < n; i++) {
2581 VISIT(c, expr,
2582 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2583 ADDOP(c, DUP_TOP);
2584 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002585 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002586 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002587 NEXT_BLOCK(c);
2588 }
2589 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002590 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002591 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002592 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002593 basicblock *end = compiler_new_block(c);
2594 if (end == NULL)
2595 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002596 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002597 compiler_use_next_block(c, cleanup);
2598 ADDOP(c, POP_TOP);
2599 if (!cond) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002600 ADDOP_JUMP(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002601 }
2602 compiler_use_next_block(c, end);
2603 return 1;
2604 }
2605 /* fallback to general implementation */
2606 break;
2607 }
2608 default:
2609 /* fallback to general implementation */
2610 break;
2611 }
2612
2613 /* general implementation */
2614 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002615 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002616 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002617 return 1;
2618}
2619
2620static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002621compiler_ifexp(struct compiler *c, expr_ty e)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 basicblock *end, *next;
2624
2625 assert(e->kind == IfExp_kind);
2626 end = compiler_new_block(c);
2627 if (end == NULL)
2628 return 0;
2629 next = compiler_new_block(c);
2630 if (next == NULL)
2631 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002632 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2633 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002635 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 compiler_use_next_block(c, next);
2637 VISIT(c, expr, e->v.IfExp.orelse);
2638 compiler_use_next_block(c, end);
2639 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002640}
2641
2642static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002643compiler_lambda(struct compiler *c, expr_ty e)
2644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002646 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002648 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 arguments_ty args = e->v.Lambda.args;
2650 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002651
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002652 if (!compiler_check_debug_args(c, args))
2653 return 0;
2654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 if (!name) {
2656 name = PyUnicode_InternFromString("<lambda>");
2657 if (!name)
2658 return 0;
2659 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002660
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002661 funcflags = compiler_default_arguments(c, args);
2662 if (funcflags == -1) {
2663 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002665
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002666 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002667 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 /* Make None the first constant, so the lambda can't have a
2671 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002672 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002676 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2678 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2679 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002680 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 }
2682 else {
2683 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002684 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002686 qualname = c->u->u_qualname;
2687 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002689 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002691
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002692 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002693 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 Py_DECREF(co);
2695
2696 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002697}
2698
2699static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002700compiler_if(struct compiler *c, stmt_ty s)
2701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 assert(s->kind == If_kind);
2704 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002705 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002707 }
2708 if (asdl_seq_LEN(s->v.If.orelse)) {
2709 next = compiler_new_block(c);
2710 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002711 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002712 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002713 }
2714 else {
2715 next = end;
2716 }
2717 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2718 return 0;
2719 }
2720 VISIT_SEQ(c, stmt, s->v.If.body);
2721 if (asdl_seq_LEN(s->v.If.orelse)) {
2722 ADDOP_JUMP(c, JUMP_FORWARD, end);
2723 compiler_use_next_block(c, next);
2724 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 }
2726 compiler_use_next_block(c, end);
2727 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002728}
2729
2730static int
2731compiler_for(struct compiler *c, stmt_ty s)
2732{
Mark Shannon5977a792020-12-02 13:31:40 +00002733 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002736 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 cleanup = compiler_new_block(c);
2738 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002739 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002741 }
2742 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002744 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 VISIT(c, expr, s->v.For.iter);
2746 ADDOP(c, GET_ITER);
2747 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002748 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002749 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 VISIT(c, expr, s->v.For.target);
2751 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002752 /* Mark jump as artificial */
2753 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002754 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002756
2757 compiler_pop_fblock(c, FOR_LOOP, start);
2758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 VISIT_SEQ(c, stmt, s->v.For.orelse);
2760 compiler_use_next_block(c, end);
2761 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002762}
2763
Yury Selivanov75445082015-05-11 22:57:16 -04002764
2765static int
2766compiler_async_for(struct compiler *c, stmt_ty s)
2767{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002768 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002769 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002770 c->u->u_ste->ste_coroutine = 1;
2771 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002772 return compiler_error(c, "'async for' outside async function");
2773 }
2774
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002775 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002776 except = compiler_new_block(c);
2777 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002778
Mark Shannonfee55262019-11-21 09:11:43 +00002779 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002780 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002781 }
Yury Selivanov75445082015-05-11 22:57:16 -04002782 VISIT(c, expr, s->v.AsyncFor.iter);
2783 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002784
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002785 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002786 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002787 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002788 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002789 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002790 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002791 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002792 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002793 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002794 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002795
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002796 /* Success block for __anext__ */
2797 VISIT(c, expr, s->v.AsyncFor.target);
2798 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002799 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002800
2801 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002802
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002803 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002804 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002805
2806 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002807 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002808
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002809 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002810 VISIT_SEQ(c, stmt, s->v.For.orelse);
2811
2812 compiler_use_next_block(c, end);
2813
2814 return 1;
2815}
2816
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002817static int
2818compiler_while(struct compiler *c, stmt_ty s)
2819{
Mark Shannon266b4622020-11-17 19:30:14 +00002820 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002822 body = compiler_new_block(c);
2823 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002825 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002829 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002832 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2833 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002834 }
2835
2836 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002838 SET_LOC(c, s);
2839 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2840 return 0;
2841 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002842
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002843 compiler_pop_fblock(c, WHILE_LOOP, loop);
2844
Mark Shannon266b4622020-11-17 19:30:14 +00002845 compiler_use_next_block(c, anchor);
2846 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002848 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852}
2853
2854static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002855compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002857 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002858 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002859 if (c->u->u_ste->ste_type != FunctionBlock)
2860 return compiler_error(c, "'return' outside function");
2861 if (s->v.Return.value != NULL &&
2862 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2863 {
2864 return compiler_error(
2865 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002867 if (preserve_tos) {
2868 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002869 } else {
2870 /* Emit instruction with line number for expression */
2871 if (s->v.Return.value != NULL) {
2872 SET_LOC(c, s->v.Return.value);
2873 ADDOP(c, NOP);
2874 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002875 }
Mark Shannonfee55262019-11-21 09:11:43 +00002876 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2877 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002878 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002879 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002880 }
2881 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00002882 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 }
2884 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002885 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002888}
2889
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002890static int
2891compiler_break(struct compiler *c)
2892{
Mark Shannonfee55262019-11-21 09:11:43 +00002893 struct fblockinfo *loop = NULL;
2894 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2895 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002896 }
Mark Shannonfee55262019-11-21 09:11:43 +00002897 if (loop == NULL) {
2898 return compiler_error(c, "'break' outside loop");
2899 }
2900 if (!compiler_unwind_fblock(c, loop, 0)) {
2901 return 0;
2902 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002903 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002904 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002905 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002906}
2907
2908static int
2909compiler_continue(struct compiler *c)
2910{
Mark Shannonfee55262019-11-21 09:11:43 +00002911 struct fblockinfo *loop = NULL;
2912 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2913 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002914 }
Mark Shannonfee55262019-11-21 09:11:43 +00002915 if (loop == NULL) {
2916 return compiler_error(c, "'continue' not properly in loop");
2917 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002918 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002919 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002920 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002921}
2922
2923
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002924/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925
2926 SETUP_FINALLY L
2927 <code for body>
2928 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002929 <code for finalbody>
2930 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002931 L:
2932 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002933 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002934
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002935 The special instructions use the block stack. Each block
2936 stack entry contains the instruction that created it (here
2937 SETUP_FINALLY), the level of the value stack at the time the
2938 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002939
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002940 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 Pushes the current value stack level and the label
2942 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002943 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002944 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002946 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002947 when a SETUP_FINALLY entry is found, the raised and the caught
2948 exceptions are pushed onto the value stack (and the exception
2949 condition is cleared), and the interpreter jumps to the label
2950 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002951*/
2952
2953static int
2954compiler_try_finally(struct compiler *c, stmt_ty s)
2955{
Mark Shannonfee55262019-11-21 09:11:43 +00002956 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 body = compiler_new_block(c);
2959 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002960 exit = compiler_new_block(c);
2961 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002963
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002964 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002965 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002966 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002967 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002969 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2970 if (!compiler_try_except(c, s))
2971 return 0;
2972 }
2973 else {
2974 VISIT_SEQ(c, stmt, s->v.Try.body);
2975 }
Mark Shannon56aa20f2020-12-14 10:19:10 +00002976 /* Mark code as artificial */
2977 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002979 compiler_pop_fblock(c, FINALLY_TRY, body);
2980 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon582aaf12020-08-04 17:30:11 +01002981 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00002982 /* `finally` block */
2983 compiler_use_next_block(c, end);
2984 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2985 return 0;
2986 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2987 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00002988 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00002989 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002991}
2992
2993/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002994 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002995 (The contents of the value stack is shown in [], with the top
2996 at the right; 'tb' is trace-back info, 'val' the exception's
2997 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002998
2999 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003000 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003001 [] <code for S>
3002 [] POP_BLOCK
3003 [] JUMP_FORWARD L0
3004
3005 [tb, val, exc] L1: DUP )
3006 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003007 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 [tb, val, exc] POP
3009 [tb, val] <assign to V1> (or POP if no V1)
3010 [tb] POP
3011 [] <code for S1>
3012 JUMP_FORWARD L0
3013
3014 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003015 .............................etc.......................
3016
Mark Shannonfee55262019-11-21 09:11:43 +00003017 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018
3019 [] L0: <next statement>
3020
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003021 Of course, parts are not generated if Vi or Ei is not present.
3022*/
3023static int
3024compiler_try_except(struct compiler *c, stmt_ty s)
3025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003027 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003029 body = compiler_new_block(c);
3030 except = compiler_new_block(c);
3031 orelse = compiler_new_block(c);
3032 end = compiler_new_block(c);
3033 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3034 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003035 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003037 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003039 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 ADDOP(c, POP_BLOCK);
Mark Shannon02d126a2020-09-25 14:04:19 +01003041 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon582aaf12020-08-04 17:30:11 +01003042 ADDOP_JUMP(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003043 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003045 /* Runtime will push a block here, so we need to account for that */
3046 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3047 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003048 for (i = 0; i < n; i++) {
3049 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003050 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003051 if (!handler->v.ExceptHandler.type && i < n-1)
3052 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003053 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003054 except = compiler_new_block(c);
3055 if (except == NULL)
3056 return 0;
3057 if (handler->v.ExceptHandler.type) {
3058 ADDOP(c, DUP_TOP);
3059 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003060 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003061 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 }
3063 ADDOP(c, POP_TOP);
3064 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003065 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003066
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003067 cleanup_end = compiler_new_block(c);
3068 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003069 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003070 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003071 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003072
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003073 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3074 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003076 /*
3077 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003078 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003079 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003080 try:
3081 # body
3082 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003083 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003084 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003085 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003087 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003088 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003089 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003090 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003091 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003093 /* second # body */
3094 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003095 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003096 ADDOP(c, POP_BLOCK);
3097 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003098 /* name = None; del name; # Mark as artificial */
3099 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003100 ADDOP_LOAD_CONST(c, Py_None);
3101 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3102 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003103 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104
Mark Shannonfee55262019-11-21 09:11:43 +00003105 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003106 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107
Mark Shannon877df852020-11-12 09:43:29 +00003108 /* name = None; del name; # Mark as artificial */
3109 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003110 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003112 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113
Mark Shannonbf353f32020-12-17 13:55:28 +00003114 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 }
3116 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003117 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003120 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003121 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122
Guido van Rossumb940e112007-01-10 16:19:56 +00003123 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003124 ADDOP(c, POP_TOP);
3125 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003126 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003127 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003129 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003130 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003131 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003133 compiler_use_next_block(c, except);
3134 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003135 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003136 /* Mark as artificial */
3137 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003138 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003140 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 compiler_use_next_block(c, end);
3142 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143}
3144
3145static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003146compiler_try(struct compiler *c, stmt_ty s) {
3147 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3148 return compiler_try_finally(c, s);
3149 else
3150 return compiler_try_except(c, s);
3151}
3152
3153
3154static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003155compiler_import_as(struct compiler *c, identifier name, identifier asname)
3156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003157 /* The IMPORT_NAME opcode was already generated. This function
3158 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003161 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003163 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3164 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003165 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003166 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003167 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003169 while (1) {
3170 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003172 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003173 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003174 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003175 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003176 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003177 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003178 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003179 if (dot == -1) {
3180 break;
3181 }
3182 ADDOP(c, ROT_TWO);
3183 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003184 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003185 if (!compiler_nameop(c, asname, Store)) {
3186 return 0;
3187 }
3188 ADDOP(c, POP_TOP);
3189 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 }
3191 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003192}
3193
3194static int
3195compiler_import(struct compiler *c, stmt_ty s)
3196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 /* The Import node stores a module name like a.b.c as a single
3198 string. This is convenient for all cases except
3199 import a.b.c as d
3200 where we need to parse that string to extract the individual
3201 module names.
3202 XXX Perhaps change the representation to make this case simpler?
3203 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003204 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003205
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003206 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003207 for (i = 0; i < n; i++) {
3208 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3209 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003210
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003211 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003212 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 if (alias->asname) {
3216 r = compiler_import_as(c, alias->name, alias->asname);
3217 if (!r)
3218 return r;
3219 }
3220 else {
3221 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003222 Py_ssize_t dot = PyUnicode_FindChar(
3223 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003224 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003225 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003226 if (tmp == NULL)
3227 return 0;
3228 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003230 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 Py_DECREF(tmp);
3232 }
3233 if (!r)
3234 return r;
3235 }
3236 }
3237 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003238}
3239
3240static int
3241compiler_from_import(struct compiler *c, stmt_ty s)
3242{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003243 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003244 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003247 if (!empty_string) {
3248 empty_string = PyUnicode_FromString("");
3249 if (!empty_string)
3250 return 0;
3251 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003252
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003253 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003254
3255 names = PyTuple_New(n);
3256 if (!names)
3257 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 /* build up the names */
3260 for (i = 0; i < n; i++) {
3261 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3262 Py_INCREF(alias->name);
3263 PyTuple_SET_ITEM(names, i, alias->name);
3264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003267 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003268 Py_DECREF(names);
3269 return compiler_error(c, "from __future__ imports must occur "
3270 "at the beginning of the file");
3271 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003272 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 if (s->v.ImportFrom.module) {
3275 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3276 }
3277 else {
3278 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3279 }
3280 for (i = 0; i < n; i++) {
3281 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3282 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003283
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003284 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 assert(n == 1);
3286 ADDOP(c, IMPORT_STAR);
3287 return 1;
3288 }
3289
3290 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3291 store_name = alias->name;
3292 if (alias->asname)
3293 store_name = alias->asname;
3294
3295 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 return 0;
3297 }
3298 }
3299 /* remove imported module */
3300 ADDOP(c, POP_TOP);
3301 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003302}
3303
3304static int
3305compiler_assert(struct compiler *c, stmt_ty s)
3306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003308
Georg Brandl8334fd92010-12-04 10:26:46 +00003309 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003312 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3313 {
3314 if (!compiler_warn(c, "assertion is always true, "
3315 "perhaps remove parentheses?"))
3316 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003317 return 0;
3318 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003319 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003320 end = compiler_new_block(c);
3321 if (end == NULL)
3322 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003323 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3324 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003325 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 if (s->v.Assert.msg) {
3327 VISIT(c, expr, s->v.Assert.msg);
3328 ADDOP_I(c, CALL_FUNCTION, 1);
3329 }
3330 ADDOP_I(c, RAISE_VARARGS, 1);
3331 compiler_use_next_block(c, end);
3332 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003333}
3334
3335static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003336compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3337{
3338 if (c->c_interactive && c->c_nestlevel <= 1) {
3339 VISIT(c, expr, value);
3340 ADDOP(c, PRINT_EXPR);
3341 return 1;
3342 }
3343
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003344 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003345 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003346 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003347 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003348 }
3349
3350 VISIT(c, expr, value);
3351 ADDOP(c, POP_TOP);
3352 return 1;
3353}
3354
3355static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003356compiler_visit_stmt(struct compiler *c, stmt_ty s)
3357{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003358 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003360 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003361 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003363 switch (s->kind) {
3364 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003365 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003366 case ClassDef_kind:
3367 return compiler_class(c, s);
3368 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003369 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003370 case Delete_kind:
3371 VISIT_SEQ(c, expr, s->v.Delete.targets)
3372 break;
3373 case Assign_kind:
3374 n = asdl_seq_LEN(s->v.Assign.targets);
3375 VISIT(c, expr, s->v.Assign.value);
3376 for (i = 0; i < n; i++) {
3377 if (i < n - 1)
3378 ADDOP(c, DUP_TOP);
3379 VISIT(c, expr,
3380 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3381 }
3382 break;
3383 case AugAssign_kind:
3384 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003385 case AnnAssign_kind:
3386 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003387 case For_kind:
3388 return compiler_for(c, s);
3389 case While_kind:
3390 return compiler_while(c, s);
3391 case If_kind:
3392 return compiler_if(c, s);
3393 case Raise_kind:
3394 n = 0;
3395 if (s->v.Raise.exc) {
3396 VISIT(c, expr, s->v.Raise.exc);
3397 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003398 if (s->v.Raise.cause) {
3399 VISIT(c, expr, s->v.Raise.cause);
3400 n++;
3401 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003402 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003403 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003404 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003406 case Try_kind:
3407 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 case Assert_kind:
3409 return compiler_assert(c, s);
3410 case Import_kind:
3411 return compiler_import(c, s);
3412 case ImportFrom_kind:
3413 return compiler_from_import(c, s);
3414 case Global_kind:
3415 case Nonlocal_kind:
3416 break;
3417 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003418 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003419 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003420 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003421 break;
3422 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003423 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003424 case Continue_kind:
3425 return compiler_continue(c);
3426 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003427 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003428 case AsyncFunctionDef_kind:
3429 return compiler_function(c, s, 1);
3430 case AsyncWith_kind:
3431 return compiler_async_with(c, s, 0);
3432 case AsyncFor_kind:
3433 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003434 }
Yury Selivanov75445082015-05-11 22:57:16 -04003435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003436 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003437}
3438
3439static int
3440unaryop(unaryop_ty op)
3441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003442 switch (op) {
3443 case Invert:
3444 return UNARY_INVERT;
3445 case Not:
3446 return UNARY_NOT;
3447 case UAdd:
3448 return UNARY_POSITIVE;
3449 case USub:
3450 return UNARY_NEGATIVE;
3451 default:
3452 PyErr_Format(PyExc_SystemError,
3453 "unary op %d should not be possible", op);
3454 return 0;
3455 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003456}
3457
3458static int
Andy Lester76d58772020-03-10 21:18:12 -05003459binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 switch (op) {
3462 case Add:
3463 return BINARY_ADD;
3464 case Sub:
3465 return BINARY_SUBTRACT;
3466 case Mult:
3467 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003468 case MatMult:
3469 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003470 case Div:
3471 return BINARY_TRUE_DIVIDE;
3472 case Mod:
3473 return BINARY_MODULO;
3474 case Pow:
3475 return BINARY_POWER;
3476 case LShift:
3477 return BINARY_LSHIFT;
3478 case RShift:
3479 return BINARY_RSHIFT;
3480 case BitOr:
3481 return BINARY_OR;
3482 case BitXor:
3483 return BINARY_XOR;
3484 case BitAnd:
3485 return BINARY_AND;
3486 case FloorDiv:
3487 return BINARY_FLOOR_DIVIDE;
3488 default:
3489 PyErr_Format(PyExc_SystemError,
3490 "binary op %d should not be possible", op);
3491 return 0;
3492 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003493}
3494
3495static int
Andy Lester76d58772020-03-10 21:18:12 -05003496inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003498 switch (op) {
3499 case Add:
3500 return INPLACE_ADD;
3501 case Sub:
3502 return INPLACE_SUBTRACT;
3503 case Mult:
3504 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003505 case MatMult:
3506 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003507 case Div:
3508 return INPLACE_TRUE_DIVIDE;
3509 case Mod:
3510 return INPLACE_MODULO;
3511 case Pow:
3512 return INPLACE_POWER;
3513 case LShift:
3514 return INPLACE_LSHIFT;
3515 case RShift:
3516 return INPLACE_RSHIFT;
3517 case BitOr:
3518 return INPLACE_OR;
3519 case BitXor:
3520 return INPLACE_XOR;
3521 case BitAnd:
3522 return INPLACE_AND;
3523 case FloorDiv:
3524 return INPLACE_FLOOR_DIVIDE;
3525 default:
3526 PyErr_Format(PyExc_SystemError,
3527 "inplace binary op %d should not be possible", op);
3528 return 0;
3529 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003530}
3531
3532static int
3533compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3534{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003535 int op, scope;
3536 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003539 PyObject *dict = c->u->u_names;
3540 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003541
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003542 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3543 !_PyUnicode_EqualToASCIIString(name, "True") &&
3544 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003545
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003546 if (forbidden_name(c, name, ctx))
3547 return 0;
3548
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003549 mangled = _Py_Mangle(c->u->u_private, name);
3550 if (!mangled)
3551 return 0;
3552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003553 op = 0;
3554 optype = OP_NAME;
3555 scope = PyST_GetScope(c->u->u_ste, mangled);
3556 switch (scope) {
3557 case FREE:
3558 dict = c->u->u_freevars;
3559 optype = OP_DEREF;
3560 break;
3561 case CELL:
3562 dict = c->u->u_cellvars;
3563 optype = OP_DEREF;
3564 break;
3565 case LOCAL:
3566 if (c->u->u_ste->ste_type == FunctionBlock)
3567 optype = OP_FAST;
3568 break;
3569 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003570 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003571 optype = OP_GLOBAL;
3572 break;
3573 case GLOBAL_EXPLICIT:
3574 optype = OP_GLOBAL;
3575 break;
3576 default:
3577 /* scope can be 0 */
3578 break;
3579 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003581 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003582 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003584 switch (optype) {
3585 case OP_DEREF:
3586 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003587 case Load:
3588 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3589 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003590 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003591 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003592 }
3593 break;
3594 case OP_FAST:
3595 switch (ctx) {
3596 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003597 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003599 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003600 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 return 1;
3602 case OP_GLOBAL:
3603 switch (ctx) {
3604 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003605 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003607 }
3608 break;
3609 case OP_NAME:
3610 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003611 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003612 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 }
3615 break;
3616 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003619 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003620 Py_DECREF(mangled);
3621 if (arg < 0)
3622 return 0;
3623 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003624}
3625
3626static int
3627compiler_boolop(struct compiler *c, expr_ty e)
3628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003630 int jumpi;
3631 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003632 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003634 assert(e->kind == BoolOp_kind);
3635 if (e->v.BoolOp.op == And)
3636 jumpi = JUMP_IF_FALSE_OR_POP;
3637 else
3638 jumpi = JUMP_IF_TRUE_OR_POP;
3639 end = compiler_new_block(c);
3640 if (end == NULL)
3641 return 0;
3642 s = e->v.BoolOp.values;
3643 n = asdl_seq_LEN(s) - 1;
3644 assert(n >= 0);
3645 for (i = 0; i < n; ++i) {
3646 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003647 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003648 basicblock *next = compiler_new_block(c);
3649 if (next == NULL) {
3650 return 0;
3651 }
3652 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003653 }
3654 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3655 compiler_use_next_block(c, end);
3656 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003657}
3658
3659static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003660starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003661 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003662{
3663 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003664 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003665 if (n > 2 && are_all_items_const(elts, 0, n)) {
3666 PyObject *folded = PyTuple_New(n);
3667 if (folded == NULL) {
3668 return 0;
3669 }
3670 PyObject *val;
3671 for (i = 0; i < n; i++) {
3672 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3673 Py_INCREF(val);
3674 PyTuple_SET_ITEM(folded, i, val);
3675 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003676 if (tuple) {
3677 ADDOP_LOAD_CONST_NEW(c, folded);
3678 } else {
3679 if (add == SET_ADD) {
3680 Py_SETREF(folded, PyFrozenSet_New(folded));
3681 if (folded == NULL) {
3682 return 0;
3683 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003684 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003685 ADDOP_I(c, build, pushed);
3686 ADDOP_LOAD_CONST_NEW(c, folded);
3687 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003688 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003689 return 1;
3690 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003691
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003692 for (i = 0; i < n; i++) {
3693 expr_ty elt = asdl_seq_GET(elts, i);
3694 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003695 seen_star = 1;
3696 }
3697 }
3698 if (seen_star) {
3699 seen_star = 0;
3700 for (i = 0; i < n; i++) {
3701 expr_ty elt = asdl_seq_GET(elts, i);
3702 if (elt->kind == Starred_kind) {
3703 if (seen_star == 0) {
3704 ADDOP_I(c, build, i+pushed);
3705 seen_star = 1;
3706 }
3707 VISIT(c, expr, elt->v.Starred.value);
3708 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003709 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003710 else {
3711 VISIT(c, expr, elt);
3712 if (seen_star) {
3713 ADDOP_I(c, add, 1);
3714 }
3715 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003716 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003717 assert(seen_star);
3718 if (tuple) {
3719 ADDOP(c, LIST_TO_TUPLE);
3720 }
3721 }
3722 else {
3723 for (i = 0; i < n; i++) {
3724 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003725 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003726 }
3727 if (tuple) {
3728 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3729 } else {
3730 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003731 }
3732 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003733 return 1;
3734}
3735
3736static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003737assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003738{
3739 Py_ssize_t n = asdl_seq_LEN(elts);
3740 Py_ssize_t i;
3741 int seen_star = 0;
3742 for (i = 0; i < n; i++) {
3743 expr_ty elt = asdl_seq_GET(elts, i);
3744 if (elt->kind == Starred_kind && !seen_star) {
3745 if ((i >= (1 << 8)) ||
3746 (n-i-1 >= (INT_MAX >> 8)))
3747 return compiler_error(c,
3748 "too many expressions in "
3749 "star-unpacking assignment");
3750 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3751 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003752 }
3753 else if (elt->kind == Starred_kind) {
3754 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003755 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003756 }
3757 }
3758 if (!seen_star) {
3759 ADDOP_I(c, UNPACK_SEQUENCE, n);
3760 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003761 for (i = 0; i < n; i++) {
3762 expr_ty elt = asdl_seq_GET(elts, i);
3763 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3764 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003765 return 1;
3766}
3767
3768static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003769compiler_list(struct compiler *c, expr_ty e)
3770{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003771 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003772 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003773 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003774 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003775 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003776 return starunpack_helper(c, elts, 0, BUILD_LIST,
3777 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003778 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003779 else
3780 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003781 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003782}
3783
3784static int
3785compiler_tuple(struct compiler *c, expr_ty e)
3786{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003787 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003788 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789 return assignment_helper(c, elts);
3790 }
3791 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003792 return starunpack_helper(c, elts, 0, BUILD_LIST,
3793 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003794 }
3795 else
3796 VISIT_SEQ(c, expr, elts);
3797 return 1;
3798}
3799
3800static int
3801compiler_set(struct compiler *c, expr_ty e)
3802{
Mark Shannon13bc1392020-01-23 09:25:17 +00003803 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3804 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805}
3806
3807static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003808are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003809{
3810 Py_ssize_t i;
3811 for (i = begin; i < end; i++) {
3812 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003813 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003814 return 0;
3815 }
3816 return 1;
3817}
3818
3819static int
3820compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3821{
3822 Py_ssize_t i, n = end - begin;
3823 PyObject *keys, *key;
3824 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3825 for (i = begin; i < end; i++) {
3826 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3827 }
3828 keys = PyTuple_New(n);
3829 if (keys == NULL) {
3830 return 0;
3831 }
3832 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003833 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003834 Py_INCREF(key);
3835 PyTuple_SET_ITEM(keys, i - begin, key);
3836 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003837 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003838 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3839 }
3840 else {
3841 for (i = begin; i < end; i++) {
3842 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3843 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3844 }
3845 ADDOP_I(c, BUILD_MAP, n);
3846 }
3847 return 1;
3848}
3849
3850static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003851compiler_dict(struct compiler *c, expr_ty e)
3852{
Victor Stinner976bb402016-03-23 11:36:19 +01003853 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003854 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003855 int is_unpacking = 0;
3856 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003857 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003858 elements = 0;
3859 for (i = 0; i < n; i++) {
3860 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003861 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003862 if (elements) {
3863 if (!compiler_subdict(c, e, i - elements, i)) {
3864 return 0;
3865 }
3866 if (have_dict) {
3867 ADDOP_I(c, DICT_UPDATE, 1);
3868 }
3869 have_dict = 1;
3870 elements = 0;
3871 }
3872 if (have_dict == 0) {
3873 ADDOP_I(c, BUILD_MAP, 0);
3874 have_dict = 1;
3875 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003876 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003877 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003878 }
3879 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003880 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003881 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003882 return 0;
3883 }
3884 if (have_dict) {
3885 ADDOP_I(c, DICT_UPDATE, 1);
3886 }
3887 have_dict = 1;
3888 elements = 0;
3889 }
3890 else {
3891 elements++;
3892 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003893 }
3894 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003895 if (elements) {
3896 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003897 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003898 }
3899 if (have_dict) {
3900 ADDOP_I(c, DICT_UPDATE, 1);
3901 }
3902 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003903 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003904 if (!have_dict) {
3905 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003906 }
3907 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003908}
3909
3910static int
3911compiler_compare(struct compiler *c, expr_ty e)
3912{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003913 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003914
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003915 if (!check_compare(c, e)) {
3916 return 0;
3917 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003919 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3920 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3921 if (n == 0) {
3922 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003923 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003924 }
3925 else {
3926 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003927 if (cleanup == NULL)
3928 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003929 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003930 VISIT(c, expr,
3931 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003932 ADDOP(c, DUP_TOP);
3933 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003934 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003935 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003936 NEXT_BLOCK(c);
3937 }
3938 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003939 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003940 basicblock *end = compiler_new_block(c);
3941 if (end == NULL)
3942 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003943 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003944 compiler_use_next_block(c, cleanup);
3945 ADDOP(c, ROT_TWO);
3946 ADDOP(c, POP_TOP);
3947 compiler_use_next_block(c, end);
3948 }
3949 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003950}
3951
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003952static PyTypeObject *
3953infer_type(expr_ty e)
3954{
3955 switch (e->kind) {
3956 case Tuple_kind:
3957 return &PyTuple_Type;
3958 case List_kind:
3959 case ListComp_kind:
3960 return &PyList_Type;
3961 case Dict_kind:
3962 case DictComp_kind:
3963 return &PyDict_Type;
3964 case Set_kind:
3965 case SetComp_kind:
3966 return &PySet_Type;
3967 case GeneratorExp_kind:
3968 return &PyGen_Type;
3969 case Lambda_kind:
3970 return &PyFunction_Type;
3971 case JoinedStr_kind:
3972 case FormattedValue_kind:
3973 return &PyUnicode_Type;
3974 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003975 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003976 default:
3977 return NULL;
3978 }
3979}
3980
3981static int
3982check_caller(struct compiler *c, expr_ty e)
3983{
3984 switch (e->kind) {
3985 case Constant_kind:
3986 case Tuple_kind:
3987 case List_kind:
3988 case ListComp_kind:
3989 case Dict_kind:
3990 case DictComp_kind:
3991 case Set_kind:
3992 case SetComp_kind:
3993 case GeneratorExp_kind:
3994 case JoinedStr_kind:
3995 case FormattedValue_kind:
3996 return compiler_warn(c, "'%.200s' object is not callable; "
3997 "perhaps you missed a comma?",
3998 infer_type(e)->tp_name);
3999 default:
4000 return 1;
4001 }
4002}
4003
4004static int
4005check_subscripter(struct compiler *c, expr_ty e)
4006{
4007 PyObject *v;
4008
4009 switch (e->kind) {
4010 case Constant_kind:
4011 v = e->v.Constant.value;
4012 if (!(v == Py_None || v == Py_Ellipsis ||
4013 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4014 PyAnySet_Check(v)))
4015 {
4016 return 1;
4017 }
4018 /* fall through */
4019 case Set_kind:
4020 case SetComp_kind:
4021 case GeneratorExp_kind:
4022 case Lambda_kind:
4023 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4024 "perhaps you missed a comma?",
4025 infer_type(e)->tp_name);
4026 default:
4027 return 1;
4028 }
4029}
4030
4031static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004032check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004033{
4034 PyObject *v;
4035
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004036 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004037 if (index_type == NULL
4038 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4039 || index_type == &PySlice_Type) {
4040 return 1;
4041 }
4042
4043 switch (e->kind) {
4044 case Constant_kind:
4045 v = e->v.Constant.value;
4046 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4047 return 1;
4048 }
4049 /* fall through */
4050 case Tuple_kind:
4051 case List_kind:
4052 case ListComp_kind:
4053 case JoinedStr_kind:
4054 case FormattedValue_kind:
4055 return compiler_warn(c, "%.200s indices must be integers or slices, "
4056 "not %.200s; "
4057 "perhaps you missed a comma?",
4058 infer_type(e)->tp_name,
4059 index_type->tp_name);
4060 default:
4061 return 1;
4062 }
4063}
4064
Zackery Spytz97f5de02019-03-22 01:30:32 -06004065// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004066static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004067maybe_optimize_method_call(struct compiler *c, expr_ty e)
4068{
4069 Py_ssize_t argsl, i;
4070 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004071 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004072
4073 /* Check that the call node is an attribute access, and that
4074 the call doesn't have keyword parameters. */
4075 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4076 asdl_seq_LEN(e->v.Call.keywords))
4077 return -1;
4078
4079 /* Check that there are no *varargs types of arguments. */
4080 argsl = asdl_seq_LEN(args);
4081 for (i = 0; i < argsl; i++) {
4082 expr_ty elt = asdl_seq_GET(args, i);
4083 if (elt->kind == Starred_kind) {
4084 return -1;
4085 }
4086 }
4087
4088 /* Alright, we can optimize the code. */
4089 VISIT(c, expr, meth->v.Attribute.value);
4090 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4091 VISIT_SEQ(c, expr, e->v.Call.args);
4092 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4093 return 1;
4094}
4095
4096static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004097validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004098{
4099 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4100 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004101 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4102 if (key->arg == NULL) {
4103 continue;
4104 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004105 if (forbidden_name(c, key->arg, Store)) {
4106 return -1;
4107 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004108 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004109 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4110 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4111 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4112 if (msg == NULL) {
4113 return -1;
4114 }
4115 c->u->u_col_offset = other->col_offset;
4116 compiler_error(c, PyUnicode_AsUTF8(msg));
4117 Py_DECREF(msg);
4118 return -1;
4119 }
4120 }
4121 }
4122 return 0;
4123}
4124
4125static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004126compiler_call(struct compiler *c, expr_ty e)
4127{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004128 int ret = maybe_optimize_method_call(c, e);
4129 if (ret >= 0) {
4130 return ret;
4131 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004132 if (!check_caller(c, e->v.Call.func)) {
4133 return 0;
4134 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004135 VISIT(c, expr, e->v.Call.func);
4136 return compiler_call_helper(c, 0,
4137 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004138 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004139}
4140
Eric V. Smith235a6f02015-09-19 14:51:32 -04004141static int
4142compiler_joined_str(struct compiler *c, expr_ty e)
4143{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004144 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004145 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4146 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004147 return 1;
4148}
4149
Eric V. Smitha78c7952015-11-03 12:45:05 -05004150/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004151static int
4152compiler_formatted_value(struct compiler *c, expr_ty e)
4153{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004154 /* Our oparg encodes 2 pieces of information: the conversion
4155 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004156
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004157 Convert the conversion char to 3 bits:
4158 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004159 !s : 001 0x1 FVC_STR
4160 !r : 010 0x2 FVC_REPR
4161 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004162
Eric V. Smitha78c7952015-11-03 12:45:05 -05004163 next bit is whether or not we have a format spec:
4164 yes : 100 0x4
4165 no : 000 0x0
4166 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004167
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004168 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004169 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004170
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004171 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004172 VISIT(c, expr, e->v.FormattedValue.value);
4173
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004174 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004175 case 's': oparg = FVC_STR; break;
4176 case 'r': oparg = FVC_REPR; break;
4177 case 'a': oparg = FVC_ASCII; break;
4178 case -1: oparg = FVC_NONE; break;
4179 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004180 PyErr_Format(PyExc_SystemError,
4181 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004182 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004183 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004184 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004185 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004186 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004187 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004188 }
4189
Eric V. Smitha78c7952015-11-03 12:45:05 -05004190 /* And push our opcode and oparg */
4191 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004192
Eric V. Smith235a6f02015-09-19 14:51:32 -04004193 return 1;
4194}
4195
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004196static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004197compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004198{
4199 Py_ssize_t i, n = end - begin;
4200 keyword_ty kw;
4201 PyObject *keys, *key;
4202 assert(n > 0);
4203 if (n > 1) {
4204 for (i = begin; i < end; i++) {
4205 kw = asdl_seq_GET(keywords, i);
4206 VISIT(c, expr, kw->value);
4207 }
4208 keys = PyTuple_New(n);
4209 if (keys == NULL) {
4210 return 0;
4211 }
4212 for (i = begin; i < end; i++) {
4213 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4214 Py_INCREF(key);
4215 PyTuple_SET_ITEM(keys, i - begin, key);
4216 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004217 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004218 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4219 }
4220 else {
4221 /* a for loop only executes once */
4222 for (i = begin; i < end; i++) {
4223 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004224 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004225 VISIT(c, expr, kw->value);
4226 }
4227 ADDOP_I(c, BUILD_MAP, n);
4228 }
4229 return 1;
4230}
4231
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004232/* shared code between compiler_call and compiler_class */
4233static int
4234compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004235 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004236 asdl_expr_seq *args,
4237 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004238{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004239 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004240
Pablo Galindo254ec782020-04-03 20:37:13 +01004241 if (validate_keywords(c, keywords) == -1) {
4242 return 0;
4243 }
4244
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004245 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004246 nkwelts = asdl_seq_LEN(keywords);
4247
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004248 for (i = 0; i < nelts; i++) {
4249 expr_ty elt = asdl_seq_GET(args, i);
4250 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004251 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004252 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004253 }
4254 for (i = 0; i < nkwelts; i++) {
4255 keyword_ty kw = asdl_seq_GET(keywords, i);
4256 if (kw->arg == NULL) {
4257 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004259 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004260
Mark Shannon13bc1392020-01-23 09:25:17 +00004261 /* No * or ** args, so can use faster calling sequence */
4262 for (i = 0; i < nelts; i++) {
4263 expr_ty elt = asdl_seq_GET(args, i);
4264 assert(elt->kind != Starred_kind);
4265 VISIT(c, expr, elt);
4266 }
4267 if (nkwelts) {
4268 PyObject *names;
4269 VISIT_SEQ(c, keyword, keywords);
4270 names = PyTuple_New(nkwelts);
4271 if (names == NULL) {
4272 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004273 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004274 for (i = 0; i < nkwelts; i++) {
4275 keyword_ty kw = asdl_seq_GET(keywords, i);
4276 Py_INCREF(kw->arg);
4277 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004278 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004279 ADDOP_LOAD_CONST_NEW(c, names);
4280 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4281 return 1;
4282 }
4283 else {
4284 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4285 return 1;
4286 }
4287
4288ex_call:
4289
4290 /* Do positional arguments. */
4291 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4292 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4293 }
4294 else if (starunpack_helper(c, args, n, BUILD_LIST,
4295 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4296 return 0;
4297 }
4298 /* Then keyword arguments */
4299 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004300 /* Has a new dict been pushed */
4301 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004302
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004303 nseen = 0; /* the number of keyword arguments on the stack following */
4304 for (i = 0; i < nkwelts; i++) {
4305 keyword_ty kw = asdl_seq_GET(keywords, i);
4306 if (kw->arg == NULL) {
4307 /* A keyword argument unpacking. */
4308 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004309 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004310 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004311 }
Mark Shannondb64f122020-06-01 10:42:42 +01004312 if (have_dict) {
4313 ADDOP_I(c, DICT_MERGE, 1);
4314 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004315 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004316 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004317 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004318 if (!have_dict) {
4319 ADDOP_I(c, BUILD_MAP, 0);
4320 have_dict = 1;
4321 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004322 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004323 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004324 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004325 else {
4326 nseen++;
4327 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004328 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004329 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004330 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004331 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004332 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004333 }
4334 if (have_dict) {
4335 ADDOP_I(c, DICT_MERGE, 1);
4336 }
4337 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004338 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004339 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004340 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004341 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4342 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004343}
4344
Nick Coghlan650f0d02007-04-15 12:05:43 +00004345
4346/* List and set comprehensions and generator expressions work by creating a
4347 nested function to perform the actual iteration. This means that the
4348 iteration variables don't leak into the current scope.
4349 The defined function is called immediately following its definition, with the
4350 result of that call being the result of the expression.
4351 The LC/SC version returns the populated container, while the GE version is
4352 flagged in symtable.c as a generator, so it returns the generator object
4353 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004354
4355 Possible cleanups:
4356 - iterate over the generator sequence instead of using recursion
4357*/
4358
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004359
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004360static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004361compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004362 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004363 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004364 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004365{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004366 comprehension_ty gen;
4367 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4368 if (gen->is_async) {
4369 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004370 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004371 } else {
4372 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004373 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004374 }
4375}
4376
4377static int
4378compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004379 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004380 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004381 expr_ty elt, expr_ty val, int type)
4382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 /* generate code for the iterator, then each of the ifs,
4384 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386 comprehension_ty gen;
4387 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004388 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004390 start = compiler_new_block(c);
4391 skip = compiler_new_block(c);
4392 if_cleanup = compiler_new_block(c);
4393 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004395 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4396 anchor == NULL)
4397 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004399 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004401 if (gen_index == 0) {
4402 /* Receive outermost iter as an implicit argument */
4403 c->u->u_argcount = 1;
4404 ADDOP_I(c, LOAD_FAST, 0);
4405 }
4406 else {
4407 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004408 /* Fast path for the temporary variable assignment idiom:
4409 for y in [f(x)]
4410 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004411 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004412 switch (gen->iter->kind) {
4413 case List_kind:
4414 elts = gen->iter->v.List.elts;
4415 break;
4416 case Tuple_kind:
4417 elts = gen->iter->v.Tuple.elts;
4418 break;
4419 default:
4420 elts = NULL;
4421 }
4422 if (asdl_seq_LEN(elts) == 1) {
4423 expr_ty elt = asdl_seq_GET(elts, 0);
4424 if (elt->kind != Starred_kind) {
4425 VISIT(c, expr, elt);
4426 start = NULL;
4427 }
4428 }
4429 if (start) {
4430 VISIT(c, expr, gen->iter);
4431 ADDOP(c, GET_ITER);
4432 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004433 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004434 if (start) {
4435 depth++;
4436 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004437 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004438 NEXT_BLOCK(c);
4439 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004440 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004442 /* XXX this needs to be cleaned up...a lot! */
4443 n = asdl_seq_LEN(gen->ifs);
4444 for (i = 0; i < n; i++) {
4445 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004446 if (!compiler_jump_if(c, e, if_cleanup, 0))
4447 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004448 NEXT_BLOCK(c);
4449 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004451 if (++gen_index < asdl_seq_LEN(generators))
4452 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004453 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004454 elt, val, type))
4455 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 /* only append after the last for generator */
4458 if (gen_index >= asdl_seq_LEN(generators)) {
4459 /* comprehension specific code */
4460 switch (type) {
4461 case COMP_GENEXP:
4462 VISIT(c, expr, elt);
4463 ADDOP(c, YIELD_VALUE);
4464 ADDOP(c, POP_TOP);
4465 break;
4466 case COMP_LISTCOMP:
4467 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004468 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 break;
4470 case COMP_SETCOMP:
4471 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004472 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 break;
4474 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004475 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004477 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004478 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004479 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004480 break;
4481 default:
4482 return 0;
4483 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004485 compiler_use_next_block(c, skip);
4486 }
4487 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004488 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004489 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004490 compiler_use_next_block(c, anchor);
4491 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004492
4493 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004494}
4495
4496static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004497compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004498 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004499 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004500 expr_ty elt, expr_ty val, int type)
4501{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004502 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004503 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004504 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004505 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004506 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004507 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004509 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004510 return 0;
4511 }
4512
4513 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4514
4515 if (gen_index == 0) {
4516 /* Receive outermost iter as an implicit argument */
4517 c->u->u_argcount = 1;
4518 ADDOP_I(c, LOAD_FAST, 0);
4519 }
4520 else {
4521 /* Sub-iter - calculate on the fly */
4522 VISIT(c, expr, gen->iter);
4523 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 }
4525
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004526 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527
Mark Shannon582aaf12020-08-04 17:30:11 +01004528 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004530 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004532 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004533 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004534
4535 n = asdl_seq_LEN(gen->ifs);
4536 for (i = 0; i < n; i++) {
4537 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004538 if (!compiler_jump_if(c, e, if_cleanup, 0))
4539 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004540 NEXT_BLOCK(c);
4541 }
4542
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004543 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004544 if (++gen_index < asdl_seq_LEN(generators))
4545 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004546 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004547 elt, val, type))
4548 return 0;
4549
4550 /* only append after the last for generator */
4551 if (gen_index >= asdl_seq_LEN(generators)) {
4552 /* comprehension specific code */
4553 switch (type) {
4554 case COMP_GENEXP:
4555 VISIT(c, expr, elt);
4556 ADDOP(c, YIELD_VALUE);
4557 ADDOP(c, POP_TOP);
4558 break;
4559 case COMP_LISTCOMP:
4560 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004561 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004562 break;
4563 case COMP_SETCOMP:
4564 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004565 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004566 break;
4567 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004568 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004569 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004570 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004571 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004572 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004573 break;
4574 default:
4575 return 0;
4576 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004577 }
4578 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004579 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004580
4581 compiler_use_next_block(c, except);
4582 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004583
4584 return 1;
4585}
4586
4587static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004588compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004589 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004590 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004592 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004593 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004594 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004595 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004596 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004597
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004598
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004599 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004600
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004601 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004602 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4603 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004604 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004605 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004606 }
4607
4608 is_async_generator = c->u->u_ste->ste_coroutine;
4609
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004610 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004611 compiler_error(c, "asynchronous comprehension outside of "
4612 "an asynchronous function");
4613 goto error_in_scope;
4614 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004616 if (type != COMP_GENEXP) {
4617 int op;
4618 switch (type) {
4619 case COMP_LISTCOMP:
4620 op = BUILD_LIST;
4621 break;
4622 case COMP_SETCOMP:
4623 op = BUILD_SET;
4624 break;
4625 case COMP_DICTCOMP:
4626 op = BUILD_MAP;
4627 break;
4628 default:
4629 PyErr_Format(PyExc_SystemError,
4630 "unknown comprehension type %d", type);
4631 goto error_in_scope;
4632 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004634 ADDOP_I(c, op, 0);
4635 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004636
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004637 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004638 val, type))
4639 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 if (type != COMP_GENEXP) {
4642 ADDOP(c, RETURN_VALUE);
4643 }
4644
4645 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004646 qualname = c->u->u_qualname;
4647 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004648 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004649 if (top_level_await && is_async_generator){
4650 c->u->u_ste->ste_coroutine = 1;
4651 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004652 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004653 goto error;
4654
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004655 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004656 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004657 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004658 Py_DECREF(co);
4659
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004660 VISIT(c, expr, outermost->iter);
4661
4662 if (outermost->is_async) {
4663 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004664 } else {
4665 ADDOP(c, GET_ITER);
4666 }
4667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004669
4670 if (is_async_generator && type != COMP_GENEXP) {
4671 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004672 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004673 ADDOP(c, YIELD_FROM);
4674 }
4675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004676 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004677error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004679error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004680 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 Py_XDECREF(co);
4682 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004683}
4684
4685static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004686compiler_genexp(struct compiler *c, expr_ty e)
4687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688 static identifier name;
4689 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004690 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004691 if (!name)
4692 return 0;
4693 }
4694 assert(e->kind == GeneratorExp_kind);
4695 return compiler_comprehension(c, e, COMP_GENEXP, name,
4696 e->v.GeneratorExp.generators,
4697 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004698}
4699
4700static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004701compiler_listcomp(struct compiler *c, expr_ty e)
4702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 static identifier name;
4704 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004705 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 if (!name)
4707 return 0;
4708 }
4709 assert(e->kind == ListComp_kind);
4710 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4711 e->v.ListComp.generators,
4712 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004713}
4714
4715static int
4716compiler_setcomp(struct compiler *c, expr_ty e)
4717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 static identifier name;
4719 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004720 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 if (!name)
4722 return 0;
4723 }
4724 assert(e->kind == SetComp_kind);
4725 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4726 e->v.SetComp.generators,
4727 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004728}
4729
4730
4731static int
4732compiler_dictcomp(struct compiler *c, expr_ty e)
4733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 static identifier name;
4735 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004736 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004737 if (!name)
4738 return 0;
4739 }
4740 assert(e->kind == DictComp_kind);
4741 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4742 e->v.DictComp.generators,
4743 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004744}
4745
4746
4747static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004748compiler_visit_keyword(struct compiler *c, keyword_ty k)
4749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004750 VISIT(c, expr, k->value);
4751 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004752}
4753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004754/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004755 whether they are true or false.
4756
4757 Return values: 1 for true, 0 for false, -1 for non-constant.
4758 */
4759
4760static int
Mark Shannonfee55262019-11-21 09:11:43 +00004761compiler_with_except_finish(struct compiler *c) {
4762 basicblock *exit;
4763 exit = compiler_new_block(c);
4764 if (exit == NULL)
4765 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004766 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004767 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004768 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004769 compiler_use_next_block(c, exit);
4770 ADDOP(c, POP_TOP);
4771 ADDOP(c, POP_TOP);
4772 ADDOP(c, POP_TOP);
4773 ADDOP(c, POP_EXCEPT);
4774 ADDOP(c, POP_TOP);
4775 return 1;
4776}
Yury Selivanov75445082015-05-11 22:57:16 -04004777
4778/*
4779 Implements the async with statement.
4780
4781 The semantics outlined in that PEP are as follows:
4782
4783 async with EXPR as VAR:
4784 BLOCK
4785
4786 It is implemented roughly as:
4787
4788 context = EXPR
4789 exit = context.__aexit__ # not calling it
4790 value = await context.__aenter__()
4791 try:
4792 VAR = value # if VAR present in the syntax
4793 BLOCK
4794 finally:
4795 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004796 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004797 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004798 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004799 if not (await exit(*exc)):
4800 raise
4801 */
4802static int
4803compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4804{
Mark Shannonfee55262019-11-21 09:11:43 +00004805 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004806 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4807
4808 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004809 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004810 c->u->u_ste->ste_coroutine = 1;
4811 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004812 return compiler_error(c, "'async with' outside async function");
4813 }
Yury Selivanov75445082015-05-11 22:57:16 -04004814
4815 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004816 final = compiler_new_block(c);
4817 exit = compiler_new_block(c);
4818 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004819 return 0;
4820
4821 /* Evaluate EXPR */
4822 VISIT(c, expr, item->context_expr);
4823
4824 ADDOP(c, BEFORE_ASYNC_WITH);
4825 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004826 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004827 ADDOP(c, YIELD_FROM);
4828
Mark Shannon582aaf12020-08-04 17:30:11 +01004829 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004830
4831 /* SETUP_ASYNC_WITH pushes a finally block. */
4832 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004833 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004834 return 0;
4835 }
4836
4837 if (item->optional_vars) {
4838 VISIT(c, expr, item->optional_vars);
4839 }
4840 else {
4841 /* Discard result from context.__aenter__() */
4842 ADDOP(c, POP_TOP);
4843 }
4844
4845 pos++;
4846 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4847 /* BLOCK code */
4848 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4849 else if (!compiler_async_with(c, s, pos))
4850 return 0;
4851
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004852 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004853 ADDOP(c, POP_BLOCK);
4854 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004855
Mark Shannonfee55262019-11-21 09:11:43 +00004856 /* For successful outcome:
4857 * call __exit__(None, None, None)
4858 */
4859 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004860 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004861 ADDOP(c, GET_AWAITABLE);
4862 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4863 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004864
Mark Shannonfee55262019-11-21 09:11:43 +00004865 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004866
Mark Shannon582aaf12020-08-04 17:30:11 +01004867 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004868
4869 /* For exceptional outcome: */
4870 compiler_use_next_block(c, final);
4871
4872 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004873 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004874 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004875 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004876 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004877
Mark Shannonfee55262019-11-21 09:11:43 +00004878compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004879 return 1;
4880}
4881
4882
Guido van Rossumc2e20742006-02-27 22:32:47 +00004883/*
4884 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004885 with EXPR as VAR:
4886 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004887 is implemented as:
4888 <code for EXPR>
4889 SETUP_WITH E
4890 <code to store to VAR> or POP_TOP
4891 <code for BLOCK>
4892 LOAD_CONST (None, None, None)
4893 CALL_FUNCTION_EX 0
4894 JUMP_FORWARD EXIT
4895 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4896 POP_JUMP_IF_TRUE T:
4897 RERAISE
4898 T: POP_TOP * 3 (remove exception from stack)
4899 POP_EXCEPT
4900 POP_TOP
4901 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004902 */
Mark Shannonfee55262019-11-21 09:11:43 +00004903
Guido van Rossumc2e20742006-02-27 22:32:47 +00004904static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004905compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004906{
Mark Shannonfee55262019-11-21 09:11:43 +00004907 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004908 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004909
4910 assert(s->kind == With_kind);
4911
Guido van Rossumc2e20742006-02-27 22:32:47 +00004912 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004913 final = compiler_new_block(c);
4914 exit = compiler_new_block(c);
4915 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004916 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004917
Thomas Wouters477c8d52006-05-27 19:21:47 +00004918 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004919 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004920 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004921 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004922
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004923 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004924 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004925 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004926 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004927 }
4928
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004929 if (item->optional_vars) {
4930 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004931 }
4932 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004933 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004934 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004935 }
4936
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004937 pos++;
4938 if (pos == asdl_seq_LEN(s->v.With.items))
4939 /* BLOCK code */
4940 VISIT_SEQ(c, stmt, s->v.With.body)
4941 else if (!compiler_with(c, s, pos))
4942 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004943
Guido van Rossumc2e20742006-02-27 22:32:47 +00004944 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004945 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004946
Mark Shannonfee55262019-11-21 09:11:43 +00004947 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004948
Mark Shannonfee55262019-11-21 09:11:43 +00004949 /* For successful outcome:
4950 * call __exit__(None, None, None)
4951 */
4952 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004953 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004954 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004955 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004956
Mark Shannonfee55262019-11-21 09:11:43 +00004957 /* For exceptional outcome: */
4958 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004959
Mark Shannonfee55262019-11-21 09:11:43 +00004960 ADDOP(c, WITH_EXCEPT_START);
4961 compiler_with_except_finish(c);
4962
4963 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004964 return 1;
4965}
4966
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004967static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004968compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004970 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004971 case NamedExpr_kind:
4972 VISIT(c, expr, e->v.NamedExpr.value);
4973 ADDOP(c, DUP_TOP);
4974 VISIT(c, expr, e->v.NamedExpr.target);
4975 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004976 case BoolOp_kind:
4977 return compiler_boolop(c, e);
4978 case BinOp_kind:
4979 VISIT(c, expr, e->v.BinOp.left);
4980 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004981 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004982 break;
4983 case UnaryOp_kind:
4984 VISIT(c, expr, e->v.UnaryOp.operand);
4985 ADDOP(c, unaryop(e->v.UnaryOp.op));
4986 break;
4987 case Lambda_kind:
4988 return compiler_lambda(c, e);
4989 case IfExp_kind:
4990 return compiler_ifexp(c, e);
4991 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004992 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004993 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004994 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 case GeneratorExp_kind:
4996 return compiler_genexp(c, e);
4997 case ListComp_kind:
4998 return compiler_listcomp(c, e);
4999 case SetComp_kind:
5000 return compiler_setcomp(c, e);
5001 case DictComp_kind:
5002 return compiler_dictcomp(c, e);
5003 case Yield_kind:
5004 if (c->u->u_ste->ste_type != FunctionBlock)
5005 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005006 if (e->v.Yield.value) {
5007 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005008 }
5009 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005010 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005011 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005012 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005013 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005014 case YieldFrom_kind:
5015 if (c->u->u_ste->ste_type != FunctionBlock)
5016 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005017
5018 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5019 return compiler_error(c, "'yield from' inside async function");
5020
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005021 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005022 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005023 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005024 ADDOP(c, YIELD_FROM);
5025 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005026 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005027 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005028 if (c->u->u_ste->ste_type != FunctionBlock){
5029 return compiler_error(c, "'await' outside function");
5030 }
Yury Selivanov75445082015-05-11 22:57:16 -04005031
Victor Stinner331a6a52019-05-27 16:39:22 +02005032 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005033 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5034 return compiler_error(c, "'await' outside async function");
5035 }
5036 }
Yury Selivanov75445082015-05-11 22:57:16 -04005037
5038 VISIT(c, expr, e->v.Await.value);
5039 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005040 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005041 ADDOP(c, YIELD_FROM);
5042 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005043 case Compare_kind:
5044 return compiler_compare(c, e);
5045 case Call_kind:
5046 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005047 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005048 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005049 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005050 case JoinedStr_kind:
5051 return compiler_joined_str(c, e);
5052 case FormattedValue_kind:
5053 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005054 /* The following exprs can be assignment targets. */
5055 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005056 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005058 case Load:
5059 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5060 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005061 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005062 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5063 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005064 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5065 break;
5066 case Del:
5067 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5068 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005069 }
5070 break;
5071 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005072 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005073 case Starred_kind:
5074 switch (e->v.Starred.ctx) {
5075 case Store:
5076 /* In all legitimate cases, the Starred node was already replaced
5077 * by compiler_list/compiler_tuple. XXX: is that okay? */
5078 return compiler_error(c,
5079 "starred assignment target must be in a list or tuple");
5080 default:
5081 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005082 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005083 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005084 break;
5085 case Slice_kind:
5086 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 case Name_kind:
5088 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5089 /* child nodes of List and Tuple will have expr_context set */
5090 case List_kind:
5091 return compiler_list(c, e);
5092 case Tuple_kind:
5093 return compiler_tuple(c, e);
5094 }
5095 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005096}
5097
5098static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005099compiler_visit_expr(struct compiler *c, expr_ty e)
5100{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005101 int old_lineno = c->u->u_lineno;
5102 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005103 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005104 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005105 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005106 c->u->u_col_offset = old_col_offset;
5107 return res;
5108}
5109
5110static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005111compiler_augassign(struct compiler *c, stmt_ty s)
5112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005113 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005114 expr_ty e = s->v.AugAssign.target;
5115
5116 int old_lineno = c->u->u_lineno;
5117 int old_col_offset = c->u->u_col_offset;
5118 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 switch (e->kind) {
5121 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005122 VISIT(c, expr, e->v.Attribute.value);
5123 ADDOP(c, DUP_TOP);
5124 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005125 break;
5126 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005127 VISIT(c, expr, e->v.Subscript.value);
5128 VISIT(c, expr, e->v.Subscript.slice);
5129 ADDOP(c, DUP_TOP_TWO);
5130 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005131 break;
5132 case Name_kind:
5133 if (!compiler_nameop(c, e->v.Name.id, Load))
5134 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005135 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005136 default:
5137 PyErr_Format(PyExc_SystemError,
5138 "invalid node type (%d) for augmented assignment",
5139 e->kind);
5140 return 0;
5141 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005142
5143 c->u->u_lineno = old_lineno;
5144 c->u->u_col_offset = old_col_offset;
5145
5146 VISIT(c, expr, s->v.AugAssign.value);
5147 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5148
5149 SET_LOC(c, e);
5150
5151 switch (e->kind) {
5152 case Attribute_kind:
5153 ADDOP(c, ROT_TWO);
5154 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5155 break;
5156 case Subscript_kind:
5157 ADDOP(c, ROT_THREE);
5158 ADDOP(c, STORE_SUBSCR);
5159 break;
5160 case Name_kind:
5161 return compiler_nameop(c, e->v.Name.id, Store);
5162 default:
5163 Py_UNREACHABLE();
5164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005165 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005166}
5167
5168static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005169check_ann_expr(struct compiler *c, expr_ty e)
5170{
5171 VISIT(c, expr, e);
5172 ADDOP(c, POP_TOP);
5173 return 1;
5174}
5175
5176static int
5177check_annotation(struct compiler *c, stmt_ty s)
5178{
5179 /* Annotations are only evaluated in a module or class. */
5180 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5181 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5182 return check_ann_expr(c, s->v.AnnAssign.annotation);
5183 }
5184 return 1;
5185}
5186
5187static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005188check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005189{
5190 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005191 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005192 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005193 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005194 return 0;
5195 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005196 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5197 return 0;
5198 }
5199 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5200 return 0;
5201 }
5202 return 1;
5203 case Tuple_kind: {
5204 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005205 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005206 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005207 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005208 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005209 return 0;
5210 }
5211 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005212 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005213 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005214 default:
5215 return check_ann_expr(c, e);
5216 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005217}
5218
5219static int
5220compiler_annassign(struct compiler *c, stmt_ty s)
5221{
5222 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005223 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005224
5225 assert(s->kind == AnnAssign_kind);
5226
5227 /* We perform the actual assignment first. */
5228 if (s->v.AnnAssign.value) {
5229 VISIT(c, expr, s->v.AnnAssign.value);
5230 VISIT(c, expr, targ);
5231 }
5232 switch (targ->kind) {
5233 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005234 if (forbidden_name(c, targ->v.Name.id, Store))
5235 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005236 /* If we have a simple name in a module or class, store annotation. */
5237 if (s->v.AnnAssign.simple &&
5238 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5239 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005240 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005241 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005242 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005243 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005244 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005245 }
5246 break;
5247 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005248 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5249 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005250 if (!s->v.AnnAssign.value &&
5251 !check_ann_expr(c, targ->v.Attribute.value)) {
5252 return 0;
5253 }
5254 break;
5255 case Subscript_kind:
5256 if (!s->v.AnnAssign.value &&
5257 (!check_ann_expr(c, targ->v.Subscript.value) ||
5258 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5259 return 0;
5260 }
5261 break;
5262 default:
5263 PyErr_Format(PyExc_SystemError,
5264 "invalid node type (%d) for annotated assignment",
5265 targ->kind);
5266 return 0;
5267 }
5268 /* Annotation is evaluated last. */
5269 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5270 return 0;
5271 }
5272 return 1;
5273}
5274
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005275/* Raises a SyntaxError and returns 0.
5276 If something goes wrong, a different exception may be raised.
5277*/
5278
5279static int
5280compiler_error(struct compiler *c, const char *errstr)
5281{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005282 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005284
Victor Stinner14e461d2013-08-26 22:28:21 +02005285 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005286 if (!loc) {
5287 Py_INCREF(Py_None);
5288 loc = Py_None;
5289 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005290 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005291 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005292 if (!u)
5293 goto exit;
5294 v = Py_BuildValue("(zO)", errstr, u);
5295 if (!v)
5296 goto exit;
5297 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005298 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005299 Py_DECREF(loc);
5300 Py_XDECREF(u);
5301 Py_XDECREF(v);
5302 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005303}
5304
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005305/* Emits a SyntaxWarning and returns 1 on success.
5306 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5307 and returns 0.
5308*/
5309static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005310compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005311{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005312 va_list vargs;
5313#ifdef HAVE_STDARG_PROTOTYPES
5314 va_start(vargs, format);
5315#else
5316 va_start(vargs);
5317#endif
5318 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5319 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005320 if (msg == NULL) {
5321 return 0;
5322 }
5323 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5324 c->u->u_lineno, NULL, NULL) < 0)
5325 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005326 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005327 /* Replace the SyntaxWarning exception with a SyntaxError
5328 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005329 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005330 assert(PyUnicode_AsUTF8(msg) != NULL);
5331 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005332 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005333 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005334 return 0;
5335 }
5336 Py_DECREF(msg);
5337 return 1;
5338}
5339
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005340static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005341compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005342{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005343 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005344 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005345
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005346 if (ctx == Load) {
5347 if (!check_subscripter(c, e->v.Subscript.value)) {
5348 return 0;
5349 }
5350 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5351 return 0;
5352 }
5353 }
5354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005355 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005356 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 case Store: op = STORE_SUBSCR; break;
5358 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005359 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005360 assert(op);
5361 VISIT(c, expr, e->v.Subscript.value);
5362 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 ADDOP(c, op);
5364 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005365}
5366
5367static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005368compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 int n = 2;
5371 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005373 /* only handles the cases where BUILD_SLICE is emitted */
5374 if (s->v.Slice.lower) {
5375 VISIT(c, expr, s->v.Slice.lower);
5376 }
5377 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005378 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005379 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005381 if (s->v.Slice.upper) {
5382 VISIT(c, expr, s->v.Slice.upper);
5383 }
5384 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005385 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005386 }
5387
5388 if (s->v.Slice.step) {
5389 n++;
5390 VISIT(c, expr, s->v.Slice.step);
5391 }
5392 ADDOP_I(c, BUILD_SLICE, n);
5393 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005394}
5395
Thomas Wouters89f507f2006-12-13 04:49:30 +00005396/* End of the compiler section, beginning of the assembler section */
5397
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005399 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005400
5401 XXX must handle implicit jumps from one block to next
5402*/
5403
Thomas Wouters89f507f2006-12-13 04:49:30 +00005404struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005405 PyObject *a_bytecode; /* string containing bytecode */
5406 int a_offset; /* offset into bytecode */
5407 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005408 PyObject *a_lnotab; /* string containing lnotab */
5409 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005410 int a_prevlineno; /* lineno of last emitted line in line table */
5411 int a_lineno; /* lineno of last emitted instruction */
5412 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005413 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005414};
5415
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005416Py_LOCAL_INLINE(void)
5417stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005418{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005419 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005420 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005421 assert(b->b_startdepth < 0);
5422 b->b_startdepth = depth;
5423 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005424 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005425}
5426
5427/* Find the flow path that needs the largest stack. We assume that
5428 * cycles in the flow graph have no net effect on the stack depth.
5429 */
5430static int
5431stackdepth(struct compiler *c)
5432{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005433 basicblock *b, *entryblock = NULL;
5434 basicblock **stack, **sp;
5435 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005436 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005437 b->b_startdepth = INT_MIN;
5438 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005439 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005440 }
5441 if (!entryblock)
5442 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005443 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5444 if (!stack) {
5445 PyErr_NoMemory();
5446 return -1;
5447 }
5448
5449 sp = stack;
5450 stackdepth_push(&sp, entryblock, 0);
5451 while (sp != stack) {
5452 b = *--sp;
5453 int depth = b->b_startdepth;
5454 assert(depth >= 0);
5455 basicblock *next = b->b_next;
5456 for (int i = 0; i < b->b_iused; i++) {
5457 struct instr *instr = &b->b_instr[i];
5458 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5459 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005460 _Py_FatalErrorFormat(__func__,
5461 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005462 }
5463 int new_depth = depth + effect;
5464 if (new_depth > maxdepth) {
5465 maxdepth = new_depth;
5466 }
5467 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005468 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005469 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5470 assert(effect != PY_INVALID_STACK_EFFECT);
5471 int target_depth = depth + effect;
5472 if (target_depth > maxdepth) {
5473 maxdepth = target_depth;
5474 }
5475 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005476 stackdepth_push(&sp, instr->i_target, target_depth);
5477 }
5478 depth = new_depth;
5479 if (instr->i_opcode == JUMP_ABSOLUTE ||
5480 instr->i_opcode == JUMP_FORWARD ||
5481 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005482 instr->i_opcode == RAISE_VARARGS ||
5483 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005484 {
5485 /* remaining code is dead */
5486 next = NULL;
5487 break;
5488 }
5489 }
5490 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005491 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005492 stackdepth_push(&sp, next, depth);
5493 }
5494 }
5495 PyObject_Free(stack);
5496 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005497}
5498
5499static int
5500assemble_init(struct assembler *a, int nblocks, int firstlineno)
5501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005502 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005503 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005504 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005505 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005506 if (a->a_bytecode == NULL) {
5507 goto error;
5508 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005509 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005510 if (a->a_lnotab == NULL) {
5511 goto error;
5512 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005513 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005514 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005515 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005516 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005517 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005518error:
5519 Py_XDECREF(a->a_bytecode);
5520 Py_XDECREF(a->a_lnotab);
5521 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005522}
5523
5524static void
5525assemble_free(struct assembler *a)
5526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005527 Py_XDECREF(a->a_bytecode);
5528 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005529}
5530
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005531static int
5532blocksize(basicblock *b)
5533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 int i;
5535 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005538 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005539 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005540}
5541
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005542static int
Mark Shannon877df852020-11-12 09:43:29 +00005543assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005544{
Mark Shannon877df852020-11-12 09:43:29 +00005545 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 if (a->a_lnotab_off + 2 >= len) {
5547 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5548 return 0;
5549 }
Mark Shannon877df852020-11-12 09:43:29 +00005550 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005551 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005554 *lnotab++ = bdelta;
5555 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005557}
5558
Mark Shannon877df852020-11-12 09:43:29 +00005559/* Appends a range to the end of the line number table. See
5560 * Objects/lnotab_notes.txt for the description of the line number table. */
5561
5562static int
5563assemble_line_range(struct assembler *a)
5564{
5565 int ldelta, bdelta;
5566 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5567 if (bdelta == 0) {
5568 return 1;
5569 }
5570 if (a->a_lineno < 0) {
5571 ldelta = -128;
5572 }
5573 else {
5574 ldelta = a->a_lineno - a->a_prevlineno;
5575 a->a_prevlineno = a->a_lineno;
5576 while (ldelta > 127) {
5577 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5578 return 0;
5579 }
5580 ldelta -= 127;
5581 }
5582 while (ldelta < -127) {
5583 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5584 return 0;
5585 }
5586 ldelta += 127;
5587 }
5588 }
5589 assert(-128 <= ldelta && ldelta < 128);
5590 while (bdelta > 254) {
5591 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5592 return 0;
5593 }
5594 ldelta = a->a_lineno < 0 ? -128 : 0;
5595 bdelta -= 254;
5596 }
5597 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5598 return 0;
5599 }
5600 a->a_lineno_start = a->a_offset;
5601 return 1;
5602}
5603
5604static int
5605assemble_lnotab(struct assembler *a, struct instr *i)
5606{
5607 if (i->i_lineno == a->a_lineno) {
5608 return 1;
5609 }
5610 if (!assemble_line_range(a)) {
5611 return 0;
5612 }
5613 a->a_lineno = i->i_lineno;
5614 return 1;
5615}
5616
5617
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005618/* assemble_emit()
5619 Extend the bytecode with a new instruction.
5620 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005621*/
5622
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005623static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005624assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005625{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005626 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005628 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005629
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005630 arg = i->i_oparg;
5631 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005632 if (i->i_lineno && !assemble_lnotab(a, i))
5633 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005634 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005635 if (len > PY_SSIZE_T_MAX / 2)
5636 return 0;
5637 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5638 return 0;
5639 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005640 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005641 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005642 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005643 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005644}
5645
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005646static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005647assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005649 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005650 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005651 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005653 /* Compute the size of each block and fixup jump args.
5654 Replace block pointer with position in bytecode. */
5655 do {
5656 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005657 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 bsize = blocksize(b);
5659 b->b_offset = totsize;
5660 totsize += bsize;
5661 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005662 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005663 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5664 bsize = b->b_offset;
5665 for (i = 0; i < b->b_iused; i++) {
5666 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005667 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005668 /* Relative jumps are computed relative to
5669 the instruction pointer after fetching
5670 the jump instruction.
5671 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005672 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005673 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005675 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005676 instr->i_oparg -= bsize;
5677 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005678 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005679 if (instrsize(instr->i_oparg) != isize) {
5680 extended_arg_recompile = 1;
5681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 }
5684 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005686 /* XXX: This is an awful hack that could hurt performance, but
5687 on the bright side it should work until we come up
5688 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 The issue is that in the first loop blocksize() is called
5691 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005692 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 So we loop until we stop seeing new EXTENDED_ARGs.
5696 The only EXTENDED_ARGs that could be popping up are
5697 ones in jump instructions. So this should converge
5698 fairly quickly.
5699 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005700 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005701}
5702
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005703static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005704dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005707 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005709 tuple = PyTuple_New(size);
5710 if (tuple == NULL)
5711 return NULL;
5712 while (PyDict_Next(dict, &pos, &k, &v)) {
5713 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005714 Py_INCREF(k);
5715 assert((i - offset) < size);
5716 assert((i - offset) >= 0);
5717 PyTuple_SET_ITEM(tuple, i - offset, k);
5718 }
5719 return tuple;
5720}
5721
5722static PyObject *
5723consts_dict_keys_inorder(PyObject *dict)
5724{
5725 PyObject *consts, *k, *v;
5726 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5727
5728 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5729 if (consts == NULL)
5730 return NULL;
5731 while (PyDict_Next(dict, &pos, &k, &v)) {
5732 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005733 /* The keys of the dictionary can be tuples wrapping a contant.
5734 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5735 * the object we want is always second. */
5736 if (PyTuple_CheckExact(k)) {
5737 k = PyTuple_GET_ITEM(k, 1);
5738 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005739 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005740 assert(i < size);
5741 assert(i >= 0);
5742 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005743 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005744 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005745}
5746
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005747static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005748compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005750 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005751 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005753 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005754 if (ste->ste_nested)
5755 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005756 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005757 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005758 if (!ste->ste_generator && ste->ste_coroutine)
5759 flags |= CO_COROUTINE;
5760 if (ste->ste_generator && ste->ste_coroutine)
5761 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005762 if (ste->ste_varargs)
5763 flags |= CO_VARARGS;
5764 if (ste->ste_varkeywords)
5765 flags |= CO_VARKEYWORDS;
5766 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005768 /* (Only) inherit compilerflags in PyCF_MASK */
5769 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005770
Pablo Galindo90235812020-03-15 04:29:22 +00005771 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005772 ste->ste_coroutine &&
5773 !ste->ste_generator) {
5774 flags |= CO_COROUTINE;
5775 }
5776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005777 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005778}
5779
INADA Naokic2e16072018-11-26 21:23:22 +09005780// Merge *tuple* with constant cache.
5781// Unlike merge_consts_recursive(), this function doesn't work recursively.
5782static int
5783merge_const_tuple(struct compiler *c, PyObject **tuple)
5784{
5785 assert(PyTuple_CheckExact(*tuple));
5786
5787 PyObject *key = _PyCode_ConstantKey(*tuple);
5788 if (key == NULL) {
5789 return 0;
5790 }
5791
5792 // t is borrowed reference
5793 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5794 Py_DECREF(key);
5795 if (t == NULL) {
5796 return 0;
5797 }
5798 if (t == key) { // tuple is new constant.
5799 return 1;
5800 }
5801
5802 PyObject *u = PyTuple_GET_ITEM(t, 1);
5803 Py_INCREF(u);
5804 Py_DECREF(*tuple);
5805 *tuple = u;
5806 return 1;
5807}
5808
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005809static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005810makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005813 PyObject *names = NULL;
5814 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005815 PyObject *name = NULL;
5816 PyObject *freevars = NULL;
5817 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005818 Py_ssize_t nlocals;
5819 int nlocals_int;
5820 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005821 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005823 names = dict_keys_inorder(c->u->u_names, 0);
5824 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005825 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005826 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005827 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005828 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5829 if (!cellvars)
5830 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005831 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005832 if (!freevars)
5833 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005834
INADA Naokic2e16072018-11-26 21:23:22 +09005835 if (!merge_const_tuple(c, &names) ||
5836 !merge_const_tuple(c, &varnames) ||
5837 !merge_const_tuple(c, &cellvars) ||
5838 !merge_const_tuple(c, &freevars))
5839 {
5840 goto error;
5841 }
5842
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005843 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005844 assert(nlocals < INT_MAX);
5845 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005847 flags = compute_code_flags(c);
5848 if (flags < 0)
5849 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005850
Mark Shannon6e8128f2020-07-30 10:03:00 +01005851 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5852 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005853 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005854 }
INADA Naokic2e16072018-11-26 21:23:22 +09005855 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005856 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005857 goto error;
5858 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005859
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005860 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005861 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005862 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005863 maxdepth = stackdepth(c);
5864 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005865 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005866 goto error;
5867 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005868 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005869 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005870 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005871 varnames, freevars, cellvars, c->c_filename,
5872 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005873 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005874 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005875 Py_XDECREF(names);
5876 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 Py_XDECREF(name);
5878 Py_XDECREF(freevars);
5879 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005880 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005881}
5882
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005883
5884/* For debugging purposes only */
5885#if 0
5886static void
5887dump_instr(const struct instr *i)
5888{
Mark Shannon582aaf12020-08-04 17:30:11 +01005889 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5890 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005893 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005894 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005895 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005896 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005897 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5898 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005899}
5900
5901static void
5902dump_basicblock(const basicblock *b)
5903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005904 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005905 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5906 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907 if (b->b_instr) {
5908 int i;
5909 for (i = 0; i < b->b_iused; i++) {
5910 fprintf(stderr, " [%02d] ", i);
5911 dump_instr(b->b_instr + i);
5912 }
5913 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005914}
5915#endif
5916
Mark Shannon5977a792020-12-02 13:31:40 +00005917
5918static int
5919normalize_basic_block(basicblock *bb);
5920
Mark Shannon6e8128f2020-07-30 10:03:00 +01005921static int
5922optimize_cfg(struct assembler *a, PyObject *consts);
5923
Mark Shannon5977a792020-12-02 13:31:40 +00005924static int
5925ensure_exits_have_lineno(struct compiler *c);
5926
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005927static PyCodeObject *
5928assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 basicblock *b, *entryblock;
5931 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005932 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005933 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005934 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 /* Make sure every block that falls off the end returns None.
5937 XXX NEXT_BLOCK() isn't quite right, because if the last
5938 block ends with a jump or return b_next shouldn't set.
5939 */
5940 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005941 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005942 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005943 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005944 ADDOP(c, RETURN_VALUE);
5945 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005946
Mark Shannon5977a792020-12-02 13:31:40 +00005947 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
5948 if (normalize_basic_block(b)) {
5949 goto error;
5950 }
5951 }
5952
5953 if (ensure_exits_have_lineno(c)) {
5954 goto error;
5955 }
5956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005957 nblocks = 0;
5958 entryblock = NULL;
5959 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5960 nblocks++;
5961 entryblock = b;
5962 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005964 /* Set firstlineno if it wasn't explicitly set. */
5965 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005966 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005968 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 c->u->u_firstlineno = 1;
5970 }
Mark Shannon5977a792020-12-02 13:31:40 +00005971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005972 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5973 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005974 a.a_entry = entryblock;
5975 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005976
Mark Shannon6e8128f2020-07-30 10:03:00 +01005977 consts = consts_dict_keys_inorder(c->u->u_consts);
5978 if (consts == NULL) {
5979 goto error;
5980 }
5981 if (optimize_cfg(&a, consts)) {
5982 goto error;
5983 }
5984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005985 /* Can't modify the bytecode after computing jump offsets. */
5986 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005987
Mark Shannoncc75ab72020-11-12 19:49:33 +00005988 /* Emit code. */
5989 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005990 for (j = 0; j < b->b_iused; j++)
5991 if (!assemble_emit(&a, &b->b_instr[j]))
5992 goto error;
5993 }
Mark Shannon877df852020-11-12 09:43:29 +00005994 if (!assemble_line_range(&a)) {
5995 return 0;
5996 }
5997 /* Emit sentinel at end of line number table */
5998 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
5999 goto error;
6000 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006002 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6003 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006004 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006005 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006006
Mark Shannon6e8128f2020-07-30 10:03:00 +01006007 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006008 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006009 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006010 assemble_free(&a);
6011 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006012}
Georg Brandl8334fd92010-12-04 10:26:46 +00006013
6014#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006015PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006016PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6017 PyArena *arena)
6018{
6019 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6020}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006021
6022
6023/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6024 with LOAD_CONST (c1, c2, ... cn).
6025 The consts table must still be in list form so that the
6026 new constant (c1, c2, ... cn) can be appended.
6027 Called with codestr pointing to the first LOAD_CONST.
6028*/
6029static int
6030fold_tuple_on_constants(struct instr *inst,
6031 int n, PyObject *consts)
6032{
6033 /* Pre-conditions */
6034 assert(PyList_CheckExact(consts));
6035 assert(inst[n].i_opcode == BUILD_TUPLE);
6036 assert(inst[n].i_oparg == n);
6037
6038 for (int i = 0; i < n; i++) {
6039 if (inst[i].i_opcode != LOAD_CONST) {
6040 return 0;
6041 }
6042 }
6043
6044 /* Buildup new tuple of constants */
6045 PyObject *newconst = PyTuple_New(n);
6046 if (newconst == NULL) {
6047 return -1;
6048 }
6049 for (int i = 0; i < n; i++) {
6050 int arg = inst[i].i_oparg;
6051 PyObject *constant = PyList_GET_ITEM(consts, arg);
6052 Py_INCREF(constant);
6053 PyTuple_SET_ITEM(newconst, i, constant);
6054 }
6055 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006056 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006057 Py_DECREF(newconst);
6058 PyErr_SetString(PyExc_OverflowError, "too many constants");
6059 return -1;
6060 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006061 if (PyList_Append(consts, newconst)) {
6062 Py_DECREF(newconst);
6063 return -1;
6064 }
6065 Py_DECREF(newconst);
6066 for (int i = 0; i < n; i++) {
6067 inst[i].i_opcode = NOP;
6068 }
6069 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006070 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006071 return 0;
6072}
6073
Mark Shannon28b75c82020-12-23 11:43:10 +00006074
6075static int
6076eliminate_jump_to_jump(basicblock *bb, int opcode) {
6077 assert (bb->b_iused > 0);
6078 struct instr *inst = &bb->b_instr[bb->b_iused-1];
6079 assert (is_jump(inst));
6080 assert (inst->i_target->b_iused > 0);
6081 struct instr *target = &inst->i_target->b_instr[0];
6082 if (inst->i_target == target->i_target) {
6083 /* Nothing to do */
6084 return 0;
6085 }
6086 int lineno = target->i_lineno;
6087 if (add_jump_to_block(bb, opcode, lineno, target->i_target) == 0) {
6088 return -1;
6089 }
6090 assert (bb->b_iused >= 2);
6091 bb->b_instr[bb->b_iused-2].i_opcode = NOP;
6092 return 0;
6093}
6094
Mark Shannoncc75ab72020-11-12 19:49:33 +00006095/* Maximum size of basic block that should be copied in optimizer */
6096#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006097
6098/* Optimization */
6099static int
6100optimize_basic_block(basicblock *bb, PyObject *consts)
6101{
6102 assert(PyList_CheckExact(consts));
6103 struct instr nop;
6104 nop.i_opcode = NOP;
6105 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006106 for (int i = 0; i < bb->b_iused; i++) {
6107 struct instr *inst = &bb->b_instr[i];
6108 int oparg = inst->i_oparg;
6109 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006110 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006111 /* Skip over empty basic blocks. */
6112 while (inst->i_target->b_iused == 0) {
6113 inst->i_target = inst->i_target->b_next;
6114 }
6115 target = &inst->i_target->b_instr[0];
6116 }
6117 else {
6118 target = &nop;
6119 }
6120 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006121 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006122 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006123 {
6124 PyObject* cnt;
6125 int is_true;
6126 int jump_if_true;
6127 switch(nextop) {
6128 case POP_JUMP_IF_FALSE:
6129 case POP_JUMP_IF_TRUE:
6130 cnt = PyList_GET_ITEM(consts, oparg);
6131 is_true = PyObject_IsTrue(cnt);
6132 if (is_true == -1) {
6133 goto error;
6134 }
6135 inst->i_opcode = NOP;
6136 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6137 if (is_true == jump_if_true) {
6138 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6139 bb->b_nofallthrough = 1;
6140 }
6141 else {
6142 bb->b_instr[i+1].i_opcode = NOP;
6143 }
6144 break;
6145 case JUMP_IF_FALSE_OR_POP:
6146 case JUMP_IF_TRUE_OR_POP:
6147 cnt = PyList_GET_ITEM(consts, oparg);
6148 is_true = PyObject_IsTrue(cnt);
6149 if (is_true == -1) {
6150 goto error;
6151 }
6152 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6153 if (is_true == jump_if_true) {
6154 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6155 bb->b_nofallthrough = 1;
6156 }
6157 else {
6158 inst->i_opcode = NOP;
6159 bb->b_instr[i+1].i_opcode = NOP;
6160 }
6161 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006162 }
6163 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006164 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006165
6166 /* Try to fold tuples of constants.
6167 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6168 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6169 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6170 case BUILD_TUPLE:
6171 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6172 switch(oparg) {
6173 case 1:
6174 inst->i_opcode = NOP;
6175 bb->b_instr[i+1].i_opcode = NOP;
6176 break;
6177 case 2:
6178 inst->i_opcode = ROT_TWO;
6179 bb->b_instr[i+1].i_opcode = NOP;
6180 break;
6181 case 3:
6182 inst->i_opcode = ROT_THREE;
6183 bb->b_instr[i+1].i_opcode = ROT_TWO;
6184 }
6185 break;
6186 }
6187 if (i >= oparg) {
6188 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6189 goto error;
6190 }
6191 }
6192 break;
6193
6194 /* Simplify conditional jump to conditional jump where the
6195 result of the first test implies the success of a similar
6196 test or the failure of the opposite test.
6197 Arises in code like:
6198 "a and b or c"
6199 "(a and b) and c"
6200 "(a or b) or c"
6201 "(a or b) and c"
6202 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6203 --> x:JUMP_IF_FALSE_OR_POP z
6204 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6205 --> x:POP_JUMP_IF_FALSE y+1
6206 where y+1 is the instruction following the second test.
6207 */
6208 case JUMP_IF_FALSE_OR_POP:
6209 switch(target->i_opcode) {
6210 case POP_JUMP_IF_FALSE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006211 if (inst->i_lineno == target->i_lineno) {
6212 *inst = *target;
6213 i--;
6214 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006215 break;
6216 case JUMP_ABSOLUTE:
6217 case JUMP_FORWARD:
6218 case JUMP_IF_FALSE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006219 if (inst->i_lineno == target->i_lineno &&
6220 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006221 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006222 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006223 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006224 break;
6225 case JUMP_IF_TRUE_OR_POP:
6226 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006227 if (inst->i_lineno == target->i_lineno) {
6228 inst->i_opcode = POP_JUMP_IF_FALSE;
6229 inst->i_target = inst->i_target->b_next;
6230 --i;
6231 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006232 break;
6233 }
6234 break;
6235
6236 case JUMP_IF_TRUE_OR_POP:
6237 switch(target->i_opcode) {
6238 case POP_JUMP_IF_TRUE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006239 if (inst->i_lineno == target->i_lineno) {
6240 *inst = *target;
6241 i--;
6242 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006243 break;
6244 case JUMP_ABSOLUTE:
6245 case JUMP_FORWARD:
6246 case JUMP_IF_TRUE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006247 if (inst->i_lineno == target->i_lineno &&
6248 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006249 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006250 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006251 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006252 break;
6253 case JUMP_IF_FALSE_OR_POP:
6254 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006255 if (inst->i_lineno == target->i_lineno) {
6256 inst->i_opcode = POP_JUMP_IF_TRUE;
6257 inst->i_target = inst->i_target->b_next;
6258 --i;
6259 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006260 break;
6261 }
6262 break;
6263
6264 case POP_JUMP_IF_FALSE:
6265 switch(target->i_opcode) {
6266 case JUMP_ABSOLUTE:
6267 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006268 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006269 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006270 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006271 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006272 break;
6273 }
6274 break;
6275
6276 case POP_JUMP_IF_TRUE:
6277 switch(target->i_opcode) {
6278 case JUMP_ABSOLUTE:
6279 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006280 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006281 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006282 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006283 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006284 break;
6285 }
6286 break;
6287
6288 case JUMP_ABSOLUTE:
6289 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006290 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006291 switch(target->i_opcode) {
6292 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006293 if (eliminate_jump_to_jump(bb, inst->i_opcode)) {
6294 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006295 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006296 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006297
Mark Shannon6e8128f2020-07-30 10:03:00 +01006298 case JUMP_ABSOLUTE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006299 if (eliminate_jump_to_jump(bb, JUMP_ABSOLUTE)) {
6300 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006301 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006302 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006303 default:
6304 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6305 basicblock *to_copy = inst->i_target;
6306 inst->i_opcode = NOP;
6307 for (i = 0; i < to_copy->b_iused; i++) {
6308 int index = compiler_next_instr(bb);
6309 if (index < 0) {
6310 return -1;
6311 }
6312 bb->b_instr[index] = to_copy->b_instr[i];
6313 }
6314 bb->b_exit = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006315 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006316 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006317 }
6318 }
6319 return 0;
6320error:
6321 return -1;
6322}
6323
6324
6325static void
6326clean_basic_block(basicblock *bb) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006327 /* Remove NOPs. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006328 int dest = 0;
Mark Shannon877df852020-11-12 09:43:29 +00006329 int prev_lineno = -1;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006330 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006331 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006332 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006333 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006334 if (lineno < 0) {
6335 continue;
6336 }
Mark Shannon266b4622020-11-17 19:30:14 +00006337 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006338 if (prev_lineno == lineno) {
6339 continue;
6340 }
Mark Shannon266b4622020-11-17 19:30:14 +00006341 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006342 if (src < bb->b_iused - 1) {
6343 int next_lineno = bb->b_instr[src+1].i_lineno;
6344 if (next_lineno < 0 || next_lineno == lineno) {
6345 bb->b_instr[src+1].i_lineno = lineno;
6346 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006347 }
6348 }
Mark Shannon266b4622020-11-17 19:30:14 +00006349 else {
6350 basicblock* next = bb->b_next;
6351 while (next && next->b_iused == 0) {
6352 next = next->b_next;
6353 }
6354 /* or if last instruction in BB and next BB has same line number */
6355 if (next) {
6356 if (lineno == next->b_instr[0].i_lineno) {
6357 continue;
6358 }
6359 }
6360 }
6361
Mark Shannon6e8128f2020-07-30 10:03:00 +01006362 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006363 if (dest != src) {
6364 bb->b_instr[dest] = bb->b_instr[src];
6365 }
6366 dest++;
6367 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006368 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006369 assert(dest <= bb->b_iused);
6370 bb->b_iused = dest;
6371}
6372
Mark Shannon266b4622020-11-17 19:30:14 +00006373static int
6374normalize_basic_block(basicblock *bb) {
6375 /* Mark blocks as exit and/or nofallthrough.
6376 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006377 for (int i = 0; i < bb->b_iused; i++) {
6378 switch(bb->b_instr[i].i_opcode) {
6379 case RETURN_VALUE:
6380 case RAISE_VARARGS:
6381 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006382 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00006383 bb->b_nofallthrough = 1;
6384 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006385 case JUMP_ABSOLUTE:
6386 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006387 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006388 /* fall through */
6389 case POP_JUMP_IF_FALSE:
6390 case POP_JUMP_IF_TRUE:
6391 case JUMP_IF_FALSE_OR_POP:
6392 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00006393 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00006394 if (i != bb->b_iused-1) {
6395 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6396 return -1;
6397 }
Mark Shannon5977a792020-12-02 13:31:40 +00006398 /* Skip over empty basic blocks. */
6399 while (bb->b_instr[i].i_target->b_iused == 0) {
6400 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
6401 }
6402
Mark Shannoncc75ab72020-11-12 19:49:33 +00006403 }
6404 }
Mark Shannon266b4622020-11-17 19:30:14 +00006405 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006406}
6407
Mark Shannon6e8128f2020-07-30 10:03:00 +01006408static int
6409mark_reachable(struct assembler *a) {
6410 basicblock **stack, **sp;
6411 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6412 if (stack == NULL) {
6413 return -1;
6414 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006415 a->a_entry->b_reachable = 1;
6416 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006417 while (sp > stack) {
6418 basicblock *b = *(--sp);
Mark Shannoncc75ab72020-11-12 19:49:33 +00006419 if (b->b_next && !b->b_nofallthrough && b->b_next->b_reachable == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006420 b->b_next->b_reachable = 1;
6421 *sp++ = b->b_next;
6422 }
6423 for (int i = 0; i < b->b_iused; i++) {
6424 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006425 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006426 target = b->b_instr[i].i_target;
6427 if (target->b_reachable == 0) {
6428 target->b_reachable = 1;
6429 *sp++ = target;
6430 }
6431 }
6432 }
6433 }
6434 PyObject_Free(stack);
6435 return 0;
6436}
6437
Mark Shannon5977a792020-12-02 13:31:40 +00006438/* If an instruction has no line number, but it's predecessor in the BB does,
6439 * then copy the line number. This reduces the size of the line number table,
6440 * but has no impact on the generated line number events.
6441 */
6442static void
6443minimize_lineno_table(struct assembler *a) {
6444 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6445 int prev_lineno = -1;
6446 for (int i = 0; i < b->b_iused; i++) {
6447 if (b->b_instr[i].i_lineno < 0) {
6448 b->b_instr[i].i_lineno = prev_lineno;
6449 }
6450 else {
6451 prev_lineno = b->b_instr[i].i_lineno;
6452 }
6453 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006454
Mark Shannon5977a792020-12-02 13:31:40 +00006455 }
6456}
6457
6458/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01006459 The consts object should still be in list form to allow new constants
6460 to be appended.
6461
6462 All transformations keep the code size the same or smaller.
6463 For those that reduce size, the gaps are initially filled with
6464 NOPs. Later those NOPs are removed.
6465*/
6466
6467static int
6468optimize_cfg(struct assembler *a, PyObject *consts)
6469{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006470 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006471 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006472 return -1;
6473 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006474 clean_basic_block(b);
6475 assert(b->b_reachable == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006476 }
6477 if (mark_reachable(a)) {
6478 return -1;
6479 }
6480 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006481 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6482 if (b->b_reachable == 0) {
6483 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05306484 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006485 }
6486 }
Om Gc71581c2020-12-16 17:48:05 +05306487 /* Delete jump instructions made redundant by previous step. If a non-empty
6488 block ends with a jump instruction, check if the next non-empty block
6489 reached through normal flow control is the target of that jump. If it
6490 is, then the jump instruction is redundant and can be deleted.
6491 */
6492 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6493 if (b->b_iused > 0) {
6494 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
6495 if (b_last_instr->i_opcode == POP_JUMP_IF_FALSE ||
6496 b_last_instr->i_opcode == POP_JUMP_IF_TRUE ||
6497 b_last_instr->i_opcode == JUMP_ABSOLUTE ||
6498 b_last_instr->i_opcode == JUMP_FORWARD) {
6499 basicblock *b_next_act = b->b_next;
6500 while (b_next_act != NULL && b_next_act->b_iused == 0) {
6501 b_next_act = b_next_act->b_next;
6502 }
6503 if (b_last_instr->i_target == b_next_act) {
6504 b->b_nofallthrough = 0;
6505 switch(b_last_instr->i_opcode) {
6506 case POP_JUMP_IF_FALSE:
6507 case POP_JUMP_IF_TRUE:
6508 b_last_instr->i_opcode = POP_TOP;
6509 b_last_instr->i_target = NULL;
6510 b_last_instr->i_oparg = 0;
6511 break;
6512 case JUMP_ABSOLUTE:
6513 case JUMP_FORWARD:
6514 b_last_instr->i_opcode = NOP;
6515 clean_basic_block(b);
6516 break;
6517 }
6518 /* The blocks after this one are now reachable through it */
6519 b_next_act = b->b_next;
6520 while (b_next_act != NULL && b_next_act->b_iused == 0) {
6521 b_next_act->b_reachable = 1;
6522 b_next_act = b_next_act->b_next;
6523 }
6524 }
6525 }
6526 }
6527 }
Mark Shannon5977a792020-12-02 13:31:40 +00006528 minimize_lineno_table(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006529 return 0;
6530}
6531
Mark Shannon5977a792020-12-02 13:31:40 +00006532static inline int
6533is_exit_without_lineno(basicblock *b) {
6534 return b->b_exit && b->b_instr[0].i_lineno < 0;
6535}
6536
6537/* PEP 626 mandates that the f_lineno of a frame is correct
6538 * after a frame terminates. It would be prohibitively expensive
6539 * to continuously update the f_lineno field at runtime,
6540 * so we make sure that all exiting instruction (raises and returns)
6541 * have a valid line number, allowing us to compute f_lineno lazily.
6542 * We can do this by duplicating the exit blocks without line number
6543 * so that none have more than one predecessor. We can then safely
6544 * copy the line number from the sole predecessor block.
6545 */
6546static int
6547ensure_exits_have_lineno(struct compiler *c)
6548{
Mark Shannoneaccc122020-12-04 15:22:12 +00006549 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006550 /* Copy all exit blocks without line number that are targets of a jump.
6551 */
6552 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6553 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
6554 switch (b->b_instr[b->b_iused-1].i_opcode) {
6555 /* Note: Only actual jumps, not exception handlers */
6556 case SETUP_ASYNC_WITH:
6557 case SETUP_WITH:
6558 case SETUP_FINALLY:
6559 continue;
6560 }
6561 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6562 if (is_exit_without_lineno(target)) {
6563 basicblock *new_target = compiler_copy_block(c, target);
6564 if (new_target == NULL) {
6565 return -1;
6566 }
6567 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6568 b->b_instr[b->b_iused-1].i_target = new_target;
6569 }
6570 }
Mark Shannoneaccc122020-12-04 15:22:12 +00006571 entry = b;
6572 }
6573 assert(entry != NULL);
6574 if (is_exit_without_lineno(entry)) {
6575 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00006576 }
6577 /* Any remaining reachable exit blocks without line number can only be reached by
6578 * fall through, and thus can only have a single predecessor */
6579 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6580 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
6581 if (is_exit_without_lineno(b->b_next)) {
6582 assert(b->b_next->b_iused > 0);
6583 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6584 }
6585 }
6586 }
6587 return 0;
6588}
6589
6590
Mark Shannon6e8128f2020-07-30 10:03:00 +01006591/* Retained for API compatibility.
6592 * Optimization is now done in optimize_cfg */
6593
6594PyObject *
6595PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6596 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6597{
6598 Py_INCREF(code);
6599 return code;
6600}
6601