blob: ea9d6781b9c156ad3d9f01a7f7ac3bac5a7a691a [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Mark Shannon6e8128f2020-07-30 10:03:00 +010012 * 5. Optimize the byte code (peephole optimizations).
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Victor Stinnerc9bc2902020-10-27 02:24:34 +010025#include "pycore_long.h" // _PyLong_GetZero()
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Mark Shannon582aaf12020-08-04 17:30:11 +010031#define NEED_OPCODE_JUMP_TABLES
Guido van Rossum10dc2e81990-11-18 17:27:39 +000032#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030033#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035#define DEFAULT_BLOCK_SIZE 16
36#define DEFAULT_BLOCKS 8
37#define DEFAULT_CODE_SIZE 128
38#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000039
Nick Coghlan650f0d02007-04-15 12:05:43 +000040#define COMP_GENEXP 0
41#define COMP_LISTCOMP 1
42#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000043#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000044
Pablo Galindo90235812020-03-15 04:29:22 +000045#define IS_TOP_LEVEL_AWAIT(c) ( \
46 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
47 && (c->u->u_ste->ste_type == ModuleBlock))
48
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000049struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Mark Shannon582aaf12020-08-04 17:30:11 +010056#define LOG_BITS_PER_INT 5
57#define MASK_LOW_LOG_BITS 31
58
59static inline int
60is_bit_set_in_table(uint32_t *table, int bitindex) {
61 /* Is the relevant bit set in the relevant word? */
62 /* 256 bits fit into 8 32-bits words.
63 * Word is indexed by (bitindex>>ln(size of int in bits)).
64 * Bit within word is the low bits of bitindex.
65 */
66 uint32_t word = table[bitindex >> LOG_BITS_PER_INT];
67 return (word >> (bitindex & MASK_LOW_LOG_BITS)) & 1;
68}
69
70static inline int
71is_relative_jump(struct instr *i)
72{
73 return is_bit_set_in_table(_PyOpcode_RelativeJump, i->i_opcode);
74}
75
76static inline int
77is_jump(struct instr *i)
78{
79 return is_bit_set_in_table(_PyOpcode_Jump, i->i_opcode);
80}
81
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000083 /* Each basicblock in a compilation unit is linked via b_list in the
84 reverse order that the block are allocated. b_list points to the next
85 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 struct basicblock_ *b_list;
87 /* number of instructions used */
88 int b_iused;
89 /* length of instruction array (b_instr) */
90 int b_ialloc;
91 /* pointer to an array of instructions, initially NULL */
92 struct instr *b_instr;
93 /* If b_next is non-NULL, it is a pointer to the next
94 block reached by normal control flow. */
95 struct basicblock_ *b_next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 /* b_return is true if a RETURN_VALUE opcode is inserted. */
97 unsigned b_return : 1;
Mark Shannon6e8128f2020-07-30 10:03:00 +010098 unsigned b_reachable : 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +000099 /* Basic block has no fall through (it ends with a return, raise or jump) */
100 unsigned b_nofallthrough : 1;
101 /* Basic block exits scope (it ends with a return or raise) */
102 unsigned b_exit : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 /* depth of stack upon entry of block, computed by stackdepth() */
104 int b_startdepth;
105 /* instruction offset for block, computed by assemble_jump_offsets() */
106 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107} basicblock;
108
109/* fblockinfo tracks the current frame block.
110
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000111A frame block is used to handle loops, try/except, and try/finally.
112It's called a frame block to distinguish it from a basic block in the
113compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114*/
115
Mark Shannon02d126a2020-09-25 14:04:19 +0100116enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
117 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118
119struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 enum fblocktype fb_type;
121 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200122 /* (optional) type-specific exit or cleanup block */
123 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +0000124 /* (optional) additional information required for unwinding */
125 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126};
127
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100128enum {
129 COMPILER_SCOPE_MODULE,
130 COMPILER_SCOPE_CLASS,
131 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400132 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400133 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100134 COMPILER_SCOPE_COMPREHENSION,
135};
136
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137/* The following items change on entry and exit of code blocks.
138 They must be saved and restored when returning to a block.
139*/
140struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400144 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100145 int u_scope_type;
146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 /* The following fields are dicts that map objects to
148 the index of them in co_XXX. The index is used as
149 the argument for opcodes that refer to those collections.
150 */
151 PyObject *u_consts; /* all constants */
152 PyObject *u_names; /* all names */
153 PyObject *u_varnames; /* local variables */
154 PyObject *u_cellvars; /* cell variables */
155 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Victor Stinnerf8e32212013-11-19 23:56:34 +0100159 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100160 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100161 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* Pointer to the most recently allocated block. By following b_list
163 members, you can reach all early allocated blocks. */
164 basicblock *u_blocks;
165 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 int u_nfblocks;
168 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 int u_firstlineno; /* the first lineno of the block */
171 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000172 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173};
174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000177The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000179managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000180
181Note that we don't track recursion levels during compilation - the
182task of detecting and rejecting excessive levels of nesting is
183handled by the symbol analysis pass.
184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185*/
186
187struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200188 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 struct symtable *c_st;
190 PyFutureFeatures *c_future; /* pointer to module's __future__ */
191 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
Georg Brandl8334fd92010-12-04 10:26:46 +0000193 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 int c_interactive; /* true if in interactive mode */
195 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100196 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
197 if this value is different from zero.
198 This can be used to temporarily visit
199 nodes without emitting bytecode to
200 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201
INADA Naokic2e16072018-11-26 21:23:22 +0900202 PyObject *c_const_cache; /* Python dict holding all constants,
203 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 struct compiler_unit *u; /* compiler state for current block */
205 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
206 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207};
208
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100209static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210static void compiler_free(struct compiler *);
211static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500212static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100214static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100215static int compiler_addop_j(struct compiler *, int, basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200217static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
219
220static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
221static int compiler_visit_stmt(struct compiler *, stmt_ty);
222static int compiler_visit_keyword(struct compiler *, keyword_ty);
223static int compiler_visit_expr(struct compiler *, expr_ty);
224static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700225static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200226static int compiler_subscript(struct compiler *, expr_ty);
227static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228
Andy Lester76d58772020-03-10 21:18:12 -0500229static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100230static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200231static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500233static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400234static int compiler_async_with(struct compiler *, stmt_ty, int);
235static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100236static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100237 asdl_expr_seq *args,
238 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500239static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400240static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000241
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700242static int compiler_sync_comprehension_generator(
243 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100244 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200245 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700246 expr_ty elt, expr_ty val, int type);
247
248static int compiler_async_comprehension_generator(
249 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100250 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200251 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700252 expr_ty elt, expr_ty val, int type);
253
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000255static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400257#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000260_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* Name mangling: __private becomes _classname__private.
263 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 PyObject *result;
265 size_t nlen, plen, ipriv;
266 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200268 PyUnicode_READ_CHAR(ident, 0) != '_' ||
269 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 Py_INCREF(ident);
271 return ident;
272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200273 nlen = PyUnicode_GET_LENGTH(ident);
274 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 The only time a name with a dot can occur is when
278 we are compiling an import statement that has a
279 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 TODO(jhylton): Decide whether we want to support
282 mangling of the module name, e.g. __M.X.
283 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200284 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
285 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
286 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Py_INCREF(ident);
288 return ident; /* Don't mangle __whatever__ */
289 }
290 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200291 ipriv = 0;
292 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
293 ipriv++;
294 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_INCREF(ident);
296 return ident; /* Don't mangle if class is just underscores */
297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200298 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000299
Antoine Pitrou55bff892013-04-06 21:21:04 +0200300 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
301 PyErr_SetString(PyExc_OverflowError,
302 "private identifier too large to be mangled");
303 return NULL;
304 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200306 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
307 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
308 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
309
310 result = PyUnicode_New(1 + nlen + plen, maxchar);
311 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200313 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
314 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200315 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
316 Py_DECREF(result);
317 return NULL;
318 }
319 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
320 Py_DECREF(result);
321 return NULL;
322 }
Victor Stinner8f825062012-04-27 13:55:39 +0200323 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200324 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000325}
326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327static int
328compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000331
INADA Naokic2e16072018-11-26 21:23:22 +0900332 c->c_const_cache = PyDict_New();
333 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900335 }
336
337 c->c_stack = PyList_New(0);
338 if (!c->c_stack) {
339 Py_CLEAR(c->c_const_cache);
340 return 0;
341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344}
345
346PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200347PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
348 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 struct compiler c;
351 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200352 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (!__doc__) {
356 __doc__ = PyUnicode_InternFromString("__doc__");
357 if (!__doc__)
358 return NULL;
359 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000360 if (!__annotations__) {
361 __annotations__ = PyUnicode_InternFromString("__annotations__");
362 if (!__annotations__)
363 return NULL;
364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (!compiler_init(&c))
366 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200367 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 c.c_filename = filename;
369 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200370 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c.c_future == NULL)
372 goto finally;
373 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 flags = &local_flags;
375 }
376 merged = c.c_future->ff_features | flags->cf_flags;
377 c.c_future->ff_features = merged;
378 flags->cf_flags = merged;
379 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200380 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100382 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383
Pablo Galindod112c602020-03-18 23:02:09 +0000384 _PyASTOptimizeState state;
385 state.optimize = c.c_optimize;
386 state.ff_features = merged;
387
388 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900389 goto finally;
390 }
391
Victor Stinner14e461d2013-08-26 22:28:21 +0200392 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (c.c_st == NULL) {
394 if (!PyErr_Occurred())
395 PyErr_SetString(PyExc_SystemError, "no symtable");
396 goto finally;
397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400
Thomas Wouters1175c432006-02-27 22:49:54 +0000401 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 compiler_free(&c);
403 assert(co || PyErr_Occurred());
404 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405}
406
407PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200408PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
409 int optimize, PyArena *arena)
410{
411 PyObject *filename;
412 PyCodeObject *co;
413 filename = PyUnicode_DecodeFSDefault(filename_str);
414 if (filename == NULL)
415 return NULL;
416 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
417 Py_DECREF(filename);
418 return co;
419
420}
421
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000422static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (c->c_st)
426 PySymtable_Free(c->c_st);
427 if (c->c_future)
428 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200429 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900430 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000432}
433
Guido van Rossum79f25d91997-04-29 20:08:16 +0000434static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 Py_ssize_t i, n;
438 PyObject *v, *k;
439 PyObject *dict = PyDict_New();
440 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 n = PyList_Size(list);
443 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100444 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (!v) {
446 Py_DECREF(dict);
447 return NULL;
448 }
449 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300450 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 Py_DECREF(v);
452 Py_DECREF(dict);
453 return NULL;
454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(v);
456 }
457 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458}
459
460/* Return new dict containing names from src that match scope(s).
461
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000462src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464values are integers, starting at offset and increasing by one for
465each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466*/
467
468static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100469dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700471 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500473 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 assert(offset >= 0);
476 if (dest == NULL)
477 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478
Meador Inge2ca63152012-07-18 14:20:11 -0500479 /* Sort the keys so that we have a deterministic order on the indexes
480 saved in the returned dictionary. These indexes are used as indexes
481 into the free and cell var storage. Therefore if they aren't
482 deterministic, then the generated bytecode is not deterministic.
483 */
484 sorted_keys = PyDict_Keys(src);
485 if (sorted_keys == NULL)
486 return NULL;
487 if (PyList_Sort(sorted_keys) != 0) {
488 Py_DECREF(sorted_keys);
489 return NULL;
490 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500491 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500492
493 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* XXX this should probably be a macro in symtable.h */
495 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500496 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200497 v = PyDict_GetItemWithError(src, k);
498 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 vi = PyLong_AS_LONG(v);
500 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300503 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500505 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_DECREF(dest);
507 return NULL;
508 }
509 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300510 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500511 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_DECREF(item);
513 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return NULL;
515 }
516 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 }
518 }
Meador Inge2ca63152012-07-18 14:20:11 -0500519 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000521}
522
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523static void
524compiler_unit_check(struct compiler_unit *u)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 basicblock *block;
527 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700528 assert((uintptr_t)block != 0xcbcbcbcbU);
529 assert((uintptr_t)block != 0xfbfbfbfbU);
530 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (block->b_instr != NULL) {
532 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100533 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 assert(block->b_ialloc >= block->b_iused);
535 }
536 else {
537 assert (block->b_iused == 0);
538 assert (block->b_ialloc == 0);
539 }
540 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541}
542
543static void
544compiler_unit_free(struct compiler_unit *u)
545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 compiler_unit_check(u);
549 b = u->u_blocks;
550 while (b != NULL) {
551 if (b->b_instr)
552 PyObject_Free((void *)b->b_instr);
553 next = b->b_list;
554 PyObject_Free((void *)b);
555 b = next;
556 }
557 Py_CLEAR(u->u_ste);
558 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400559 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 Py_CLEAR(u->u_consts);
561 Py_CLEAR(u->u_names);
562 Py_CLEAR(u->u_varnames);
563 Py_CLEAR(u->u_freevars);
564 Py_CLEAR(u->u_cellvars);
565 Py_CLEAR(u->u_private);
566 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567}
568
569static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100570compiler_enter_scope(struct compiler *c, identifier name,
571 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100574 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575
Andy Lester7668a8b2020-03-24 23:26:44 -0500576 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 struct compiler_unit));
578 if (!u) {
579 PyErr_NoMemory();
580 return 0;
581 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100582 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100584 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 u->u_kwonlyargcount = 0;
586 u->u_ste = PySymtable_Lookup(c->c_st, key);
587 if (!u->u_ste) {
588 compiler_unit_free(u);
589 return 0;
590 }
591 Py_INCREF(name);
592 u->u_name = name;
593 u->u_varnames = list2dict(u->u_ste->ste_varnames);
594 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
595 if (!u->u_varnames || !u->u_cellvars) {
596 compiler_unit_free(u);
597 return 0;
598 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500599 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000600 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500601 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300602 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500603 int res;
604 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200605 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500606 name = _PyUnicode_FromId(&PyId___class__);
607 if (!name) {
608 compiler_unit_free(u);
609 return 0;
610 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100611 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500612 if (res < 0) {
613 compiler_unit_free(u);
614 return 0;
615 }
616 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200619 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (!u->u_freevars) {
621 compiler_unit_free(u);
622 return 0;
623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 u->u_blocks = NULL;
626 u->u_nfblocks = 0;
627 u->u_firstlineno = lineno;
628 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000629 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 u->u_consts = PyDict_New();
631 if (!u->u_consts) {
632 compiler_unit_free(u);
633 return 0;
634 }
635 u->u_names = PyDict_New();
636 if (!u->u_names) {
637 compiler_unit_free(u);
638 return 0;
639 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 /* Push the old compiler_unit on the stack. */
644 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400645 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
647 Py_XDECREF(capsule);
648 compiler_unit_free(u);
649 return 0;
650 }
651 Py_DECREF(capsule);
652 u->u_private = c->u->u_private;
653 Py_XINCREF(u->u_private);
654 }
655 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100658
659 block = compiler_new_block(c);
660 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100662 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400664 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
665 if (!compiler_set_qualname(c))
666 return 0;
667 }
668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000672static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673compiler_exit_scope(struct compiler *c)
674{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100675 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 c->c_nestlevel--;
679 compiler_unit_free(c->u);
680 /* Restore c->u to the parent unit. */
681 n = PyList_GET_SIZE(c->c_stack) - 1;
682 if (n >= 0) {
683 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400684 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 assert(c->u);
686 /* we are deleting from a list so this really shouldn't fail */
687 if (PySequence_DelItem(c->c_stack, n) < 0)
688 Py_FatalError("compiler_exit_scope()");
689 compiler_unit_check(c->u);
690 }
691 else
692 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000693
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694}
695
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696static int
697compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100699 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400700 _Py_static_string(dot_locals, ".<locals>");
701 Py_ssize_t stack_size;
702 struct compiler_unit *u = c->u;
703 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100704
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400707 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400708 if (stack_size > 1) {
709 int scope, force_global = 0;
710 struct compiler_unit *parent;
711 PyObject *mangled, *capsule;
712
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400713 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400714 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400715 assert(parent);
716
Yury Selivanov75445082015-05-11 22:57:16 -0400717 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
718 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
719 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 assert(u->u_name);
721 mangled = _Py_Mangle(parent->u_private, u->u_name);
722 if (!mangled)
723 return 0;
724 scope = PyST_GetScope(parent->u_ste, mangled);
725 Py_DECREF(mangled);
726 assert(scope != GLOBAL_IMPLICIT);
727 if (scope == GLOBAL_EXPLICIT)
728 force_global = 1;
729 }
730
731 if (!force_global) {
732 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400733 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400734 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
735 dot_locals_str = _PyUnicode_FromId(&dot_locals);
736 if (dot_locals_str == NULL)
737 return 0;
738 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
739 if (base == NULL)
740 return 0;
741 }
742 else {
743 Py_INCREF(parent->u_qualname);
744 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400745 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100746 }
747 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400748
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400749 if (base != NULL) {
750 dot_str = _PyUnicode_FromId(&dot);
751 if (dot_str == NULL) {
752 Py_DECREF(base);
753 return 0;
754 }
755 name = PyUnicode_Concat(base, dot_str);
756 Py_DECREF(base);
757 if (name == NULL)
758 return 0;
759 PyUnicode_Append(&name, u->u_name);
760 if (name == NULL)
761 return 0;
762 }
763 else {
764 Py_INCREF(u->u_name);
765 name = u->u_name;
766 }
767 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100768
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400769 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100770}
771
Eric V. Smith235a6f02015-09-19 14:51:32 -0400772
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773/* Allocate a new block and return a pointer to it.
774 Returns NULL on error.
775*/
776
777static basicblock *
778compiler_new_block(struct compiler *c)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 basicblock *b;
781 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500784 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (b == NULL) {
786 PyErr_NoMemory();
787 return NULL;
788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 /* Extend the singly linked list of blocks with new block. */
790 b->b_list = u->u_blocks;
791 u->u_blocks = b;
792 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796compiler_next_block(struct compiler *c)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 basicblock *block = compiler_new_block(c);
799 if (block == NULL)
800 return NULL;
801 c->u->u_curblock->b_next = block;
802 c->u->u_curblock = block;
803 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000804}
805
806static basicblock *
807compiler_use_next_block(struct compiler *c, basicblock *block)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(block != NULL);
810 c->u->u_curblock->b_next = block;
811 c->u->u_curblock = block;
812 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813}
814
Mark Shannon5977a792020-12-02 13:31:40 +0000815static basicblock *
816compiler_copy_block(struct compiler *c, basicblock *block)
817{
818 /* Cannot copy a block if it has a fallthrough, since
819 * a block can only have one fallthrough predecessor.
820 */
821 assert(block->b_nofallthrough);
822 basicblock *result = compiler_next_block(c);
823 if (result == NULL) {
824 return NULL;
825 }
826 for (int i = 0; i < block->b_iused; i++) {
827 int n = compiler_next_instr(result);
828 if (n < 0) {
829 return NULL;
830 }
831 result->b_instr[n] = block->b_instr[i];
832 }
833 result->b_exit = block->b_exit;
834 return result;
835}
836
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000837/* Returns the offset of the next instruction in the current block's
838 b_instr array. Resizes the b_instr as necessary.
839 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000840*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000841
842static int
Andy Lester76d58772020-03-10 21:18:12 -0500843compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 assert(b != NULL);
846 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500847 b->b_instr = (struct instr *)PyObject_Calloc(
848 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (b->b_instr == NULL) {
850 PyErr_NoMemory();
851 return -1;
852 }
853 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 }
855 else if (b->b_iused == b->b_ialloc) {
856 struct instr *tmp;
857 size_t oldsize, newsize;
858 oldsize = b->b_ialloc * sizeof(struct instr);
859 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000860
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700861 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyErr_NoMemory();
863 return -1;
864 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (newsize == 0) {
867 PyErr_NoMemory();
868 return -1;
869 }
870 b->b_ialloc <<= 1;
871 tmp = (struct instr *)PyObject_Realloc(
872 (void *)b->b_instr, newsize);
873 if (tmp == NULL) {
874 PyErr_NoMemory();
875 return -1;
876 }
877 b->b_instr = tmp;
878 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
879 }
880 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000881}
882
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200883/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000884
Christian Heimes2202f872008-02-06 14:31:34 +0000885 The line number is reset in the following cases:
886 - when entering a new scope
887 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200888 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200889 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000891
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200892#define SET_LOC(c, x) \
893 (c)->u->u_lineno = (x)->lineno; \
894 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000895
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200896/* Return the stack effect of opcode with argument oparg.
897
898 Some opcodes have different stack effect when jump to the target and
899 when not jump. The 'jump' parameter specifies the case:
900
901 * 0 -- when not jump
902 * 1 -- when jump
903 * -1 -- maximal
904 */
905/* XXX Make the stack effect of WITH_CLEANUP_START and
906 WITH_CLEANUP_FINISH deterministic. */
907static int
908stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300911 case NOP:
912 case EXTENDED_ARG:
913 return 0;
914
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200915 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 case POP_TOP:
917 return -1;
918 case ROT_TWO:
919 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200920 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 return 0;
922 case DUP_TOP:
923 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000924 case DUP_TOP_TWO:
925 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000926
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200927 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case UNARY_POSITIVE:
929 case UNARY_NEGATIVE:
930 case UNARY_NOT:
931 case UNARY_INVERT:
932 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 case SET_ADD:
935 case LIST_APPEND:
936 return -1;
937 case MAP_ADD:
938 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000939
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200940 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case BINARY_POWER:
942 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400943 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 case BINARY_MODULO:
945 case BINARY_ADD:
946 case BINARY_SUBTRACT:
947 case BINARY_SUBSCR:
948 case BINARY_FLOOR_DIVIDE:
949 case BINARY_TRUE_DIVIDE:
950 return -1;
951 case INPLACE_FLOOR_DIVIDE:
952 case INPLACE_TRUE_DIVIDE:
953 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 case INPLACE_ADD:
956 case INPLACE_SUBTRACT:
957 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400958 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 case INPLACE_MODULO:
960 return -1;
961 case STORE_SUBSCR:
962 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 case DELETE_SUBSCR:
964 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case BINARY_LSHIFT:
967 case BINARY_RSHIFT:
968 case BINARY_AND:
969 case BINARY_XOR:
970 case BINARY_OR:
971 return -1;
972 case INPLACE_POWER:
973 return -1;
974 case GET_ITER:
975 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case PRINT_EXPR:
978 return -1;
979 case LOAD_BUILD_CLASS:
980 return 1;
981 case INPLACE_LSHIFT:
982 case INPLACE_RSHIFT:
983 case INPLACE_AND:
984 case INPLACE_XOR:
985 case INPLACE_OR:
986 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200989 /* 1 in the normal flow.
990 * Restore the stack position and push 6 values before jumping to
991 * the handler if an exception be raised. */
992 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case RETURN_VALUE:
994 return -1;
995 case IMPORT_STAR:
996 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700997 case SETUP_ANNOTATIONS:
998 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 case YIELD_VALUE:
1000 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -05001001 case YIELD_FROM:
1002 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 case POP_BLOCK:
1004 return 0;
1005 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001006 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 case STORE_NAME:
1009 return -1;
1010 case DELETE_NAME:
1011 return 0;
1012 case UNPACK_SEQUENCE:
1013 return oparg-1;
1014 case UNPACK_EX:
1015 return (oparg&0xFF) + (oparg>>8);
1016 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001017 /* -1 at end of iterator, 1 if continue iterating. */
1018 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 case STORE_ATTR:
1021 return -2;
1022 case DELETE_ATTR:
1023 return -1;
1024 case STORE_GLOBAL:
1025 return -1;
1026 case DELETE_GLOBAL:
1027 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 case LOAD_CONST:
1029 return 1;
1030 case LOAD_NAME:
1031 return 1;
1032 case BUILD_TUPLE:
1033 case BUILD_LIST:
1034 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001035 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 return 1-oparg;
1037 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001038 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001039 case BUILD_CONST_KEY_MAP:
1040 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case LOAD_ATTR:
1042 return 0;
1043 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001044 case IS_OP:
1045 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001047 case JUMP_IF_NOT_EXC_MATCH:
1048 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case IMPORT_NAME:
1050 return -1;
1051 case IMPORT_FROM:
1052 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001053
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001054 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 case JUMP_ABSOLUTE:
1057 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001058
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001059 case JUMP_IF_TRUE_OR_POP:
1060 case JUMP_IF_FALSE_OR_POP:
1061 return jump ? 0 : -1;
1062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 case POP_JUMP_IF_FALSE:
1064 case POP_JUMP_IF_TRUE:
1065 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case LOAD_GLOBAL:
1068 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001070 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001072 /* 0 in the normal flow.
1073 * Restore the stack position and push 6 values before jumping to
1074 * the handler if an exception be raised. */
1075 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001076 case RERAISE:
1077 return -3;
1078
1079 case WITH_EXCEPT_START:
1080 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 case LOAD_FAST:
1083 return 1;
1084 case STORE_FAST:
1085 return -1;
1086 case DELETE_FAST:
1087 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 case RAISE_VARARGS:
1090 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001091
1092 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001094 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001095 case CALL_METHOD:
1096 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001098 return -oparg-1;
1099 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001100 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001101 case MAKE_FUNCTION:
1102 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1103 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 case BUILD_SLICE:
1105 if (oparg == 3)
1106 return -2;
1107 else
1108 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001109
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001110 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 case LOAD_CLOSURE:
1112 return 1;
1113 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001114 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 return 1;
1116 case STORE_DEREF:
1117 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001118 case DELETE_DEREF:
1119 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001120
1121 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001122 case GET_AWAITABLE:
1123 return 0;
1124 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001125 /* 0 in the normal flow.
1126 * Restore the stack position to the position before the result
1127 * of __aenter__ and push 6 values before jumping to the handler
1128 * if an exception be raised. */
1129 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001130 case BEFORE_ASYNC_WITH:
1131 return 1;
1132 case GET_AITER:
1133 return 0;
1134 case GET_ANEXT:
1135 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001136 case GET_YIELD_FROM_ITER:
1137 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001138 case END_ASYNC_FOR:
1139 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001140 case FORMAT_VALUE:
1141 /* If there's a fmt_spec on the stack, we go from 2->1,
1142 else 1->1. */
1143 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001144 case LOAD_METHOD:
1145 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001146 case LOAD_ASSERTION_ERROR:
1147 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001148 case LIST_TO_TUPLE:
1149 return 0;
1150 case LIST_EXTEND:
1151 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001152 case DICT_MERGE:
1153 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001154 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001156 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 }
Larry Hastings3a907972013-11-23 14:49:22 -08001158 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001159}
1160
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001161int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001162PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1163{
1164 return stack_effect(opcode, oparg, jump);
1165}
1166
1167int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001168PyCompile_OpcodeStackEffect(int opcode, int oparg)
1169{
1170 return stack_effect(opcode, oparg, -1);
1171}
1172
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001173/* Add an opcode with no argument.
1174 Returns 0 on failure, 1 on success.
1175*/
1176
1177static int
1178compiler_addop(struct compiler *c, int opcode)
1179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 basicblock *b;
1181 struct instr *i;
1182 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001183 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001184 if (c->c_do_not_emit_bytecode) {
1185 return 1;
1186 }
Andy Lester76d58772020-03-10 21:18:12 -05001187 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (off < 0)
1189 return 0;
1190 b = c->u->u_curblock;
1191 i = &b->b_instr[off];
1192 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001193 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (opcode == RETURN_VALUE)
1195 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001196 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001198}
1199
Victor Stinnerf8e32212013-11-19 23:56:34 +01001200static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001201compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001202{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001203 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001205
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001206 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001208 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001210 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001211 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001212 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return -1;
1215 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001216 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 Py_DECREF(v);
1218 return -1;
1219 }
1220 Py_DECREF(v);
1221 }
1222 else
1223 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001224 return arg;
1225}
1226
INADA Naokic2e16072018-11-26 21:23:22 +09001227// Merge const *o* recursively and return constant key object.
1228static PyObject*
1229merge_consts_recursive(struct compiler *c, PyObject *o)
1230{
1231 // None and Ellipsis are singleton, and key is the singleton.
1232 // No need to merge object and key.
1233 if (o == Py_None || o == Py_Ellipsis) {
1234 Py_INCREF(o);
1235 return o;
1236 }
1237
1238 PyObject *key = _PyCode_ConstantKey(o);
1239 if (key == NULL) {
1240 return NULL;
1241 }
1242
1243 // t is borrowed reference
1244 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1245 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001246 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001247 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001248 Py_DECREF(key);
1249 return t;
1250 }
1251
INADA Naokif7e4d362018-11-29 00:58:46 +09001252 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001253 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001254 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001255 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001256 Py_ssize_t len = PyTuple_GET_SIZE(o);
1257 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001258 PyObject *item = PyTuple_GET_ITEM(o, i);
1259 PyObject *u = merge_consts_recursive(c, item);
1260 if (u == NULL) {
1261 Py_DECREF(key);
1262 return NULL;
1263 }
1264
1265 // See _PyCode_ConstantKey()
1266 PyObject *v; // borrowed
1267 if (PyTuple_CheckExact(u)) {
1268 v = PyTuple_GET_ITEM(u, 1);
1269 }
1270 else {
1271 v = u;
1272 }
1273 if (v != item) {
1274 Py_INCREF(v);
1275 PyTuple_SET_ITEM(o, i, v);
1276 Py_DECREF(item);
1277 }
1278
1279 Py_DECREF(u);
1280 }
1281 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001282 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001283 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001284 // constant keys.
1285 // See _PyCode_ConstantKey() for detail.
1286 assert(PyTuple_CheckExact(key));
1287 assert(PyTuple_GET_SIZE(key) == 2);
1288
1289 Py_ssize_t len = PySet_GET_SIZE(o);
1290 if (len == 0) { // empty frozenset should not be re-created.
1291 return key;
1292 }
1293 PyObject *tuple = PyTuple_New(len);
1294 if (tuple == NULL) {
1295 Py_DECREF(key);
1296 return NULL;
1297 }
1298 Py_ssize_t i = 0, pos = 0;
1299 PyObject *item;
1300 Py_hash_t hash;
1301 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1302 PyObject *k = merge_consts_recursive(c, item);
1303 if (k == NULL) {
1304 Py_DECREF(tuple);
1305 Py_DECREF(key);
1306 return NULL;
1307 }
1308 PyObject *u;
1309 if (PyTuple_CheckExact(k)) {
1310 u = PyTuple_GET_ITEM(k, 1);
1311 Py_INCREF(u);
1312 Py_DECREF(k);
1313 }
1314 else {
1315 u = k;
1316 }
1317 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1318 i++;
1319 }
1320
1321 // Instead of rewriting o, we create new frozenset and embed in the
1322 // key tuple. Caller should get merged frozenset from the key tuple.
1323 PyObject *new = PyFrozenSet_New(tuple);
1324 Py_DECREF(tuple);
1325 if (new == NULL) {
1326 Py_DECREF(key);
1327 return NULL;
1328 }
1329 assert(PyTuple_GET_ITEM(key, 1) == o);
1330 Py_DECREF(o);
1331 PyTuple_SET_ITEM(key, 1, new);
1332 }
INADA Naokic2e16072018-11-26 21:23:22 +09001333
1334 return key;
1335}
1336
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001337static Py_ssize_t
1338compiler_add_const(struct compiler *c, PyObject *o)
1339{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001340 if (c->c_do_not_emit_bytecode) {
1341 return 0;
1342 }
1343
INADA Naokic2e16072018-11-26 21:23:22 +09001344 PyObject *key = merge_consts_recursive(c, o);
1345 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001346 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001347 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001348
Andy Lester76d58772020-03-10 21:18:12 -05001349 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001350 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001352}
1353
1354static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001355compiler_addop_load_const(struct compiler *c, PyObject *o)
1356{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001357 if (c->c_do_not_emit_bytecode) {
1358 return 1;
1359 }
1360
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001361 Py_ssize_t arg = compiler_add_const(c, o);
1362 if (arg < 0)
1363 return 0;
1364 return compiler_addop_i(c, LOAD_CONST, arg);
1365}
1366
1367static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001368compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001371 if (c->c_do_not_emit_bytecode) {
1372 return 1;
1373 }
1374
Andy Lester76d58772020-03-10 21:18:12 -05001375 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001377 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001378 return compiler_addop_i(c, opcode, arg);
1379}
1380
1381static int
1382compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001384{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001385 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001386
1387 if (c->c_do_not_emit_bytecode) {
1388 return 1;
1389 }
1390
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001391 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1392 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001393 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001394 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001395 Py_DECREF(mangled);
1396 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001397 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001398 return compiler_addop_i(c, opcode, arg);
1399}
1400
1401/* Add an opcode with an integer argument.
1402 Returns 0 on failure, 1 on success.
1403*/
1404
1405static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001406compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 struct instr *i;
1409 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001410
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001411 if (c->c_do_not_emit_bytecode) {
1412 return 1;
1413 }
1414
Victor Stinner2ad474b2016-03-01 23:34:47 +01001415 /* oparg value is unsigned, but a signed C int is usually used to store
1416 it in the C code (like Python/ceval.c).
1417
1418 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1419
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001420 The argument of a concrete bytecode instruction is limited to 8-bit.
1421 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1422 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001423 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001424
Andy Lester76d58772020-03-10 21:18:12 -05001425 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (off < 0)
1427 return 0;
1428 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001429 i->i_opcode = opcode;
1430 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001431 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433}
1434
1435static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001436compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 struct instr *i;
1439 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001441 if (c->c_do_not_emit_bytecode) {
1442 return 1;
1443 }
1444
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001445 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001447 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (off < 0)
1449 return 0;
1450 i = &c->u->u_curblock->b_instr[off];
1451 i->i_opcode = opcode;
1452 i->i_target = b;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001453 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001455}
1456
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001457/* NEXT_BLOCK() creates an implicit jump from the current block
1458 to the new block.
1459
1460 The returns inside this macro make it impossible to decref objects
1461 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001462*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 if (compiler_next_block((C)) == NULL) \
1465 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001466}
1467
1468#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (!compiler_addop((C), (OP))) \
1470 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001471}
1472
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001473#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (!compiler_addop((C), (OP))) { \
1475 compiler_exit_scope(c); \
1476 return 0; \
1477 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001478}
1479
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001480#define ADDOP_LOAD_CONST(C, O) { \
1481 if (!compiler_addop_load_const((C), (O))) \
1482 return 0; \
1483}
1484
1485/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1486#define ADDOP_LOAD_CONST_NEW(C, O) { \
1487 PyObject *__new_const = (O); \
1488 if (__new_const == NULL) { \
1489 return 0; \
1490 } \
1491 if (!compiler_addop_load_const((C), __new_const)) { \
1492 Py_DECREF(__new_const); \
1493 return 0; \
1494 } \
1495 Py_DECREF(__new_const); \
1496}
1497
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1500 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001501}
1502
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001503/* Same as ADDOP_O, but steals a reference. */
1504#define ADDOP_N(C, OP, O, TYPE) { \
1505 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1506 Py_DECREF((O)); \
1507 return 0; \
1508 } \
1509 Py_DECREF((O)); \
1510}
1511
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1514 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515}
1516
1517#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (!compiler_addop_i((C), (OP), (O))) \
1519 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001520}
1521
Mark Shannon582aaf12020-08-04 17:30:11 +01001522#define ADDOP_JUMP(C, OP, O) { \
1523 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525}
1526
Mark Shannon9af0e472020-01-14 10:12:45 +00001527#define ADDOP_COMPARE(C, CMP) { \
1528 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1529 return 0; \
1530}
1531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001532/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1533 the ASDL name to synthesize the name of the C type and the visit function.
1534*/
1535
1536#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (!compiler_visit_ ## TYPE((C), (V))) \
1538 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539}
1540
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001541#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 if (!compiler_visit_ ## TYPE((C), (V))) { \
1543 compiler_exit_scope(c); \
1544 return 0; \
1545 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001546}
1547
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001548#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (!compiler_visit_slice((C), (V), (CTX))) \
1550 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001551}
1552
1553#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001555 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1557 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1558 if (!compiler_visit_ ## TYPE((C), elt)) \
1559 return 0; \
1560 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561}
1562
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001563#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001565 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1567 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1568 if (!compiler_visit_ ## TYPE((C), elt)) { \
1569 compiler_exit_scope(c); \
1570 return 0; \
1571 } \
1572 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001573}
1574
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001575/* These macros allows to check only for errors and not emmit bytecode
1576 * while visiting nodes.
1577*/
1578
1579#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1580 c->c_do_not_emit_bytecode++;
1581
1582#define END_DO_NOT_EMIT_BYTECODE \
1583 c->c_do_not_emit_bytecode--; \
1584}
1585
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001586/* Search if variable annotations are present statically in a block. */
1587
1588static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001589find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001590{
1591 int i, j, res = 0;
1592 stmt_ty st;
1593
1594 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1595 st = (stmt_ty)asdl_seq_GET(stmts, i);
1596 switch (st->kind) {
1597 case AnnAssign_kind:
1598 return 1;
1599 case For_kind:
1600 res = find_ann(st->v.For.body) ||
1601 find_ann(st->v.For.orelse);
1602 break;
1603 case AsyncFor_kind:
1604 res = find_ann(st->v.AsyncFor.body) ||
1605 find_ann(st->v.AsyncFor.orelse);
1606 break;
1607 case While_kind:
1608 res = find_ann(st->v.While.body) ||
1609 find_ann(st->v.While.orelse);
1610 break;
1611 case If_kind:
1612 res = find_ann(st->v.If.body) ||
1613 find_ann(st->v.If.orelse);
1614 break;
1615 case With_kind:
1616 res = find_ann(st->v.With.body);
1617 break;
1618 case AsyncWith_kind:
1619 res = find_ann(st->v.AsyncWith.body);
1620 break;
1621 case Try_kind:
1622 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1623 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1624 st->v.Try.handlers, j);
1625 if (find_ann(handler->v.ExceptHandler.body)) {
1626 return 1;
1627 }
1628 }
1629 res = find_ann(st->v.Try.body) ||
1630 find_ann(st->v.Try.finalbody) ||
1631 find_ann(st->v.Try.orelse);
1632 break;
1633 default:
1634 res = 0;
1635 }
1636 if (res) {
1637 break;
1638 }
1639 }
1640 return res;
1641}
1642
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001643/*
1644 * Frame block handling functions
1645 */
1646
1647static int
1648compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001649 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001650{
1651 struct fblockinfo *f;
1652 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001653 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001654 }
1655 f = &c->u->u_fblock[c->u->u_nfblocks++];
1656 f->fb_type = t;
1657 f->fb_block = b;
1658 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001659 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001660 return 1;
1661}
1662
1663static void
1664compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1665{
1666 struct compiler_unit *u = c->u;
1667 assert(u->u_nfblocks > 0);
1668 u->u_nfblocks--;
1669 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1670 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1671}
1672
Mark Shannonfee55262019-11-21 09:11:43 +00001673static int
1674compiler_call_exit_with_nones(struct compiler *c) {
1675 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1676 ADDOP(c, DUP_TOP);
1677 ADDOP(c, DUP_TOP);
1678 ADDOP_I(c, CALL_FUNCTION, 3);
1679 return 1;
1680}
1681
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001682/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001683 * popping the blocks will be restored afterwards, unless another
1684 * return, break or continue is found. In which case, the TOS will
1685 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001686 */
1687static int
1688compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1689 int preserve_tos)
1690{
1691 switch (info->fb_type) {
1692 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001693 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001694 return 1;
1695
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001696 case FOR_LOOP:
1697 /* Pop the iterator */
1698 if (preserve_tos) {
1699 ADDOP(c, ROT_TWO);
1700 }
1701 ADDOP(c, POP_TOP);
1702 return 1;
1703
Mark Shannon02d126a2020-09-25 14:04:19 +01001704 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001705 ADDOP(c, POP_BLOCK);
1706 return 1;
1707
1708 case FINALLY_TRY:
1709 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001710 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001711 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1712 return 0;
1713 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001714 }
Mark Shannon88dce262019-12-30 09:53:36 +00001715 /* Emit the finally block, restoring the line number when done */
1716 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001717 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001718 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001719 if (preserve_tos) {
1720 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001721 }
1722 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001723
Mark Shannonfee55262019-11-21 09:11:43 +00001724 case FINALLY_END:
1725 if (preserve_tos) {
1726 ADDOP(c, ROT_FOUR);
1727 }
1728 ADDOP(c, POP_TOP);
1729 ADDOP(c, POP_TOP);
1730 ADDOP(c, POP_TOP);
1731 if (preserve_tos) {
1732 ADDOP(c, ROT_FOUR);
1733 }
1734 ADDOP(c, POP_EXCEPT);
1735 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001736
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001737 case WITH:
1738 case ASYNC_WITH:
1739 ADDOP(c, POP_BLOCK);
1740 if (preserve_tos) {
1741 ADDOP(c, ROT_TWO);
1742 }
Mark Shannonfee55262019-11-21 09:11:43 +00001743 if(!compiler_call_exit_with_nones(c)) {
1744 return 0;
1745 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001746 if (info->fb_type == ASYNC_WITH) {
1747 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001748 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001749 ADDOP(c, YIELD_FROM);
1750 }
Mark Shannonfee55262019-11-21 09:11:43 +00001751 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001752 return 1;
1753
1754 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001755 if (info->fb_datum) {
1756 ADDOP(c, POP_BLOCK);
1757 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001758 if (preserve_tos) {
1759 ADDOP(c, ROT_FOUR);
1760 }
Mark Shannonfee55262019-11-21 09:11:43 +00001761 ADDOP(c, POP_EXCEPT);
1762 if (info->fb_datum) {
1763 ADDOP_LOAD_CONST(c, Py_None);
1764 compiler_nameop(c, info->fb_datum, Store);
1765 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001766 }
Mark Shannonfee55262019-11-21 09:11:43 +00001767 return 1;
1768
1769 case POP_VALUE:
1770 if (preserve_tos) {
1771 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001772 }
Mark Shannonfee55262019-11-21 09:11:43 +00001773 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001774 return 1;
1775 }
1776 Py_UNREACHABLE();
1777}
1778
Mark Shannonfee55262019-11-21 09:11:43 +00001779/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1780static int
1781compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1782 if (c->u->u_nfblocks == 0) {
1783 return 1;
1784 }
1785 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1786 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1787 *loop = top;
1788 return 1;
1789 }
1790 struct fblockinfo copy = *top;
1791 c->u->u_nfblocks--;
1792 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1793 return 0;
1794 }
1795 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1796 return 0;
1797 }
1798 c->u->u_fblock[c->u->u_nfblocks] = copy;
1799 c->u->u_nfblocks++;
1800 return 1;
1801}
1802
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001803/* Compile a sequence of statements, checking for a docstring
1804 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001805
1806static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001807compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001809 int i = 0;
1810 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001811 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001812
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001813 /* Set current line number to the line number of first statement.
1814 This way line number for SETUP_ANNOTATIONS will always
1815 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301816 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001817 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001818 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001819 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001820 }
1821 /* Every annotated class and module should have __annotations__. */
1822 if (find_ann(stmts)) {
1823 ADDOP(c, SETUP_ANNOTATIONS);
1824 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001825 if (!asdl_seq_LEN(stmts))
1826 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001827 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001828 if (c->c_optimize < 2) {
1829 docstring = _PyAST_GetDocString(stmts);
1830 if (docstring) {
1831 i = 1;
1832 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1833 assert(st->kind == Expr_kind);
1834 VISIT(c, expr, st->v.Expr.value);
1835 if (!compiler_nameop(c, __doc__, Store))
1836 return 0;
1837 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001839 for (; i < asdl_seq_LEN(stmts); i++)
1840 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842}
1843
1844static PyCodeObject *
1845compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 PyCodeObject *co;
1848 int addNone = 1;
1849 static PyObject *module;
1850 if (!module) {
1851 module = PyUnicode_InternFromString("<module>");
1852 if (!module)
1853 return NULL;
1854 }
1855 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001856 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 return NULL;
1858 switch (mod->kind) {
1859 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001860 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 compiler_exit_scope(c);
1862 return 0;
1863 }
1864 break;
1865 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001866 if (find_ann(mod->v.Interactive.body)) {
1867 ADDOP(c, SETUP_ANNOTATIONS);
1868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001870 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 break;
1872 case Expression_kind:
1873 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1874 addNone = 0;
1875 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 default:
1877 PyErr_Format(PyExc_SystemError,
1878 "module kind %d should not be possible",
1879 mod->kind);
1880 return 0;
1881 }
1882 co = assemble(c, addNone);
1883 compiler_exit_scope(c);
1884 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001885}
1886
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887/* The test for LOCAL must come before the test for FREE in order to
1888 handle classes where name is both local and free. The local var is
1889 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001890*/
1891
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001892static int
1893get_ref_type(struct compiler *c, PyObject *name)
1894{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001895 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001896 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001897 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001898 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001899 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001901 _Py_FatalErrorFormat(__func__,
1902 "unknown scope for %.100s in %.100s(%s)\n"
1903 "symbols: %s\nlocals: %s\nglobals: %s",
1904 PyUnicode_AsUTF8(name),
1905 PyUnicode_AsUTF8(c->u->u_name),
1906 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1907 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1908 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1909 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913}
1914
1915static int
1916compiler_lookup_arg(PyObject *dict, PyObject *name)
1917{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001918 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001919 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001921 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001922 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001923}
1924
1925static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001926compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001928 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001929 if (qualname == NULL)
1930 qualname = co->co_name;
1931
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001932 if (free) {
1933 for (i = 0; i < free; ++i) {
1934 /* Bypass com_addop_varname because it will generate
1935 LOAD_DEREF but LOAD_CLOSURE is needed.
1936 */
1937 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1938 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001939
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001940 /* Special case: If a class contains a method with a
1941 free variable that has the same name as a method,
1942 the name will be considered free *and* local in the
1943 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001944 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001945 */
1946 reftype = get_ref_type(c, name);
1947 if (reftype == CELL)
1948 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1949 else /* (reftype == FREE) */
1950 arg = compiler_lookup_arg(c->u->u_freevars, name);
1951 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001952 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001953 "lookup %s in %s %d %d\n"
1954 "freevars of %s: %s\n",
1955 PyUnicode_AsUTF8(PyObject_Repr(name)),
1956 PyUnicode_AsUTF8(c->u->u_name),
1957 reftype, arg,
1958 PyUnicode_AsUTF8(co->co_name),
1959 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001960 }
1961 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001963 flags |= 0x08;
1964 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001966 ADDOP_LOAD_CONST(c, (PyObject*)co);
1967 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001968 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001970}
1971
1972static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001973compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (!decos)
1978 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1981 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1982 }
1983 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001984}
1985
1986static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001987compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1988 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001989{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001990 /* Push a dict of keyword-only default values.
1991
1992 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1993 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001994 int i;
1995 PyObject *keys = NULL;
1996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1998 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1999 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
2000 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04002001 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002002 if (!mangled) {
2003 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002005 if (keys == NULL) {
2006 keys = PyList_New(1);
2007 if (keys == NULL) {
2008 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002009 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002010 }
2011 PyList_SET_ITEM(keys, 0, mangled);
2012 }
2013 else {
2014 int res = PyList_Append(keys, mangled);
2015 Py_DECREF(mangled);
2016 if (res == -1) {
2017 goto error;
2018 }
2019 }
2020 if (!compiler_visit_expr(c, default_)) {
2021 goto error;
2022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 }
2024 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002025 if (keys != NULL) {
2026 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2027 PyObject *keys_tuple = PyList_AsTuple(keys);
2028 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002029 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002030 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002031 assert(default_count > 0);
2032 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002033 }
2034 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002035 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002036 }
2037
2038error:
2039 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002040 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002041}
2042
2043static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002044compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2045{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002046 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002047 return 1;
2048}
2049
2050static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002051compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002052 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002055 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002056 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002057 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002058
2059 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002060 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002061 VISIT(c, annexpr, annotation);
2062 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002064 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002065}
2066
2067static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002068compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002069 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002070{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002071 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 for (i = 0; i < asdl_seq_LEN(args); i++) {
2073 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002074 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 c,
2076 arg->arg,
2077 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002078 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002079 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002081 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002082}
2083
2084static int
2085compiler_visit_annotations(struct compiler *c, arguments_ty args,
2086 expr_ty returns)
2087{
Yurii Karabas73019792020-11-25 12:43:18 +02002088 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002089 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002090
Yurii Karabas73019792020-11-25 12:43:18 +02002091 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 */
2093 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002094 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002095
Yurii Karabas73019792020-11-25 12:43:18 +02002096 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2097 return 0;
2098 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2099 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002100 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002101 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002102 args->vararg->annotation, &annotations_len))
2103 return 0;
2104 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2105 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002106 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002107 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002108 args->kwarg->annotation, &annotations_len))
2109 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (!return_str) {
2112 return_str = PyUnicode_InternFromString("return");
2113 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002114 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 }
Yurii Karabas73019792020-11-25 12:43:18 +02002116 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2117 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 }
2119
Yurii Karabas73019792020-11-25 12:43:18 +02002120 if (annotations_len) {
2121 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002122 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002124
Yurii Karabas73019792020-11-25 12:43:18 +02002125 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002126}
2127
2128static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002129compiler_visit_defaults(struct compiler *c, arguments_ty args)
2130{
2131 VISIT_SEQ(c, expr, args->defaults);
2132 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2133 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134}
2135
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002136static Py_ssize_t
2137compiler_default_arguments(struct compiler *c, arguments_ty args)
2138{
2139 Py_ssize_t funcflags = 0;
2140 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002141 if (!compiler_visit_defaults(c, args))
2142 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002143 funcflags |= 0x01;
2144 }
2145 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002146 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002147 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002148 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002149 return -1;
2150 }
2151 else if (res > 0) {
2152 funcflags |= 0x02;
2153 }
2154 }
2155 return funcflags;
2156}
2157
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002158static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002159forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2160{
2161
2162 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2163 compiler_error(c, "cannot assign to __debug__");
2164 return 1;
2165 }
2166 return 0;
2167}
2168
2169static int
2170compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2171{
2172 if (arg != NULL) {
2173 if (forbidden_name(c, arg->arg, Store))
2174 return 0;
2175 }
2176 return 1;
2177}
2178
2179static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002180compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002181{
2182 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002183 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002184 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2185 return 0;
2186 }
2187 }
2188 return 1;
2189}
2190
2191static int
2192compiler_check_debug_args(struct compiler *c, arguments_ty args)
2193{
2194 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2195 return 0;
2196 if (!compiler_check_debug_args_seq(c, args->args))
2197 return 0;
2198 if (!compiler_check_debug_one_arg(c, args->vararg))
2199 return 0;
2200 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2201 return 0;
2202 if (!compiler_check_debug_one_arg(c, args->kwarg))
2203 return 0;
2204 return 1;
2205}
2206
2207static int
Yury Selivanov75445082015-05-11 22:57:16 -04002208compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002211 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002212 arguments_ty args;
2213 expr_ty returns;
2214 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002215 asdl_expr_seq* decos;
2216 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002217 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002218 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002219 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002220 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221
Yury Selivanov75445082015-05-11 22:57:16 -04002222 if (is_async) {
2223 assert(s->kind == AsyncFunctionDef_kind);
2224
2225 args = s->v.AsyncFunctionDef.args;
2226 returns = s->v.AsyncFunctionDef.returns;
2227 decos = s->v.AsyncFunctionDef.decorator_list;
2228 name = s->v.AsyncFunctionDef.name;
2229 body = s->v.AsyncFunctionDef.body;
2230
2231 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2232 } else {
2233 assert(s->kind == FunctionDef_kind);
2234
2235 args = s->v.FunctionDef.args;
2236 returns = s->v.FunctionDef.returns;
2237 decos = s->v.FunctionDef.decorator_list;
2238 name = s->v.FunctionDef.name;
2239 body = s->v.FunctionDef.body;
2240
2241 scope_type = COMPILER_SCOPE_FUNCTION;
2242 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002243
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002244 if (!compiler_check_debug_args(c, args))
2245 return 0;
2246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (!compiler_decorators(c, decos))
2248 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002249
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002250 firstlineno = s->lineno;
2251 if (asdl_seq_LEN(decos)) {
2252 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2253 }
2254
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002255 funcflags = compiler_default_arguments(c, args);
2256 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002258 }
2259
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002260 annotations = compiler_visit_annotations(c, args, returns);
2261 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002262 return 0;
2263 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002264 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002265 funcflags |= 0x04;
2266 }
2267
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002268 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002269 return 0;
2270 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271
INADA Naokicb41b272017-02-23 00:31:59 +09002272 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002273 if (c->c_optimize < 2) {
2274 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002275 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002276 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 compiler_exit_scope(c);
2278 return 0;
2279 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002282 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002284 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002285 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002288 qualname = c->u->u_qualname;
2289 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002291 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002292 Py_XDECREF(qualname);
2293 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002295 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002297 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002298 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 /* decorators */
2302 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2303 ADDOP_I(c, CALL_FUNCTION, 1);
2304 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002305
Yury Selivanov75445082015-05-11 22:57:16 -04002306 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307}
2308
2309static int
2310compiler_class(struct compiler *c, stmt_ty s)
2311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 PyCodeObject *co;
2313 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002314 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002315 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 if (!compiler_decorators(c, decos))
2318 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002319
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002320 firstlineno = s->lineno;
2321 if (asdl_seq_LEN(decos)) {
2322 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2323 }
2324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 /* ultimately generate code for:
2326 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2327 where:
2328 <func> is a function/closure created from the class body;
2329 it has a single argument (__locals__) where the dict
2330 (or MutableSequence) representing the locals is passed
2331 <name> is the class name
2332 <bases> is the positional arguments and *varargs argument
2333 <keywords> is the keyword arguments and **kwds argument
2334 This borrows from compiler_call.
2335 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002338 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002339 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 return 0;
2341 /* this block represents what we do in the new scope */
2342 {
2343 /* use the class name for name mangling */
2344 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002345 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 /* load (global) __name__ ... */
2347 str = PyUnicode_InternFromString("__name__");
2348 if (!str || !compiler_nameop(c, str, Load)) {
2349 Py_XDECREF(str);
2350 compiler_exit_scope(c);
2351 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002352 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 Py_DECREF(str);
2354 /* ... and store it as __module__ */
2355 str = PyUnicode_InternFromString("__module__");
2356 if (!str || !compiler_nameop(c, str, Store)) {
2357 Py_XDECREF(str);
2358 compiler_exit_scope(c);
2359 return 0;
2360 }
2361 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002362 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002363 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002364 str = PyUnicode_InternFromString("__qualname__");
2365 if (!str || !compiler_nameop(c, str, Store)) {
2366 Py_XDECREF(str);
2367 compiler_exit_scope(c);
2368 return 0;
2369 }
2370 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002372 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 compiler_exit_scope(c);
2374 return 0;
2375 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002376 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002377 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002378 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002379 str = PyUnicode_InternFromString("__class__");
2380 if (str == NULL) {
2381 compiler_exit_scope(c);
2382 return 0;
2383 }
2384 i = compiler_lookup_arg(c->u->u_cellvars, str);
2385 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002386 if (i < 0) {
2387 compiler_exit_scope(c);
2388 return 0;
2389 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002390 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002393 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002394 str = PyUnicode_InternFromString("__classcell__");
2395 if (!str || !compiler_nameop(c, str, Store)) {
2396 Py_XDECREF(str);
2397 compiler_exit_scope(c);
2398 return 0;
2399 }
2400 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002402 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002403 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002404 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002405 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002406 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002407 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 /* create the code object */
2409 co = assemble(c, 1);
2410 }
2411 /* leave the new scope */
2412 compiler_exit_scope(c);
2413 if (co == NULL)
2414 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 /* 2. load the 'build_class' function */
2417 ADDOP(c, LOAD_BUILD_CLASS);
2418
2419 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002420 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 Py_DECREF(co);
2422
2423 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002424 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425
2426 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002427 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 return 0;
2429
2430 /* 6. apply decorators */
2431 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2432 ADDOP_I(c, CALL_FUNCTION, 1);
2433 }
2434
2435 /* 7. store into <name> */
2436 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2437 return 0;
2438 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002439}
2440
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002441/* Return 0 if the expression is a constant value except named singletons.
2442 Return 1 otherwise. */
2443static int
2444check_is_arg(expr_ty e)
2445{
2446 if (e->kind != Constant_kind) {
2447 return 1;
2448 }
2449 PyObject *value = e->v.Constant.value;
2450 return (value == Py_None
2451 || value == Py_False
2452 || value == Py_True
2453 || value == Py_Ellipsis);
2454}
2455
2456/* Check operands of identity chacks ("is" and "is not").
2457 Emit a warning if any operand is a constant except named singletons.
2458 Return 0 on error.
2459 */
2460static int
2461check_compare(struct compiler *c, expr_ty e)
2462{
2463 Py_ssize_t i, n;
2464 int left = check_is_arg(e->v.Compare.left);
2465 n = asdl_seq_LEN(e->v.Compare.ops);
2466 for (i = 0; i < n; i++) {
2467 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2468 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2469 if (op == Is || op == IsNot) {
2470 if (!right || !left) {
2471 const char *msg = (op == Is)
2472 ? "\"is\" with a literal. Did you mean \"==\"?"
2473 : "\"is not\" with a literal. Did you mean \"!=\"?";
2474 return compiler_warn(c, msg);
2475 }
2476 }
2477 left = right;
2478 }
2479 return 1;
2480}
2481
Mark Shannon9af0e472020-01-14 10:12:45 +00002482static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483{
Mark Shannon9af0e472020-01-14 10:12:45 +00002484 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485 switch (op) {
2486 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002487 cmp = Py_EQ;
2488 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002489 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002490 cmp = Py_NE;
2491 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002492 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002493 cmp = Py_LT;
2494 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002495 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002496 cmp = Py_LE;
2497 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002498 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002499 cmp = Py_GT;
2500 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002501 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002502 cmp = Py_GE;
2503 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002504 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002505 ADDOP_I(c, IS_OP, 0);
2506 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002507 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002508 ADDOP_I(c, IS_OP, 1);
2509 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002510 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002511 ADDOP_I(c, CONTAINS_OP, 0);
2512 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002513 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002514 ADDOP_I(c, CONTAINS_OP, 1);
2515 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002516 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002517 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002518 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002519 ADDOP_I(c, COMPARE_OP, cmp);
2520 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002521}
2522
Mark Shannon9af0e472020-01-14 10:12:45 +00002523
2524
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002525static int
2526compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2527{
2528 switch (e->kind) {
2529 case UnaryOp_kind:
2530 if (e->v.UnaryOp.op == Not)
2531 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2532 /* fallback to general implementation */
2533 break;
2534 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002535 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002536 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2537 assert(n >= 0);
2538 int cond2 = e->v.BoolOp.op == Or;
2539 basicblock *next2 = next;
2540 if (!cond2 != !cond) {
2541 next2 = compiler_new_block(c);
2542 if (next2 == NULL)
2543 return 0;
2544 }
2545 for (i = 0; i < n; ++i) {
2546 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2547 return 0;
2548 }
2549 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2550 return 0;
2551 if (next2 != next)
2552 compiler_use_next_block(c, next2);
2553 return 1;
2554 }
2555 case IfExp_kind: {
2556 basicblock *end, *next2;
2557 end = compiler_new_block(c);
2558 if (end == NULL)
2559 return 0;
2560 next2 = compiler_new_block(c);
2561 if (next2 == NULL)
2562 return 0;
2563 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2564 return 0;
2565 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2566 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002567 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002568 compiler_use_next_block(c, next2);
2569 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2570 return 0;
2571 compiler_use_next_block(c, end);
2572 return 1;
2573 }
2574 case Compare_kind: {
2575 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2576 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002577 if (!check_compare(c, e)) {
2578 return 0;
2579 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002580 basicblock *cleanup = compiler_new_block(c);
2581 if (cleanup == NULL)
2582 return 0;
2583 VISIT(c, expr, e->v.Compare.left);
2584 for (i = 0; i < n; i++) {
2585 VISIT(c, expr,
2586 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2587 ADDOP(c, DUP_TOP);
2588 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002589 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002590 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002591 NEXT_BLOCK(c);
2592 }
2593 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002594 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002595 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002596 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002597 basicblock *end = compiler_new_block(c);
2598 if (end == NULL)
2599 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002600 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002601 compiler_use_next_block(c, cleanup);
2602 ADDOP(c, POP_TOP);
2603 if (!cond) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002604 ADDOP_JUMP(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002605 }
2606 compiler_use_next_block(c, end);
2607 return 1;
2608 }
2609 /* fallback to general implementation */
2610 break;
2611 }
2612 default:
2613 /* fallback to general implementation */
2614 break;
2615 }
2616
2617 /* general implementation */
2618 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002619 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002620 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002621 return 1;
2622}
2623
2624static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002625compiler_ifexp(struct compiler *c, expr_ty e)
2626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 basicblock *end, *next;
2628
2629 assert(e->kind == IfExp_kind);
2630 end = compiler_new_block(c);
2631 if (end == NULL)
2632 return 0;
2633 next = compiler_new_block(c);
2634 if (next == NULL)
2635 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002636 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2637 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002639 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 compiler_use_next_block(c, next);
2641 VISIT(c, expr, e->v.IfExp.orelse);
2642 compiler_use_next_block(c, end);
2643 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002644}
2645
2646static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647compiler_lambda(struct compiler *c, expr_ty e)
2648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002650 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002652 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 arguments_ty args = e->v.Lambda.args;
2654 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002655
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002656 if (!compiler_check_debug_args(c, args))
2657 return 0;
2658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 if (!name) {
2660 name = PyUnicode_InternFromString("<lambda>");
2661 if (!name)
2662 return 0;
2663 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002664
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002665 funcflags = compiler_default_arguments(c, args);
2666 if (funcflags == -1) {
2667 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002669
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002670 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002671 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 /* Make None the first constant, so the lambda can't have a
2675 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002676 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002680 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2682 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2683 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002684 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 }
2686 else {
2687 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002688 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002690 qualname = c->u->u_qualname;
2691 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002693 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002695
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002696 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002697 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 Py_DECREF(co);
2699
2700 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002701}
2702
2703static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002704compiler_if(struct compiler *c, stmt_ty s)
2705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 basicblock *end, *next;
2707 int constant;
2708 assert(s->kind == If_kind);
2709 end = compiler_new_block(c);
2710 if (end == NULL)
2711 return 0;
2712
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002713 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002714 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 * constant = 1: "if 1", "if 2", ...
2716 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002717 if (constant == 0) {
2718 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002720 END_DO_NOT_EMIT_BYTECODE
2721 if (s->v.If.orelse) {
2722 VISIT_SEQ(c, stmt, s->v.If.orelse);
2723 }
2724 } else if (constant == 1) {
2725 VISIT_SEQ(c, stmt, s->v.If.body);
2726 if (s->v.If.orelse) {
2727 BEGIN_DO_NOT_EMIT_BYTECODE
2728 VISIT_SEQ(c, stmt, s->v.If.orelse);
2729 END_DO_NOT_EMIT_BYTECODE
2730 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002732 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 next = compiler_new_block(c);
2734 if (next == NULL)
2735 return 0;
2736 }
Mark Shannonfee55262019-11-21 09:11:43 +00002737 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002739 }
2740 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002741 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002742 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002744 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002745 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 compiler_use_next_block(c, next);
2747 VISIT_SEQ(c, stmt, s->v.If.orelse);
2748 }
2749 }
2750 compiler_use_next_block(c, end);
2751 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002752}
2753
2754static int
2755compiler_for(struct compiler *c, stmt_ty s)
2756{
Mark Shannon5977a792020-12-02 13:31:40 +00002757 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002760 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 cleanup = compiler_new_block(c);
2762 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002763 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002765 }
2766 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002768 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 VISIT(c, expr, s->v.For.iter);
2770 ADDOP(c, GET_ITER);
2771 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002772 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002773 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 VISIT(c, expr, s->v.For.target);
2775 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002776 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002778
2779 compiler_pop_fblock(c, FOR_LOOP, start);
2780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 VISIT_SEQ(c, stmt, s->v.For.orelse);
2782 compiler_use_next_block(c, end);
2783 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784}
2785
Yury Selivanov75445082015-05-11 22:57:16 -04002786
2787static int
2788compiler_async_for(struct compiler *c, stmt_ty s)
2789{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002790 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002791 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002792 c->u->u_ste->ste_coroutine = 1;
2793 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002794 return compiler_error(c, "'async for' outside async function");
2795 }
2796
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002797 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002798 except = compiler_new_block(c);
2799 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002800
Mark Shannonfee55262019-11-21 09:11:43 +00002801 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002802 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002803 }
Yury Selivanov75445082015-05-11 22:57:16 -04002804 VISIT(c, expr, s->v.AsyncFor.iter);
2805 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002806
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002807 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002808 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002809 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002810 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002811 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002812 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002813 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002814 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002815 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002816 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002817
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002818 /* Success block for __anext__ */
2819 VISIT(c, expr, s->v.AsyncFor.target);
2820 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002821 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002822
2823 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002824
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002825 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002826 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002827
2828 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002829 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002830
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002831 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002832 VISIT_SEQ(c, stmt, s->v.For.orelse);
2833
2834 compiler_use_next_block(c, end);
2835
2836 return 1;
2837}
2838
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002839static int
2840compiler_while(struct compiler *c, stmt_ty s)
2841{
Mark Shannon266b4622020-11-17 19:30:14 +00002842 basicblock *loop, *body, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002843 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002846 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002847 // Push a dummy block so the VISIT_SEQ knows that we are
2848 // inside a while loop so it can correctly evaluate syntax
2849 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002850 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002851 return 0;
2852 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002853 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002854 // Remove the dummy block now that is not needed.
2855 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002856 END_DO_NOT_EMIT_BYTECODE
2857 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002859 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 return 1;
2861 }
2862 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002863 body = compiler_new_block(c);
2864 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002866 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002870 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 }
Mark Shannon266b4622020-11-17 19:30:14 +00002873 if (constant == -1) {
2874 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2875 return 0;
2876 }
2877 }
2878
2879 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002881 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002883 compiler_pop_fblock(c, WHILE_LOOP, loop);
2884
Mark Shannon266b4622020-11-17 19:30:14 +00002885 compiler_use_next_block(c, anchor);
2886 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002888 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002892}
2893
2894static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002895compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002896{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002897 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002898 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002899 if (c->u->u_ste->ste_type != FunctionBlock)
2900 return compiler_error(c, "'return' outside function");
2901 if (s->v.Return.value != NULL &&
2902 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2903 {
2904 return compiler_error(
2905 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002906 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002907 if (preserve_tos) {
2908 VISIT(c, expr, s->v.Return.value);
2909 }
Mark Shannonfee55262019-11-21 09:11:43 +00002910 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2911 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002912 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002913 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002914 }
2915 else if (!preserve_tos) {
2916 VISIT(c, expr, s->v.Return.value);
2917 }
2918 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002919 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922}
2923
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002924static int
2925compiler_break(struct compiler *c)
2926{
Mark Shannonfee55262019-11-21 09:11:43 +00002927 struct fblockinfo *loop = NULL;
2928 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2929 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002930 }
Mark Shannonfee55262019-11-21 09:11:43 +00002931 if (loop == NULL) {
2932 return compiler_error(c, "'break' outside loop");
2933 }
2934 if (!compiler_unwind_fblock(c, loop, 0)) {
2935 return 0;
2936 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002937 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002938 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002939 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002940}
2941
2942static int
2943compiler_continue(struct compiler *c)
2944{
Mark Shannonfee55262019-11-21 09:11:43 +00002945 struct fblockinfo *loop = NULL;
2946 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2947 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002948 }
Mark Shannonfee55262019-11-21 09:11:43 +00002949 if (loop == NULL) {
2950 return compiler_error(c, "'continue' not properly in loop");
2951 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002952 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002953 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002954 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002955}
2956
2957
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002958/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959
2960 SETUP_FINALLY L
2961 <code for body>
2962 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002963 <code for finalbody>
2964 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002965 L:
2966 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002967 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002969 The special instructions use the block stack. Each block
2970 stack entry contains the instruction that created it (here
2971 SETUP_FINALLY), the level of the value stack at the time the
2972 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002973
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002975 Pushes the current value stack level and the label
2976 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002978 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002980 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002981 when a SETUP_FINALLY entry is found, the raised and the caught
2982 exceptions are pushed onto the value stack (and the exception
2983 condition is cleared), and the interpreter jumps to the label
2984 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002985*/
2986
2987static int
2988compiler_try_finally(struct compiler *c, stmt_ty s)
2989{
Mark Shannonfee55262019-11-21 09:11:43 +00002990 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002992 body = compiler_new_block(c);
2993 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002994 exit = compiler_new_block(c);
2995 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002996 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002998 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002999 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00003001 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003002 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003003 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
3004 if (!compiler_try_except(c, s))
3005 return 0;
3006 }
3007 else {
3008 VISIT_SEQ(c, stmt, s->v.Try.body);
3009 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003010 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00003011 compiler_pop_fblock(c, FINALLY_TRY, body);
3012 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon582aaf12020-08-04 17:30:11 +01003013 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00003014 /* `finally` block */
3015 compiler_use_next_block(c, end);
3016 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
3017 return 0;
3018 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3019 compiler_pop_fblock(c, FINALLY_END, end);
3020 ADDOP(c, RERAISE);
3021 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003023}
3024
3025/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003026 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003027 (The contents of the value stack is shown in [], with the top
3028 at the right; 'tb' is trace-back info, 'val' the exception's
3029 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030
3031 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003032 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 [] <code for S>
3034 [] POP_BLOCK
3035 [] JUMP_FORWARD L0
3036
3037 [tb, val, exc] L1: DUP )
3038 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003039 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003040 [tb, val, exc] POP
3041 [tb, val] <assign to V1> (or POP if no V1)
3042 [tb] POP
3043 [] <code for S1>
3044 JUMP_FORWARD L0
3045
3046 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003047 .............................etc.......................
3048
Mark Shannonfee55262019-11-21 09:11:43 +00003049 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003050
3051 [] L0: <next statement>
3052
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003053 Of course, parts are not generated if Vi or Ei is not present.
3054*/
3055static int
3056compiler_try_except(struct compiler *c, stmt_ty s)
3057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003059 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 body = compiler_new_block(c);
3062 except = compiler_new_block(c);
3063 orelse = compiler_new_block(c);
3064 end = compiler_new_block(c);
3065 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3066 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003067 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003069 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003071 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 ADDOP(c, POP_BLOCK);
Mark Shannon02d126a2020-09-25 14:04:19 +01003073 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon582aaf12020-08-04 17:30:11 +01003074 ADDOP_JUMP(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003075 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003077 /* Runtime will push a block here, so we need to account for that */
3078 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3079 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 for (i = 0; i < n; i++) {
3081 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003082 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 if (!handler->v.ExceptHandler.type && i < n-1)
3084 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003085 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086 except = compiler_new_block(c);
3087 if (except == NULL)
3088 return 0;
3089 if (handler->v.ExceptHandler.type) {
3090 ADDOP(c, DUP_TOP);
3091 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003092 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003093 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 }
3095 ADDOP(c, POP_TOP);
3096 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003097 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003098
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003099 cleanup_end = compiler_new_block(c);
3100 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003101 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003102 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003103 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003104
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003105 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3106 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003107
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003108 /*
3109 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003110 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003111 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003112 try:
3113 # body
3114 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003115 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003116 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003117 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003118
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003120 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003121 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003122 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003123 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003124
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003125 /* second # body */
3126 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003127 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003128 ADDOP(c, POP_BLOCK);
3129 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003130 /* name = None; del name; # Mark as artificial */
3131 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003132 ADDOP_LOAD_CONST(c, Py_None);
3133 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3134 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003135 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136
Mark Shannonfee55262019-11-21 09:11:43 +00003137 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003138 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003139
Mark Shannon877df852020-11-12 09:43:29 +00003140 /* name = None; del name; # Mark as artificial */
3141 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003142 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003143 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003144 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145
Mark Shannonfee55262019-11-21 09:11:43 +00003146 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003147 }
3148 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003149 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003151 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003152 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003153 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154
Guido van Rossumb940e112007-01-10 16:19:56 +00003155 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003156 ADDOP(c, POP_TOP);
3157 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003158 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003159 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003161 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003162 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003163 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 compiler_use_next_block(c, except);
3166 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003167 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonfee55262019-11-21 09:11:43 +00003168 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003169 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003170 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003171 compiler_use_next_block(c, end);
3172 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003173}
3174
3175static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003176compiler_try(struct compiler *c, stmt_ty s) {
3177 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3178 return compiler_try_finally(c, s);
3179 else
3180 return compiler_try_except(c, s);
3181}
3182
3183
3184static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185compiler_import_as(struct compiler *c, identifier name, identifier asname)
3186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003187 /* The IMPORT_NAME opcode was already generated. This function
3188 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003191 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003193 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3194 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003195 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003196 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003197 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003198 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003199 while (1) {
3200 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003202 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003203 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003204 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003205 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003206 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003207 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003208 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003209 if (dot == -1) {
3210 break;
3211 }
3212 ADDOP(c, ROT_TWO);
3213 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003215 if (!compiler_nameop(c, asname, Store)) {
3216 return 0;
3217 }
3218 ADDOP(c, POP_TOP);
3219 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 }
3221 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222}
3223
3224static int
3225compiler_import(struct compiler *c, stmt_ty s)
3226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 /* The Import node stores a module name like a.b.c as a single
3228 string. This is convenient for all cases except
3229 import a.b.c as d
3230 where we need to parse that string to extract the individual
3231 module names.
3232 XXX Perhaps change the representation to make this case simpler?
3233 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003234 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003235
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003236 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003237 for (i = 0; i < n; i++) {
3238 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3239 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003241 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003242 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003245 if (alias->asname) {
3246 r = compiler_import_as(c, alias->name, alias->asname);
3247 if (!r)
3248 return r;
3249 }
3250 else {
3251 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003252 Py_ssize_t dot = PyUnicode_FindChar(
3253 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003254 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003255 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003256 if (tmp == NULL)
3257 return 0;
3258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003260 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 Py_DECREF(tmp);
3262 }
3263 if (!r)
3264 return r;
3265 }
3266 }
3267 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003268}
3269
3270static int
3271compiler_from_import(struct compiler *c, stmt_ty s)
3272{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003273 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003274 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003275 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003277 if (!empty_string) {
3278 empty_string = PyUnicode_FromString("");
3279 if (!empty_string)
3280 return 0;
3281 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003282
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003283 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003284
3285 names = PyTuple_New(n);
3286 if (!names)
3287 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 /* build up the names */
3290 for (i = 0; i < n; i++) {
3291 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3292 Py_INCREF(alias->name);
3293 PyTuple_SET_ITEM(names, i, alias->name);
3294 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003297 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 Py_DECREF(names);
3299 return compiler_error(c, "from __future__ imports must occur "
3300 "at the beginning of the file");
3301 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003302 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 if (s->v.ImportFrom.module) {
3305 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3306 }
3307 else {
3308 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3309 }
3310 for (i = 0; i < n; i++) {
3311 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3312 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003314 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003315 assert(n == 1);
3316 ADDOP(c, IMPORT_STAR);
3317 return 1;
3318 }
3319
3320 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3321 store_name = alias->name;
3322 if (alias->asname)
3323 store_name = alias->asname;
3324
3325 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 return 0;
3327 }
3328 }
3329 /* remove imported module */
3330 ADDOP(c, POP_TOP);
3331 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003332}
3333
3334static int
3335compiler_assert(struct compiler *c, stmt_ty s)
3336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003338
Georg Brandl8334fd92010-12-04 10:26:46 +00003339 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003340 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003341 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003342 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3343 {
3344 if (!compiler_warn(c, "assertion is always true, "
3345 "perhaps remove parentheses?"))
3346 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003347 return 0;
3348 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003349 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 end = compiler_new_block(c);
3351 if (end == NULL)
3352 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003353 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3354 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003355 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003356 if (s->v.Assert.msg) {
3357 VISIT(c, expr, s->v.Assert.msg);
3358 ADDOP_I(c, CALL_FUNCTION, 1);
3359 }
3360 ADDOP_I(c, RAISE_VARARGS, 1);
3361 compiler_use_next_block(c, end);
3362 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003363}
3364
3365static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003366compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3367{
3368 if (c->c_interactive && c->c_nestlevel <= 1) {
3369 VISIT(c, expr, value);
3370 ADDOP(c, PRINT_EXPR);
3371 return 1;
3372 }
3373
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003374 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003375 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003376 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003377 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003378 }
3379
3380 VISIT(c, expr, value);
3381 ADDOP(c, POP_TOP);
3382 return 1;
3383}
3384
3385static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003386compiler_visit_stmt(struct compiler *c, stmt_ty s)
3387{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003388 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003390 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003391 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003393 switch (s->kind) {
3394 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003395 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 case ClassDef_kind:
3397 return compiler_class(c, s);
3398 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003399 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003400 case Delete_kind:
3401 VISIT_SEQ(c, expr, s->v.Delete.targets)
3402 break;
3403 case Assign_kind:
3404 n = asdl_seq_LEN(s->v.Assign.targets);
3405 VISIT(c, expr, s->v.Assign.value);
3406 for (i = 0; i < n; i++) {
3407 if (i < n - 1)
3408 ADDOP(c, DUP_TOP);
3409 VISIT(c, expr,
3410 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3411 }
3412 break;
3413 case AugAssign_kind:
3414 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003415 case AnnAssign_kind:
3416 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003417 case For_kind:
3418 return compiler_for(c, s);
3419 case While_kind:
3420 return compiler_while(c, s);
3421 case If_kind:
3422 return compiler_if(c, s);
3423 case Raise_kind:
3424 n = 0;
3425 if (s->v.Raise.exc) {
3426 VISIT(c, expr, s->v.Raise.exc);
3427 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003428 if (s->v.Raise.cause) {
3429 VISIT(c, expr, s->v.Raise.cause);
3430 n++;
3431 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003432 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003433 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003434 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003435 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003436 case Try_kind:
3437 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003438 case Assert_kind:
3439 return compiler_assert(c, s);
3440 case Import_kind:
3441 return compiler_import(c, s);
3442 case ImportFrom_kind:
3443 return compiler_from_import(c, s);
3444 case Global_kind:
3445 case Nonlocal_kind:
3446 break;
3447 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003448 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003450 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003451 break;
3452 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003453 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 case Continue_kind:
3455 return compiler_continue(c);
3456 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003457 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003458 case AsyncFunctionDef_kind:
3459 return compiler_function(c, s, 1);
3460 case AsyncWith_kind:
3461 return compiler_async_with(c, s, 0);
3462 case AsyncFor_kind:
3463 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003464 }
Yury Selivanov75445082015-05-11 22:57:16 -04003465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003466 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003467}
3468
3469static int
3470unaryop(unaryop_ty op)
3471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003472 switch (op) {
3473 case Invert:
3474 return UNARY_INVERT;
3475 case Not:
3476 return UNARY_NOT;
3477 case UAdd:
3478 return UNARY_POSITIVE;
3479 case USub:
3480 return UNARY_NEGATIVE;
3481 default:
3482 PyErr_Format(PyExc_SystemError,
3483 "unary op %d should not be possible", op);
3484 return 0;
3485 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003486}
3487
3488static int
Andy Lester76d58772020-03-10 21:18:12 -05003489binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 switch (op) {
3492 case Add:
3493 return BINARY_ADD;
3494 case Sub:
3495 return BINARY_SUBTRACT;
3496 case Mult:
3497 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003498 case MatMult:
3499 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003500 case Div:
3501 return BINARY_TRUE_DIVIDE;
3502 case Mod:
3503 return BINARY_MODULO;
3504 case Pow:
3505 return BINARY_POWER;
3506 case LShift:
3507 return BINARY_LSHIFT;
3508 case RShift:
3509 return BINARY_RSHIFT;
3510 case BitOr:
3511 return BINARY_OR;
3512 case BitXor:
3513 return BINARY_XOR;
3514 case BitAnd:
3515 return BINARY_AND;
3516 case FloorDiv:
3517 return BINARY_FLOOR_DIVIDE;
3518 default:
3519 PyErr_Format(PyExc_SystemError,
3520 "binary op %d should not be possible", op);
3521 return 0;
3522 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003523}
3524
3525static int
Andy Lester76d58772020-03-10 21:18:12 -05003526inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003528 switch (op) {
3529 case Add:
3530 return INPLACE_ADD;
3531 case Sub:
3532 return INPLACE_SUBTRACT;
3533 case Mult:
3534 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003535 case MatMult:
3536 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 case Div:
3538 return INPLACE_TRUE_DIVIDE;
3539 case Mod:
3540 return INPLACE_MODULO;
3541 case Pow:
3542 return INPLACE_POWER;
3543 case LShift:
3544 return INPLACE_LSHIFT;
3545 case RShift:
3546 return INPLACE_RSHIFT;
3547 case BitOr:
3548 return INPLACE_OR;
3549 case BitXor:
3550 return INPLACE_XOR;
3551 case BitAnd:
3552 return INPLACE_AND;
3553 case FloorDiv:
3554 return INPLACE_FLOOR_DIVIDE;
3555 default:
3556 PyErr_Format(PyExc_SystemError,
3557 "inplace binary op %d should not be possible", op);
3558 return 0;
3559 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003560}
3561
3562static int
3563compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3564{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003565 int op, scope;
3566 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003567 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003569 PyObject *dict = c->u->u_names;
3570 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003571
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003572 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3573 !_PyUnicode_EqualToASCIIString(name, "True") &&
3574 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003575
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003576 if (forbidden_name(c, name, ctx))
3577 return 0;
3578
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003579 mangled = _Py_Mangle(c->u->u_private, name);
3580 if (!mangled)
3581 return 0;
3582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 op = 0;
3584 optype = OP_NAME;
3585 scope = PyST_GetScope(c->u->u_ste, mangled);
3586 switch (scope) {
3587 case FREE:
3588 dict = c->u->u_freevars;
3589 optype = OP_DEREF;
3590 break;
3591 case CELL:
3592 dict = c->u->u_cellvars;
3593 optype = OP_DEREF;
3594 break;
3595 case LOCAL:
3596 if (c->u->u_ste->ste_type == FunctionBlock)
3597 optype = OP_FAST;
3598 break;
3599 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003600 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003601 optype = OP_GLOBAL;
3602 break;
3603 case GLOBAL_EXPLICIT:
3604 optype = OP_GLOBAL;
3605 break;
3606 default:
3607 /* scope can be 0 */
3608 break;
3609 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003611 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003612 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003614 switch (optype) {
3615 case OP_DEREF:
3616 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003617 case Load:
3618 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3619 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003620 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003621 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003622 }
3623 break;
3624 case OP_FAST:
3625 switch (ctx) {
3626 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003627 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003628 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003629 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003630 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 return 1;
3632 case OP_GLOBAL:
3633 switch (ctx) {
3634 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003635 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003636 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 }
3638 break;
3639 case OP_NAME:
3640 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003641 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003642 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003644 }
3645 break;
3646 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003648 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003649 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003650 Py_DECREF(mangled);
3651 if (arg < 0)
3652 return 0;
3653 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003654}
3655
3656static int
3657compiler_boolop(struct compiler *c, expr_ty e)
3658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003660 int jumpi;
3661 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003662 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003664 assert(e->kind == BoolOp_kind);
3665 if (e->v.BoolOp.op == And)
3666 jumpi = JUMP_IF_FALSE_OR_POP;
3667 else
3668 jumpi = JUMP_IF_TRUE_OR_POP;
3669 end = compiler_new_block(c);
3670 if (end == NULL)
3671 return 0;
3672 s = e->v.BoolOp.values;
3673 n = asdl_seq_LEN(s) - 1;
3674 assert(n >= 0);
3675 for (i = 0; i < n; ++i) {
3676 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003677 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003678 basicblock *next = compiler_new_block(c);
3679 if (next == NULL) {
3680 return 0;
3681 }
3682 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003683 }
3684 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3685 compiler_use_next_block(c, end);
3686 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003687}
3688
3689static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003690starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003691 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003692{
3693 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003694 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003695 if (n > 2 && are_all_items_const(elts, 0, n)) {
3696 PyObject *folded = PyTuple_New(n);
3697 if (folded == NULL) {
3698 return 0;
3699 }
3700 PyObject *val;
3701 for (i = 0; i < n; i++) {
3702 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3703 Py_INCREF(val);
3704 PyTuple_SET_ITEM(folded, i, val);
3705 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003706 if (tuple) {
3707 ADDOP_LOAD_CONST_NEW(c, folded);
3708 } else {
3709 if (add == SET_ADD) {
3710 Py_SETREF(folded, PyFrozenSet_New(folded));
3711 if (folded == NULL) {
3712 return 0;
3713 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003714 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003715 ADDOP_I(c, build, pushed);
3716 ADDOP_LOAD_CONST_NEW(c, folded);
3717 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003718 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003719 return 1;
3720 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003721
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003722 for (i = 0; i < n; i++) {
3723 expr_ty elt = asdl_seq_GET(elts, i);
3724 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003725 seen_star = 1;
3726 }
3727 }
3728 if (seen_star) {
3729 seen_star = 0;
3730 for (i = 0; i < n; i++) {
3731 expr_ty elt = asdl_seq_GET(elts, i);
3732 if (elt->kind == Starred_kind) {
3733 if (seen_star == 0) {
3734 ADDOP_I(c, build, i+pushed);
3735 seen_star = 1;
3736 }
3737 VISIT(c, expr, elt->v.Starred.value);
3738 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003739 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003740 else {
3741 VISIT(c, expr, elt);
3742 if (seen_star) {
3743 ADDOP_I(c, add, 1);
3744 }
3745 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003746 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003747 assert(seen_star);
3748 if (tuple) {
3749 ADDOP(c, LIST_TO_TUPLE);
3750 }
3751 }
3752 else {
3753 for (i = 0; i < n; i++) {
3754 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003755 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003756 }
3757 if (tuple) {
3758 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3759 } else {
3760 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003761 }
3762 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003763 return 1;
3764}
3765
3766static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003767assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003768{
3769 Py_ssize_t n = asdl_seq_LEN(elts);
3770 Py_ssize_t i;
3771 int seen_star = 0;
3772 for (i = 0; i < n; i++) {
3773 expr_ty elt = asdl_seq_GET(elts, i);
3774 if (elt->kind == Starred_kind && !seen_star) {
3775 if ((i >= (1 << 8)) ||
3776 (n-i-1 >= (INT_MAX >> 8)))
3777 return compiler_error(c,
3778 "too many expressions in "
3779 "star-unpacking assignment");
3780 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3781 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003782 }
3783 else if (elt->kind == Starred_kind) {
3784 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003785 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003786 }
3787 }
3788 if (!seen_star) {
3789 ADDOP_I(c, UNPACK_SEQUENCE, n);
3790 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003791 for (i = 0; i < n; i++) {
3792 expr_ty elt = asdl_seq_GET(elts, i);
3793 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3794 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003795 return 1;
3796}
3797
3798static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003799compiler_list(struct compiler *c, expr_ty e)
3800{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003801 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003802 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003803 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003804 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003805 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003806 return starunpack_helper(c, elts, 0, BUILD_LIST,
3807 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003808 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003809 else
3810 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003811 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003812}
3813
3814static int
3815compiler_tuple(struct compiler *c, expr_ty e)
3816{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003817 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003818 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003819 return assignment_helper(c, elts);
3820 }
3821 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003822 return starunpack_helper(c, elts, 0, BUILD_LIST,
3823 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003824 }
3825 else
3826 VISIT_SEQ(c, expr, elts);
3827 return 1;
3828}
3829
3830static int
3831compiler_set(struct compiler *c, expr_ty e)
3832{
Mark Shannon13bc1392020-01-23 09:25:17 +00003833 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3834 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003835}
3836
3837static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003838are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003839{
3840 Py_ssize_t i;
3841 for (i = begin; i < end; i++) {
3842 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003843 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003844 return 0;
3845 }
3846 return 1;
3847}
3848
3849static int
3850compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3851{
3852 Py_ssize_t i, n = end - begin;
3853 PyObject *keys, *key;
3854 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3855 for (i = begin; i < end; i++) {
3856 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3857 }
3858 keys = PyTuple_New(n);
3859 if (keys == NULL) {
3860 return 0;
3861 }
3862 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003863 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003864 Py_INCREF(key);
3865 PyTuple_SET_ITEM(keys, i - begin, key);
3866 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003867 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003868 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3869 }
3870 else {
3871 for (i = begin; i < end; i++) {
3872 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3873 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3874 }
3875 ADDOP_I(c, BUILD_MAP, n);
3876 }
3877 return 1;
3878}
3879
3880static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003881compiler_dict(struct compiler *c, expr_ty e)
3882{
Victor Stinner976bb402016-03-23 11:36:19 +01003883 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003884 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003885 int is_unpacking = 0;
3886 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003887 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003888 elements = 0;
3889 for (i = 0; i < n; i++) {
3890 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003891 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003892 if (elements) {
3893 if (!compiler_subdict(c, e, i - elements, i)) {
3894 return 0;
3895 }
3896 if (have_dict) {
3897 ADDOP_I(c, DICT_UPDATE, 1);
3898 }
3899 have_dict = 1;
3900 elements = 0;
3901 }
3902 if (have_dict == 0) {
3903 ADDOP_I(c, BUILD_MAP, 0);
3904 have_dict = 1;
3905 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003906 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003907 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003908 }
3909 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003910 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003911 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003912 return 0;
3913 }
3914 if (have_dict) {
3915 ADDOP_I(c, DICT_UPDATE, 1);
3916 }
3917 have_dict = 1;
3918 elements = 0;
3919 }
3920 else {
3921 elements++;
3922 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003923 }
3924 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003925 if (elements) {
3926 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003927 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003928 }
3929 if (have_dict) {
3930 ADDOP_I(c, DICT_UPDATE, 1);
3931 }
3932 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003933 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003934 if (!have_dict) {
3935 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003936 }
3937 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003938}
3939
3940static int
3941compiler_compare(struct compiler *c, expr_ty e)
3942{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003943 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003944
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003945 if (!check_compare(c, e)) {
3946 return 0;
3947 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003948 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003949 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3950 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3951 if (n == 0) {
3952 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003953 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003954 }
3955 else {
3956 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003957 if (cleanup == NULL)
3958 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003959 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003960 VISIT(c, expr,
3961 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003962 ADDOP(c, DUP_TOP);
3963 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003964 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003965 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003966 NEXT_BLOCK(c);
3967 }
3968 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003969 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003970 basicblock *end = compiler_new_block(c);
3971 if (end == NULL)
3972 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003973 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003974 compiler_use_next_block(c, cleanup);
3975 ADDOP(c, ROT_TWO);
3976 ADDOP(c, POP_TOP);
3977 compiler_use_next_block(c, end);
3978 }
3979 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003980}
3981
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003982static PyTypeObject *
3983infer_type(expr_ty e)
3984{
3985 switch (e->kind) {
3986 case Tuple_kind:
3987 return &PyTuple_Type;
3988 case List_kind:
3989 case ListComp_kind:
3990 return &PyList_Type;
3991 case Dict_kind:
3992 case DictComp_kind:
3993 return &PyDict_Type;
3994 case Set_kind:
3995 case SetComp_kind:
3996 return &PySet_Type;
3997 case GeneratorExp_kind:
3998 return &PyGen_Type;
3999 case Lambda_kind:
4000 return &PyFunction_Type;
4001 case JoinedStr_kind:
4002 case FormattedValue_kind:
4003 return &PyUnicode_Type;
4004 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01004005 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004006 default:
4007 return NULL;
4008 }
4009}
4010
4011static int
4012check_caller(struct compiler *c, expr_ty e)
4013{
4014 switch (e->kind) {
4015 case Constant_kind:
4016 case Tuple_kind:
4017 case List_kind:
4018 case ListComp_kind:
4019 case Dict_kind:
4020 case DictComp_kind:
4021 case Set_kind:
4022 case SetComp_kind:
4023 case GeneratorExp_kind:
4024 case JoinedStr_kind:
4025 case FormattedValue_kind:
4026 return compiler_warn(c, "'%.200s' object is not callable; "
4027 "perhaps you missed a comma?",
4028 infer_type(e)->tp_name);
4029 default:
4030 return 1;
4031 }
4032}
4033
4034static int
4035check_subscripter(struct compiler *c, expr_ty e)
4036{
4037 PyObject *v;
4038
4039 switch (e->kind) {
4040 case Constant_kind:
4041 v = e->v.Constant.value;
4042 if (!(v == Py_None || v == Py_Ellipsis ||
4043 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4044 PyAnySet_Check(v)))
4045 {
4046 return 1;
4047 }
4048 /* fall through */
4049 case Set_kind:
4050 case SetComp_kind:
4051 case GeneratorExp_kind:
4052 case Lambda_kind:
4053 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4054 "perhaps you missed a comma?",
4055 infer_type(e)->tp_name);
4056 default:
4057 return 1;
4058 }
4059}
4060
4061static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004062check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004063{
4064 PyObject *v;
4065
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004066 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004067 if (index_type == NULL
4068 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4069 || index_type == &PySlice_Type) {
4070 return 1;
4071 }
4072
4073 switch (e->kind) {
4074 case Constant_kind:
4075 v = e->v.Constant.value;
4076 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4077 return 1;
4078 }
4079 /* fall through */
4080 case Tuple_kind:
4081 case List_kind:
4082 case ListComp_kind:
4083 case JoinedStr_kind:
4084 case FormattedValue_kind:
4085 return compiler_warn(c, "%.200s indices must be integers or slices, "
4086 "not %.200s; "
4087 "perhaps you missed a comma?",
4088 infer_type(e)->tp_name,
4089 index_type->tp_name);
4090 default:
4091 return 1;
4092 }
4093}
4094
Zackery Spytz97f5de02019-03-22 01:30:32 -06004095// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004096static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004097maybe_optimize_method_call(struct compiler *c, expr_ty e)
4098{
4099 Py_ssize_t argsl, i;
4100 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004101 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004102
4103 /* Check that the call node is an attribute access, and that
4104 the call doesn't have keyword parameters. */
4105 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4106 asdl_seq_LEN(e->v.Call.keywords))
4107 return -1;
4108
4109 /* Check that there are no *varargs types of arguments. */
4110 argsl = asdl_seq_LEN(args);
4111 for (i = 0; i < argsl; i++) {
4112 expr_ty elt = asdl_seq_GET(args, i);
4113 if (elt->kind == Starred_kind) {
4114 return -1;
4115 }
4116 }
4117
4118 /* Alright, we can optimize the code. */
4119 VISIT(c, expr, meth->v.Attribute.value);
4120 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4121 VISIT_SEQ(c, expr, e->v.Call.args);
4122 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4123 return 1;
4124}
4125
4126static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004127validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004128{
4129 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4130 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004131 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4132 if (key->arg == NULL) {
4133 continue;
4134 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004135 if (forbidden_name(c, key->arg, Store)) {
4136 return -1;
4137 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004138 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004139 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4140 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4141 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4142 if (msg == NULL) {
4143 return -1;
4144 }
4145 c->u->u_col_offset = other->col_offset;
4146 compiler_error(c, PyUnicode_AsUTF8(msg));
4147 Py_DECREF(msg);
4148 return -1;
4149 }
4150 }
4151 }
4152 return 0;
4153}
4154
4155static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004156compiler_call(struct compiler *c, expr_ty e)
4157{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004158 int ret = maybe_optimize_method_call(c, e);
4159 if (ret >= 0) {
4160 return ret;
4161 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004162 if (!check_caller(c, e->v.Call.func)) {
4163 return 0;
4164 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004165 VISIT(c, expr, e->v.Call.func);
4166 return compiler_call_helper(c, 0,
4167 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004168 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004169}
4170
Eric V. Smith235a6f02015-09-19 14:51:32 -04004171static int
4172compiler_joined_str(struct compiler *c, expr_ty e)
4173{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004174 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004175 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4176 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004177 return 1;
4178}
4179
Eric V. Smitha78c7952015-11-03 12:45:05 -05004180/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004181static int
4182compiler_formatted_value(struct compiler *c, expr_ty e)
4183{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004184 /* Our oparg encodes 2 pieces of information: the conversion
4185 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004186
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004187 Convert the conversion char to 3 bits:
4188 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004189 !s : 001 0x1 FVC_STR
4190 !r : 010 0x2 FVC_REPR
4191 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004192
Eric V. Smitha78c7952015-11-03 12:45:05 -05004193 next bit is whether or not we have a format spec:
4194 yes : 100 0x4
4195 no : 000 0x0
4196 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004197
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004198 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004199 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004200
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004201 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004202 VISIT(c, expr, e->v.FormattedValue.value);
4203
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004204 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004205 case 's': oparg = FVC_STR; break;
4206 case 'r': oparg = FVC_REPR; break;
4207 case 'a': oparg = FVC_ASCII; break;
4208 case -1: oparg = FVC_NONE; break;
4209 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004210 PyErr_Format(PyExc_SystemError,
4211 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004212 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004213 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004214 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004215 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004216 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004217 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004218 }
4219
Eric V. Smitha78c7952015-11-03 12:45:05 -05004220 /* And push our opcode and oparg */
4221 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004222
Eric V. Smith235a6f02015-09-19 14:51:32 -04004223 return 1;
4224}
4225
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004226static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004227compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004228{
4229 Py_ssize_t i, n = end - begin;
4230 keyword_ty kw;
4231 PyObject *keys, *key;
4232 assert(n > 0);
4233 if (n > 1) {
4234 for (i = begin; i < end; i++) {
4235 kw = asdl_seq_GET(keywords, i);
4236 VISIT(c, expr, kw->value);
4237 }
4238 keys = PyTuple_New(n);
4239 if (keys == NULL) {
4240 return 0;
4241 }
4242 for (i = begin; i < end; i++) {
4243 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4244 Py_INCREF(key);
4245 PyTuple_SET_ITEM(keys, i - begin, key);
4246 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004247 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004248 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4249 }
4250 else {
4251 /* a for loop only executes once */
4252 for (i = begin; i < end; i++) {
4253 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004254 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004255 VISIT(c, expr, kw->value);
4256 }
4257 ADDOP_I(c, BUILD_MAP, n);
4258 }
4259 return 1;
4260}
4261
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004262/* shared code between compiler_call and compiler_class */
4263static int
4264compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004265 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004266 asdl_expr_seq *args,
4267 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004268{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004269 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004270
Pablo Galindo254ec782020-04-03 20:37:13 +01004271 if (validate_keywords(c, keywords) == -1) {
4272 return 0;
4273 }
4274
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004275 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004276 nkwelts = asdl_seq_LEN(keywords);
4277
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004278 for (i = 0; i < nelts; i++) {
4279 expr_ty elt = asdl_seq_GET(args, i);
4280 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004281 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004282 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004283 }
4284 for (i = 0; i < nkwelts; i++) {
4285 keyword_ty kw = asdl_seq_GET(keywords, i);
4286 if (kw->arg == NULL) {
4287 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004288 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004289 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004290
Mark Shannon13bc1392020-01-23 09:25:17 +00004291 /* No * or ** args, so can use faster calling sequence */
4292 for (i = 0; i < nelts; i++) {
4293 expr_ty elt = asdl_seq_GET(args, i);
4294 assert(elt->kind != Starred_kind);
4295 VISIT(c, expr, elt);
4296 }
4297 if (nkwelts) {
4298 PyObject *names;
4299 VISIT_SEQ(c, keyword, keywords);
4300 names = PyTuple_New(nkwelts);
4301 if (names == NULL) {
4302 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004303 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004304 for (i = 0; i < nkwelts; i++) {
4305 keyword_ty kw = asdl_seq_GET(keywords, i);
4306 Py_INCREF(kw->arg);
4307 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004308 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004309 ADDOP_LOAD_CONST_NEW(c, names);
4310 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4311 return 1;
4312 }
4313 else {
4314 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4315 return 1;
4316 }
4317
4318ex_call:
4319
4320 /* Do positional arguments. */
4321 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4322 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4323 }
4324 else if (starunpack_helper(c, args, n, BUILD_LIST,
4325 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4326 return 0;
4327 }
4328 /* Then keyword arguments */
4329 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004330 /* Has a new dict been pushed */
4331 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004332
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004333 nseen = 0; /* the number of keyword arguments on the stack following */
4334 for (i = 0; i < nkwelts; i++) {
4335 keyword_ty kw = asdl_seq_GET(keywords, i);
4336 if (kw->arg == NULL) {
4337 /* A keyword argument unpacking. */
4338 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004339 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004340 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004341 }
Mark Shannondb64f122020-06-01 10:42:42 +01004342 if (have_dict) {
4343 ADDOP_I(c, DICT_MERGE, 1);
4344 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004345 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004346 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004347 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004348 if (!have_dict) {
4349 ADDOP_I(c, BUILD_MAP, 0);
4350 have_dict = 1;
4351 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004352 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004353 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004354 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004355 else {
4356 nseen++;
4357 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004358 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004359 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004360 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004361 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004362 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004363 }
4364 if (have_dict) {
4365 ADDOP_I(c, DICT_MERGE, 1);
4366 }
4367 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004368 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004369 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004371 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4372 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004373}
4374
Nick Coghlan650f0d02007-04-15 12:05:43 +00004375
4376/* List and set comprehensions and generator expressions work by creating a
4377 nested function to perform the actual iteration. This means that the
4378 iteration variables don't leak into the current scope.
4379 The defined function is called immediately following its definition, with the
4380 result of that call being the result of the expression.
4381 The LC/SC version returns the populated container, while the GE version is
4382 flagged in symtable.c as a generator, so it returns the generator object
4383 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004384
4385 Possible cleanups:
4386 - iterate over the generator sequence instead of using recursion
4387*/
4388
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004389
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004390static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004391compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004392 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004393 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004394 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004395{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004396 comprehension_ty gen;
4397 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4398 if (gen->is_async) {
4399 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004400 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004401 } else {
4402 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004403 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004404 }
4405}
4406
4407static int
4408compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004409 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004410 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004411 expr_ty elt, expr_ty val, int type)
4412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004413 /* generate code for the iterator, then each of the ifs,
4414 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004416 comprehension_ty gen;
4417 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004418 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 start = compiler_new_block(c);
4421 skip = compiler_new_block(c);
4422 if_cleanup = compiler_new_block(c);
4423 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004425 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4426 anchor == NULL)
4427 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004429 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004431 if (gen_index == 0) {
4432 /* Receive outermost iter as an implicit argument */
4433 c->u->u_argcount = 1;
4434 ADDOP_I(c, LOAD_FAST, 0);
4435 }
4436 else {
4437 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004438 /* Fast path for the temporary variable assignment idiom:
4439 for y in [f(x)]
4440 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004441 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004442 switch (gen->iter->kind) {
4443 case List_kind:
4444 elts = gen->iter->v.List.elts;
4445 break;
4446 case Tuple_kind:
4447 elts = gen->iter->v.Tuple.elts;
4448 break;
4449 default:
4450 elts = NULL;
4451 }
4452 if (asdl_seq_LEN(elts) == 1) {
4453 expr_ty elt = asdl_seq_GET(elts, 0);
4454 if (elt->kind != Starred_kind) {
4455 VISIT(c, expr, elt);
4456 start = NULL;
4457 }
4458 }
4459 if (start) {
4460 VISIT(c, expr, gen->iter);
4461 ADDOP(c, GET_ITER);
4462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004463 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004464 if (start) {
4465 depth++;
4466 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004467 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004468 NEXT_BLOCK(c);
4469 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004470 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004472 /* XXX this needs to be cleaned up...a lot! */
4473 n = asdl_seq_LEN(gen->ifs);
4474 for (i = 0; i < n; i++) {
4475 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004476 if (!compiler_jump_if(c, e, if_cleanup, 0))
4477 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004478 NEXT_BLOCK(c);
4479 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004481 if (++gen_index < asdl_seq_LEN(generators))
4482 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004483 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004484 elt, val, type))
4485 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004487 /* only append after the last for generator */
4488 if (gen_index >= asdl_seq_LEN(generators)) {
4489 /* comprehension specific code */
4490 switch (type) {
4491 case COMP_GENEXP:
4492 VISIT(c, expr, elt);
4493 ADDOP(c, YIELD_VALUE);
4494 ADDOP(c, POP_TOP);
4495 break;
4496 case COMP_LISTCOMP:
4497 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004498 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004499 break;
4500 case COMP_SETCOMP:
4501 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004502 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004503 break;
4504 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004505 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004506 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004507 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004508 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004509 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 break;
4511 default:
4512 return 0;
4513 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004515 compiler_use_next_block(c, skip);
4516 }
4517 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004518 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004519 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004520 compiler_use_next_block(c, anchor);
4521 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004522
4523 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004524}
4525
4526static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004528 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004529 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004530 expr_ty elt, expr_ty val, int type)
4531{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004532 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004533 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004534 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004535 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004536 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004537 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004538
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004539 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004540 return 0;
4541 }
4542
4543 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4544
4545 if (gen_index == 0) {
4546 /* Receive outermost iter as an implicit argument */
4547 c->u->u_argcount = 1;
4548 ADDOP_I(c, LOAD_FAST, 0);
4549 }
4550 else {
4551 /* Sub-iter - calculate on the fly */
4552 VISIT(c, expr, gen->iter);
4553 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 }
4555
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004556 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557
Mark Shannon582aaf12020-08-04 17:30:11 +01004558 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004559 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004560 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004561 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004562 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004563 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004564
4565 n = asdl_seq_LEN(gen->ifs);
4566 for (i = 0; i < n; i++) {
4567 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004568 if (!compiler_jump_if(c, e, if_cleanup, 0))
4569 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004570 NEXT_BLOCK(c);
4571 }
4572
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004573 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004574 if (++gen_index < asdl_seq_LEN(generators))
4575 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004576 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004577 elt, val, type))
4578 return 0;
4579
4580 /* only append after the last for generator */
4581 if (gen_index >= asdl_seq_LEN(generators)) {
4582 /* comprehension specific code */
4583 switch (type) {
4584 case COMP_GENEXP:
4585 VISIT(c, expr, elt);
4586 ADDOP(c, YIELD_VALUE);
4587 ADDOP(c, POP_TOP);
4588 break;
4589 case COMP_LISTCOMP:
4590 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004591 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004592 break;
4593 case COMP_SETCOMP:
4594 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004595 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004596 break;
4597 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004598 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004599 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004600 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004601 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004602 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004603 break;
4604 default:
4605 return 0;
4606 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004607 }
4608 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004609 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004610
4611 compiler_use_next_block(c, except);
4612 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004613
4614 return 1;
4615}
4616
4617static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004618compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004619 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004620 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004623 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004624 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004625 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004626 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004627
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004628
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004629 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004630
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004631 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004632 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4633 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004634 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004635 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004636 }
4637
4638 is_async_generator = c->u->u_ste->ste_coroutine;
4639
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004640 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004641 compiler_error(c, "asynchronous comprehension outside of "
4642 "an asynchronous function");
4643 goto error_in_scope;
4644 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004646 if (type != COMP_GENEXP) {
4647 int op;
4648 switch (type) {
4649 case COMP_LISTCOMP:
4650 op = BUILD_LIST;
4651 break;
4652 case COMP_SETCOMP:
4653 op = BUILD_SET;
4654 break;
4655 case COMP_DICTCOMP:
4656 op = BUILD_MAP;
4657 break;
4658 default:
4659 PyErr_Format(PyExc_SystemError,
4660 "unknown comprehension type %d", type);
4661 goto error_in_scope;
4662 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004664 ADDOP_I(c, op, 0);
4665 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004666
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004667 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004668 val, type))
4669 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004671 if (type != COMP_GENEXP) {
4672 ADDOP(c, RETURN_VALUE);
4673 }
4674
4675 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004676 qualname = c->u->u_qualname;
4677 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004679 if (top_level_await && is_async_generator){
4680 c->u->u_ste->ste_coroutine = 1;
4681 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004682 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 goto error;
4684
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004685 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004686 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004687 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004688 Py_DECREF(co);
4689
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004690 VISIT(c, expr, outermost->iter);
4691
4692 if (outermost->is_async) {
4693 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004694 } else {
4695 ADDOP(c, GET_ITER);
4696 }
4697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004698 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004699
4700 if (is_async_generator && type != COMP_GENEXP) {
4701 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004702 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004703 ADDOP(c, YIELD_FROM);
4704 }
4705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004707error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004708 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004709error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004710 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004711 Py_XDECREF(co);
4712 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004713}
4714
4715static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004716compiler_genexp(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("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 if (!name)
4722 return 0;
4723 }
4724 assert(e->kind == GeneratorExp_kind);
4725 return compiler_comprehension(c, e, COMP_GENEXP, name,
4726 e->v.GeneratorExp.generators,
4727 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004728}
4729
4730static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004731compiler_listcomp(struct compiler *c, expr_ty e)
4732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004733 static identifier name;
4734 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004735 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004736 if (!name)
4737 return 0;
4738 }
4739 assert(e->kind == ListComp_kind);
4740 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4741 e->v.ListComp.generators,
4742 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004743}
4744
4745static int
4746compiler_setcomp(struct compiler *c, expr_ty e)
4747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004748 static identifier name;
4749 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004750 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004751 if (!name)
4752 return 0;
4753 }
4754 assert(e->kind == SetComp_kind);
4755 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4756 e->v.SetComp.generators,
4757 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004758}
4759
4760
4761static int
4762compiler_dictcomp(struct compiler *c, expr_ty e)
4763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004764 static identifier name;
4765 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004766 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004767 if (!name)
4768 return 0;
4769 }
4770 assert(e->kind == DictComp_kind);
4771 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4772 e->v.DictComp.generators,
4773 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004774}
4775
4776
4777static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004778compiler_visit_keyword(struct compiler *c, keyword_ty k)
4779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004780 VISIT(c, expr, k->value);
4781 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004782}
4783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004784/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004785 whether they are true or false.
4786
4787 Return values: 1 for true, 0 for false, -1 for non-constant.
4788 */
4789
4790static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004791expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004792{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004793 if (e->kind == Constant_kind) {
4794 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004795 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004796 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004797}
4798
Mark Shannonfee55262019-11-21 09:11:43 +00004799static int
4800compiler_with_except_finish(struct compiler *c) {
4801 basicblock *exit;
4802 exit = compiler_new_block(c);
4803 if (exit == NULL)
4804 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004805 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004806 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004807 ADDOP(c, RERAISE);
4808 compiler_use_next_block(c, exit);
4809 ADDOP(c, POP_TOP);
4810 ADDOP(c, POP_TOP);
4811 ADDOP(c, POP_TOP);
4812 ADDOP(c, POP_EXCEPT);
4813 ADDOP(c, POP_TOP);
4814 return 1;
4815}
Yury Selivanov75445082015-05-11 22:57:16 -04004816
4817/*
4818 Implements the async with statement.
4819
4820 The semantics outlined in that PEP are as follows:
4821
4822 async with EXPR as VAR:
4823 BLOCK
4824
4825 It is implemented roughly as:
4826
4827 context = EXPR
4828 exit = context.__aexit__ # not calling it
4829 value = await context.__aenter__()
4830 try:
4831 VAR = value # if VAR present in the syntax
4832 BLOCK
4833 finally:
4834 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004835 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004836 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004837 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004838 if not (await exit(*exc)):
4839 raise
4840 */
4841static int
4842compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4843{
Mark Shannonfee55262019-11-21 09:11:43 +00004844 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004845 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4846
4847 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004848 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004849 c->u->u_ste->ste_coroutine = 1;
4850 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004851 return compiler_error(c, "'async with' outside async function");
4852 }
Yury Selivanov75445082015-05-11 22:57:16 -04004853
4854 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004855 final = compiler_new_block(c);
4856 exit = compiler_new_block(c);
4857 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004858 return 0;
4859
4860 /* Evaluate EXPR */
4861 VISIT(c, expr, item->context_expr);
4862
4863 ADDOP(c, BEFORE_ASYNC_WITH);
4864 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004865 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004866 ADDOP(c, YIELD_FROM);
4867
Mark Shannon582aaf12020-08-04 17:30:11 +01004868 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004869
4870 /* SETUP_ASYNC_WITH pushes a finally block. */
4871 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004872 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004873 return 0;
4874 }
4875
4876 if (item->optional_vars) {
4877 VISIT(c, expr, item->optional_vars);
4878 }
4879 else {
4880 /* Discard result from context.__aenter__() */
4881 ADDOP(c, POP_TOP);
4882 }
4883
4884 pos++;
4885 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4886 /* BLOCK code */
4887 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4888 else if (!compiler_async_with(c, s, pos))
4889 return 0;
4890
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004891 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004892 ADDOP(c, POP_BLOCK);
4893 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004894
Mark Shannonfee55262019-11-21 09:11:43 +00004895 /* For successful outcome:
4896 * call __exit__(None, None, None)
4897 */
4898 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004899 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004900 ADDOP(c, GET_AWAITABLE);
4901 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4902 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004903
Mark Shannonfee55262019-11-21 09:11:43 +00004904 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004905
Mark Shannon582aaf12020-08-04 17:30:11 +01004906 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004907
4908 /* For exceptional outcome: */
4909 compiler_use_next_block(c, final);
4910
4911 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004912 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004913 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004914 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004915 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004916
Mark Shannonfee55262019-11-21 09:11:43 +00004917compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004918 return 1;
4919}
4920
4921
Guido van Rossumc2e20742006-02-27 22:32:47 +00004922/*
4923 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004924 with EXPR as VAR:
4925 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004926 is implemented as:
4927 <code for EXPR>
4928 SETUP_WITH E
4929 <code to store to VAR> or POP_TOP
4930 <code for BLOCK>
4931 LOAD_CONST (None, None, None)
4932 CALL_FUNCTION_EX 0
4933 JUMP_FORWARD EXIT
4934 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4935 POP_JUMP_IF_TRUE T:
4936 RERAISE
4937 T: POP_TOP * 3 (remove exception from stack)
4938 POP_EXCEPT
4939 POP_TOP
4940 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004941 */
Mark Shannonfee55262019-11-21 09:11:43 +00004942
Guido van Rossumc2e20742006-02-27 22:32:47 +00004943static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004944compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004945{
Mark Shannonfee55262019-11-21 09:11:43 +00004946 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004947 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004948
4949 assert(s->kind == With_kind);
4950
Guido van Rossumc2e20742006-02-27 22:32:47 +00004951 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004952 final = compiler_new_block(c);
4953 exit = compiler_new_block(c);
4954 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004955 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004956
Thomas Wouters477c8d52006-05-27 19:21:47 +00004957 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004958 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004959 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004960 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004961
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004962 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004963 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004964 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004965 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004966 }
4967
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004968 if (item->optional_vars) {
4969 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004970 }
4971 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004972 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004973 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004974 }
4975
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004976 pos++;
4977 if (pos == asdl_seq_LEN(s->v.With.items))
4978 /* BLOCK code */
4979 VISIT_SEQ(c, stmt, s->v.With.body)
4980 else if (!compiler_with(c, s, pos))
4981 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004982
Guido van Rossumc2e20742006-02-27 22:32:47 +00004983 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004984 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004985
Mark Shannonfee55262019-11-21 09:11:43 +00004986 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004987
Mark Shannonfee55262019-11-21 09:11:43 +00004988 /* For successful outcome:
4989 * call __exit__(None, None, None)
4990 */
4991 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004992 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004993 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004994 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004995
Mark Shannonfee55262019-11-21 09:11:43 +00004996 /* For exceptional outcome: */
4997 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004998
Mark Shannonfee55262019-11-21 09:11:43 +00004999 ADDOP(c, WITH_EXCEPT_START);
5000 compiler_with_except_finish(c);
5001
5002 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00005003 return 1;
5004}
5005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005006static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005007compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07005010 case NamedExpr_kind:
5011 VISIT(c, expr, e->v.NamedExpr.value);
5012 ADDOP(c, DUP_TOP);
5013 VISIT(c, expr, e->v.NamedExpr.target);
5014 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 case BoolOp_kind:
5016 return compiler_boolop(c, e);
5017 case BinOp_kind:
5018 VISIT(c, expr, e->v.BinOp.left);
5019 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05005020 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005021 break;
5022 case UnaryOp_kind:
5023 VISIT(c, expr, e->v.UnaryOp.operand);
5024 ADDOP(c, unaryop(e->v.UnaryOp.op));
5025 break;
5026 case Lambda_kind:
5027 return compiler_lambda(c, e);
5028 case IfExp_kind:
5029 return compiler_ifexp(c, e);
5030 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005031 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005032 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005033 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005034 case GeneratorExp_kind:
5035 return compiler_genexp(c, e);
5036 case ListComp_kind:
5037 return compiler_listcomp(c, e);
5038 case SetComp_kind:
5039 return compiler_setcomp(c, e);
5040 case DictComp_kind:
5041 return compiler_dictcomp(c, e);
5042 case Yield_kind:
5043 if (c->u->u_ste->ste_type != FunctionBlock)
5044 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005045 if (e->v.Yield.value) {
5046 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005047 }
5048 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005049 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005050 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005051 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005052 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005053 case YieldFrom_kind:
5054 if (c->u->u_ste->ste_type != FunctionBlock)
5055 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005056
5057 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5058 return compiler_error(c, "'yield from' inside async function");
5059
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005060 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005061 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005062 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005063 ADDOP(c, YIELD_FROM);
5064 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005065 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005066 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005067 if (c->u->u_ste->ste_type != FunctionBlock){
5068 return compiler_error(c, "'await' outside function");
5069 }
Yury Selivanov75445082015-05-11 22:57:16 -04005070
Victor Stinner331a6a52019-05-27 16:39:22 +02005071 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005072 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5073 return compiler_error(c, "'await' outside async function");
5074 }
5075 }
Yury Selivanov75445082015-05-11 22:57:16 -04005076
5077 VISIT(c, expr, e->v.Await.value);
5078 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005079 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005080 ADDOP(c, YIELD_FROM);
5081 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005082 case Compare_kind:
5083 return compiler_compare(c, e);
5084 case Call_kind:
5085 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005086 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005087 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005088 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005089 case JoinedStr_kind:
5090 return compiler_joined_str(c, e);
5091 case FormattedValue_kind:
5092 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005093 /* The following exprs can be assignment targets. */
5094 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005095 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005096 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 case Load:
5098 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5099 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005100 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005101 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5102 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005103 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5104 break;
5105 case Del:
5106 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5107 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005108 }
5109 break;
5110 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005111 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005112 case Starred_kind:
5113 switch (e->v.Starred.ctx) {
5114 case Store:
5115 /* In all legitimate cases, the Starred node was already replaced
5116 * by compiler_list/compiler_tuple. XXX: is that okay? */
5117 return compiler_error(c,
5118 "starred assignment target must be in a list or tuple");
5119 default:
5120 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005121 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005122 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005123 break;
5124 case Slice_kind:
5125 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005126 case Name_kind:
5127 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5128 /* child nodes of List and Tuple will have expr_context set */
5129 case List_kind:
5130 return compiler_list(c, e);
5131 case Tuple_kind:
5132 return compiler_tuple(c, e);
5133 }
5134 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005135}
5136
5137static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005138compiler_visit_expr(struct compiler *c, expr_ty e)
5139{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005140 int old_lineno = c->u->u_lineno;
5141 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005142 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005143 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005144 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005145 c->u->u_col_offset = old_col_offset;
5146 return res;
5147}
5148
5149static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005150compiler_augassign(struct compiler *c, stmt_ty s)
5151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005152 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005153 expr_ty e = s->v.AugAssign.target;
5154
5155 int old_lineno = c->u->u_lineno;
5156 int old_col_offset = c->u->u_col_offset;
5157 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005159 switch (e->kind) {
5160 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005161 VISIT(c, expr, e->v.Attribute.value);
5162 ADDOP(c, DUP_TOP);
5163 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 break;
5165 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005166 VISIT(c, expr, e->v.Subscript.value);
5167 VISIT(c, expr, e->v.Subscript.slice);
5168 ADDOP(c, DUP_TOP_TWO);
5169 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005170 break;
5171 case Name_kind:
5172 if (!compiler_nameop(c, e->v.Name.id, Load))
5173 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005174 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005175 default:
5176 PyErr_Format(PyExc_SystemError,
5177 "invalid node type (%d) for augmented assignment",
5178 e->kind);
5179 return 0;
5180 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005181
5182 c->u->u_lineno = old_lineno;
5183 c->u->u_col_offset = old_col_offset;
5184
5185 VISIT(c, expr, s->v.AugAssign.value);
5186 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5187
5188 SET_LOC(c, e);
5189
5190 switch (e->kind) {
5191 case Attribute_kind:
5192 ADDOP(c, ROT_TWO);
5193 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5194 break;
5195 case Subscript_kind:
5196 ADDOP(c, ROT_THREE);
5197 ADDOP(c, STORE_SUBSCR);
5198 break;
5199 case Name_kind:
5200 return compiler_nameop(c, e->v.Name.id, Store);
5201 default:
5202 Py_UNREACHABLE();
5203 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005204 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005205}
5206
5207static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005208check_ann_expr(struct compiler *c, expr_ty e)
5209{
5210 VISIT(c, expr, e);
5211 ADDOP(c, POP_TOP);
5212 return 1;
5213}
5214
5215static int
5216check_annotation(struct compiler *c, stmt_ty s)
5217{
5218 /* Annotations are only evaluated in a module or class. */
5219 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5220 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5221 return check_ann_expr(c, s->v.AnnAssign.annotation);
5222 }
5223 return 1;
5224}
5225
5226static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005227check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005228{
5229 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005230 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005231 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005232 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005233 return 0;
5234 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005235 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5236 return 0;
5237 }
5238 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5239 return 0;
5240 }
5241 return 1;
5242 case Tuple_kind: {
5243 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005244 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005245 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005246 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005247 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005248 return 0;
5249 }
5250 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005251 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005252 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005253 default:
5254 return check_ann_expr(c, e);
5255 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005256}
5257
5258static int
5259compiler_annassign(struct compiler *c, stmt_ty s)
5260{
5261 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005262 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005263
5264 assert(s->kind == AnnAssign_kind);
5265
5266 /* We perform the actual assignment first. */
5267 if (s->v.AnnAssign.value) {
5268 VISIT(c, expr, s->v.AnnAssign.value);
5269 VISIT(c, expr, targ);
5270 }
5271 switch (targ->kind) {
5272 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005273 if (forbidden_name(c, targ->v.Name.id, Store))
5274 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005275 /* If we have a simple name in a module or class, store annotation. */
5276 if (s->v.AnnAssign.simple &&
5277 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5278 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005279 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005280 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005281 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005282 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005283 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005284 }
5285 break;
5286 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005287 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5288 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005289 if (!s->v.AnnAssign.value &&
5290 !check_ann_expr(c, targ->v.Attribute.value)) {
5291 return 0;
5292 }
5293 break;
5294 case Subscript_kind:
5295 if (!s->v.AnnAssign.value &&
5296 (!check_ann_expr(c, targ->v.Subscript.value) ||
5297 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5298 return 0;
5299 }
5300 break;
5301 default:
5302 PyErr_Format(PyExc_SystemError,
5303 "invalid node type (%d) for annotated assignment",
5304 targ->kind);
5305 return 0;
5306 }
5307 /* Annotation is evaluated last. */
5308 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5309 return 0;
5310 }
5311 return 1;
5312}
5313
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005314/* Raises a SyntaxError and returns 0.
5315 If something goes wrong, a different exception may be raised.
5316*/
5317
5318static int
5319compiler_error(struct compiler *c, const char *errstr)
5320{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005321 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005322 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005323
Victor Stinner14e461d2013-08-26 22:28:21 +02005324 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 if (!loc) {
5326 Py_INCREF(Py_None);
5327 loc = Py_None;
5328 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005329 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005330 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005331 if (!u)
5332 goto exit;
5333 v = Py_BuildValue("(zO)", errstr, u);
5334 if (!v)
5335 goto exit;
5336 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005337 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005338 Py_DECREF(loc);
5339 Py_XDECREF(u);
5340 Py_XDECREF(v);
5341 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005342}
5343
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005344/* Emits a SyntaxWarning and returns 1 on success.
5345 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5346 and returns 0.
5347*/
5348static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005349compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005350{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005351 va_list vargs;
5352#ifdef HAVE_STDARG_PROTOTYPES
5353 va_start(vargs, format);
5354#else
5355 va_start(vargs);
5356#endif
5357 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5358 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005359 if (msg == NULL) {
5360 return 0;
5361 }
5362 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5363 c->u->u_lineno, NULL, NULL) < 0)
5364 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005365 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005366 /* Replace the SyntaxWarning exception with a SyntaxError
5367 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005368 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005369 assert(PyUnicode_AsUTF8(msg) != NULL);
5370 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005371 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005372 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005373 return 0;
5374 }
5375 Py_DECREF(msg);
5376 return 1;
5377}
5378
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005379static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005380compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005381{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005382 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005383 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005384
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005385 if (ctx == Load) {
5386 if (!check_subscripter(c, e->v.Subscript.value)) {
5387 return 0;
5388 }
5389 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5390 return 0;
5391 }
5392 }
5393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005394 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005395 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 case Store: op = STORE_SUBSCR; break;
5397 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005398 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005399 assert(op);
5400 VISIT(c, expr, e->v.Subscript.value);
5401 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005402 ADDOP(c, op);
5403 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005404}
5405
5406static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005407compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005409 int n = 2;
5410 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 /* only handles the cases where BUILD_SLICE is emitted */
5413 if (s->v.Slice.lower) {
5414 VISIT(c, expr, s->v.Slice.lower);
5415 }
5416 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005417 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005418 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 if (s->v.Slice.upper) {
5421 VISIT(c, expr, s->v.Slice.upper);
5422 }
5423 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005424 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005425 }
5426
5427 if (s->v.Slice.step) {
5428 n++;
5429 VISIT(c, expr, s->v.Slice.step);
5430 }
5431 ADDOP_I(c, BUILD_SLICE, n);
5432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005433}
5434
Thomas Wouters89f507f2006-12-13 04:49:30 +00005435/* End of the compiler section, beginning of the assembler section */
5436
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005437/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005438 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005439
5440 XXX must handle implicit jumps from one block to next
5441*/
5442
Thomas Wouters89f507f2006-12-13 04:49:30 +00005443struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005444 PyObject *a_bytecode; /* string containing bytecode */
5445 int a_offset; /* offset into bytecode */
5446 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005447 PyObject *a_lnotab; /* string containing lnotab */
5448 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005449 int a_prevlineno; /* lineno of last emitted line in line table */
5450 int a_lineno; /* lineno of last emitted instruction */
5451 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005452 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005453};
5454
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005455Py_LOCAL_INLINE(void)
5456stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005457{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005458 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005459 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005460 assert(b->b_startdepth < 0);
5461 b->b_startdepth = depth;
5462 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005464}
5465
5466/* Find the flow path that needs the largest stack. We assume that
5467 * cycles in the flow graph have no net effect on the stack depth.
5468 */
5469static int
5470stackdepth(struct compiler *c)
5471{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005472 basicblock *b, *entryblock = NULL;
5473 basicblock **stack, **sp;
5474 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005475 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005476 b->b_startdepth = INT_MIN;
5477 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005478 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005479 }
5480 if (!entryblock)
5481 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005482 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5483 if (!stack) {
5484 PyErr_NoMemory();
5485 return -1;
5486 }
5487
5488 sp = stack;
5489 stackdepth_push(&sp, entryblock, 0);
5490 while (sp != stack) {
5491 b = *--sp;
5492 int depth = b->b_startdepth;
5493 assert(depth >= 0);
5494 basicblock *next = b->b_next;
5495 for (int i = 0; i < b->b_iused; i++) {
5496 struct instr *instr = &b->b_instr[i];
5497 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5498 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005499 _Py_FatalErrorFormat(__func__,
5500 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005501 }
5502 int new_depth = depth + effect;
5503 if (new_depth > maxdepth) {
5504 maxdepth = new_depth;
5505 }
5506 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005507 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005508 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5509 assert(effect != PY_INVALID_STACK_EFFECT);
5510 int target_depth = depth + effect;
5511 if (target_depth > maxdepth) {
5512 maxdepth = target_depth;
5513 }
5514 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005515 stackdepth_push(&sp, instr->i_target, target_depth);
5516 }
5517 depth = new_depth;
5518 if (instr->i_opcode == JUMP_ABSOLUTE ||
5519 instr->i_opcode == JUMP_FORWARD ||
5520 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005521 instr->i_opcode == RAISE_VARARGS ||
5522 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005523 {
5524 /* remaining code is dead */
5525 next = NULL;
5526 break;
5527 }
5528 }
5529 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005530 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005531 stackdepth_push(&sp, next, depth);
5532 }
5533 }
5534 PyObject_Free(stack);
5535 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005536}
5537
5538static int
5539assemble_init(struct assembler *a, int nblocks, int firstlineno)
5540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005542 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005543 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005544 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005545 if (a->a_bytecode == NULL) {
5546 goto error;
5547 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005549 if (a->a_lnotab == NULL) {
5550 goto error;
5551 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005552 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005553 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005554 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005556 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005557error:
5558 Py_XDECREF(a->a_bytecode);
5559 Py_XDECREF(a->a_lnotab);
5560 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005561}
5562
5563static void
5564assemble_free(struct assembler *a)
5565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 Py_XDECREF(a->a_bytecode);
5567 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005568}
5569
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005570static int
5571blocksize(basicblock *b)
5572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005573 int i;
5574 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005576 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005577 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005579}
5580
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005581static int
Mark Shannon877df852020-11-12 09:43:29 +00005582assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005583{
Mark Shannon877df852020-11-12 09:43:29 +00005584 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 if (a->a_lnotab_off + 2 >= len) {
5586 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5587 return 0;
5588 }
Mark Shannon877df852020-11-12 09:43:29 +00005589 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005590 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005592 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005593 *lnotab++ = bdelta;
5594 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005595 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005596}
5597
Mark Shannon877df852020-11-12 09:43:29 +00005598/* Appends a range to the end of the line number table. See
5599 * Objects/lnotab_notes.txt for the description of the line number table. */
5600
5601static int
5602assemble_line_range(struct assembler *a)
5603{
5604 int ldelta, bdelta;
5605 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5606 if (bdelta == 0) {
5607 return 1;
5608 }
5609 if (a->a_lineno < 0) {
5610 ldelta = -128;
5611 }
5612 else {
5613 ldelta = a->a_lineno - a->a_prevlineno;
5614 a->a_prevlineno = a->a_lineno;
5615 while (ldelta > 127) {
5616 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5617 return 0;
5618 }
5619 ldelta -= 127;
5620 }
5621 while (ldelta < -127) {
5622 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5623 return 0;
5624 }
5625 ldelta += 127;
5626 }
5627 }
5628 assert(-128 <= ldelta && ldelta < 128);
5629 while (bdelta > 254) {
5630 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5631 return 0;
5632 }
5633 ldelta = a->a_lineno < 0 ? -128 : 0;
5634 bdelta -= 254;
5635 }
5636 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5637 return 0;
5638 }
5639 a->a_lineno_start = a->a_offset;
5640 return 1;
5641}
5642
5643static int
5644assemble_lnotab(struct assembler *a, struct instr *i)
5645{
5646 if (i->i_lineno == a->a_lineno) {
5647 return 1;
5648 }
5649 if (!assemble_line_range(a)) {
5650 return 0;
5651 }
5652 a->a_lineno = i->i_lineno;
5653 return 1;
5654}
5655
5656
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005657/* assemble_emit()
5658 Extend the bytecode with a new instruction.
5659 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005660*/
5661
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005662static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005663assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005664{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005665 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005667 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005668
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005669 arg = i->i_oparg;
5670 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005671 if (i->i_lineno && !assemble_lnotab(a, i))
5672 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005673 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 if (len > PY_SSIZE_T_MAX / 2)
5675 return 0;
5676 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5677 return 0;
5678 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005679 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005680 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005681 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005682 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005683}
5684
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005685static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005686assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005688 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005689 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005692 /* Compute the size of each block and fixup jump args.
5693 Replace block pointer with position in bytecode. */
5694 do {
5695 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005696 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005697 bsize = blocksize(b);
5698 b->b_offset = totsize;
5699 totsize += bsize;
5700 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005701 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005702 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5703 bsize = b->b_offset;
5704 for (i = 0; i < b->b_iused; i++) {
5705 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005706 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005707 /* Relative jumps are computed relative to
5708 the instruction pointer after fetching
5709 the jump instruction.
5710 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005711 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005712 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005713 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005714 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005715 instr->i_oparg -= bsize;
5716 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005717 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005718 if (instrsize(instr->i_oparg) != isize) {
5719 extended_arg_recompile = 1;
5720 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005721 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 }
5723 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 /* XXX: This is an awful hack that could hurt performance, but
5726 on the bright side it should work until we come up
5727 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005729 The issue is that in the first loop blocksize() is called
5730 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005731 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005732 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 So we loop until we stop seeing new EXTENDED_ARGs.
5735 The only EXTENDED_ARGs that could be popping up are
5736 ones in jump instructions. So this should converge
5737 fairly quickly.
5738 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005739 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005740}
5741
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005742static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005743dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005745 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005746 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005748 tuple = PyTuple_New(size);
5749 if (tuple == NULL)
5750 return NULL;
5751 while (PyDict_Next(dict, &pos, &k, &v)) {
5752 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005753 Py_INCREF(k);
5754 assert((i - offset) < size);
5755 assert((i - offset) >= 0);
5756 PyTuple_SET_ITEM(tuple, i - offset, k);
5757 }
5758 return tuple;
5759}
5760
5761static PyObject *
5762consts_dict_keys_inorder(PyObject *dict)
5763{
5764 PyObject *consts, *k, *v;
5765 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5766
5767 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5768 if (consts == NULL)
5769 return NULL;
5770 while (PyDict_Next(dict, &pos, &k, &v)) {
5771 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005772 /* The keys of the dictionary can be tuples wrapping a contant.
5773 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5774 * the object we want is always second. */
5775 if (PyTuple_CheckExact(k)) {
5776 k = PyTuple_GET_ITEM(k, 1);
5777 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005778 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005779 assert(i < size);
5780 assert(i >= 0);
5781 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005782 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005783 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005784}
5785
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005786static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005787compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005790 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005791 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005792 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005793 if (ste->ste_nested)
5794 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005795 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005796 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005797 if (!ste->ste_generator && ste->ste_coroutine)
5798 flags |= CO_COROUTINE;
5799 if (ste->ste_generator && ste->ste_coroutine)
5800 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005801 if (ste->ste_varargs)
5802 flags |= CO_VARARGS;
5803 if (ste->ste_varkeywords)
5804 flags |= CO_VARKEYWORDS;
5805 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 /* (Only) inherit compilerflags in PyCF_MASK */
5808 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005809
Pablo Galindo90235812020-03-15 04:29:22 +00005810 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005811 ste->ste_coroutine &&
5812 !ste->ste_generator) {
5813 flags |= CO_COROUTINE;
5814 }
5815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005817}
5818
INADA Naokic2e16072018-11-26 21:23:22 +09005819// Merge *tuple* with constant cache.
5820// Unlike merge_consts_recursive(), this function doesn't work recursively.
5821static int
5822merge_const_tuple(struct compiler *c, PyObject **tuple)
5823{
5824 assert(PyTuple_CheckExact(*tuple));
5825
5826 PyObject *key = _PyCode_ConstantKey(*tuple);
5827 if (key == NULL) {
5828 return 0;
5829 }
5830
5831 // t is borrowed reference
5832 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5833 Py_DECREF(key);
5834 if (t == NULL) {
5835 return 0;
5836 }
5837 if (t == key) { // tuple is new constant.
5838 return 1;
5839 }
5840
5841 PyObject *u = PyTuple_GET_ITEM(t, 1);
5842 Py_INCREF(u);
5843 Py_DECREF(*tuple);
5844 *tuple = u;
5845 return 1;
5846}
5847
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005848static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005849makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005851 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005852 PyObject *names = NULL;
5853 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005854 PyObject *name = NULL;
5855 PyObject *freevars = NULL;
5856 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005857 Py_ssize_t nlocals;
5858 int nlocals_int;
5859 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005860 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005862 names = dict_keys_inorder(c->u->u_names, 0);
5863 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005864 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005865 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005866 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005867 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5868 if (!cellvars)
5869 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005870 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005871 if (!freevars)
5872 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005873
INADA Naokic2e16072018-11-26 21:23:22 +09005874 if (!merge_const_tuple(c, &names) ||
5875 !merge_const_tuple(c, &varnames) ||
5876 !merge_const_tuple(c, &cellvars) ||
5877 !merge_const_tuple(c, &freevars))
5878 {
5879 goto error;
5880 }
5881
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005882 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005883 assert(nlocals < INT_MAX);
5884 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005886 flags = compute_code_flags(c);
5887 if (flags < 0)
5888 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005889
Mark Shannon6e8128f2020-07-30 10:03:00 +01005890 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5891 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005892 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005893 }
INADA Naokic2e16072018-11-26 21:23:22 +09005894 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005895 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005896 goto error;
5897 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005898
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005899 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005900 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005901 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005902 maxdepth = stackdepth(c);
5903 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005904 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005905 goto error;
5906 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005907 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005908 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005909 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005910 varnames, freevars, cellvars, c->c_filename,
5911 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005912 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005913 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005914 Py_XDECREF(names);
5915 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005916 Py_XDECREF(name);
5917 Py_XDECREF(freevars);
5918 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005919 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005920}
5921
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005922
5923/* For debugging purposes only */
5924#if 0
5925static void
5926dump_instr(const struct instr *i)
5927{
Mark Shannon582aaf12020-08-04 17:30:11 +01005928 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5929 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005930 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005932 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005933 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005934 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005935 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5937 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005938}
5939
5940static void
5941dump_basicblock(const basicblock *b)
5942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005943 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005944 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5945 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005946 if (b->b_instr) {
5947 int i;
5948 for (i = 0; i < b->b_iused; i++) {
5949 fprintf(stderr, " [%02d] ", i);
5950 dump_instr(b->b_instr + i);
5951 }
5952 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005953}
5954#endif
5955
Mark Shannon5977a792020-12-02 13:31:40 +00005956
5957static int
5958normalize_basic_block(basicblock *bb);
5959
Mark Shannon6e8128f2020-07-30 10:03:00 +01005960static int
5961optimize_cfg(struct assembler *a, PyObject *consts);
5962
Mark Shannon5977a792020-12-02 13:31:40 +00005963static int
5964ensure_exits_have_lineno(struct compiler *c);
5965
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005966static PyCodeObject *
5967assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 basicblock *b, *entryblock;
5970 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005971 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005972 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005973 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005975 /* Make sure every block that falls off the end returns None.
5976 XXX NEXT_BLOCK() isn't quite right, because if the last
5977 block ends with a jump or return b_next shouldn't set.
5978 */
5979 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005980 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005981 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005982 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005983 ADDOP(c, RETURN_VALUE);
5984 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005985
Mark Shannon5977a792020-12-02 13:31:40 +00005986 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
5987 if (normalize_basic_block(b)) {
5988 goto error;
5989 }
5990 }
5991
5992 if (ensure_exits_have_lineno(c)) {
5993 goto error;
5994 }
5995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005996 nblocks = 0;
5997 entryblock = NULL;
5998 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5999 nblocks++;
6000 entryblock = b;
6001 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006003 /* Set firstlineno if it wasn't explicitly set. */
6004 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04006005 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006006 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00006007 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006008 c->u->u_firstlineno = 1;
6009 }
Mark Shannon5977a792020-12-02 13:31:40 +00006010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006011 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
6012 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006013 a.a_entry = entryblock;
6014 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006015
Mark Shannon6e8128f2020-07-30 10:03:00 +01006016 consts = consts_dict_keys_inorder(c->u->u_consts);
6017 if (consts == NULL) {
6018 goto error;
6019 }
6020 if (optimize_cfg(&a, consts)) {
6021 goto error;
6022 }
6023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006024 /* Can't modify the bytecode after computing jump offsets. */
6025 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006026
Mark Shannoncc75ab72020-11-12 19:49:33 +00006027 /* Emit code. */
6028 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006029 for (j = 0; j < b->b_iused; j++)
6030 if (!assemble_emit(&a, &b->b_instr[j]))
6031 goto error;
6032 }
Mark Shannon877df852020-11-12 09:43:29 +00006033 if (!assemble_line_range(&a)) {
6034 return 0;
6035 }
6036 /* Emit sentinel at end of line number table */
6037 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
6038 goto error;
6039 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006041 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6042 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006043 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006044 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006045
Mark Shannon6e8128f2020-07-30 10:03:00 +01006046 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006047 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006048 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006049 assemble_free(&a);
6050 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006051}
Georg Brandl8334fd92010-12-04 10:26:46 +00006052
6053#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006054PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006055PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6056 PyArena *arena)
6057{
6058 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6059}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006060
6061
6062/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6063 with LOAD_CONST (c1, c2, ... cn).
6064 The consts table must still be in list form so that the
6065 new constant (c1, c2, ... cn) can be appended.
6066 Called with codestr pointing to the first LOAD_CONST.
6067*/
6068static int
6069fold_tuple_on_constants(struct instr *inst,
6070 int n, PyObject *consts)
6071{
6072 /* Pre-conditions */
6073 assert(PyList_CheckExact(consts));
6074 assert(inst[n].i_opcode == BUILD_TUPLE);
6075 assert(inst[n].i_oparg == n);
6076
6077 for (int i = 0; i < n; i++) {
6078 if (inst[i].i_opcode != LOAD_CONST) {
6079 return 0;
6080 }
6081 }
6082
6083 /* Buildup new tuple of constants */
6084 PyObject *newconst = PyTuple_New(n);
6085 if (newconst == NULL) {
6086 return -1;
6087 }
6088 for (int i = 0; i < n; i++) {
6089 int arg = inst[i].i_oparg;
6090 PyObject *constant = PyList_GET_ITEM(consts, arg);
6091 Py_INCREF(constant);
6092 PyTuple_SET_ITEM(newconst, i, constant);
6093 }
6094 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006095 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006096 Py_DECREF(newconst);
6097 PyErr_SetString(PyExc_OverflowError, "too many constants");
6098 return -1;
6099 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006100 if (PyList_Append(consts, newconst)) {
6101 Py_DECREF(newconst);
6102 return -1;
6103 }
6104 Py_DECREF(newconst);
6105 for (int i = 0; i < n; i++) {
6106 inst[i].i_opcode = NOP;
6107 }
6108 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006109 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006110 return 0;
6111}
6112
Mark Shannoncc75ab72020-11-12 19:49:33 +00006113/* Maximum size of basic block that should be copied in optimizer */
6114#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006115
6116/* Optimization */
6117static int
6118optimize_basic_block(basicblock *bb, PyObject *consts)
6119{
6120 assert(PyList_CheckExact(consts));
6121 struct instr nop;
6122 nop.i_opcode = NOP;
6123 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006124 for (int i = 0; i < bb->b_iused; i++) {
6125 struct instr *inst = &bb->b_instr[i];
6126 int oparg = inst->i_oparg;
6127 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006128 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006129 /* Skip over empty basic blocks. */
6130 while (inst->i_target->b_iused == 0) {
6131 inst->i_target = inst->i_target->b_next;
6132 }
6133 target = &inst->i_target->b_instr[0];
6134 }
6135 else {
6136 target = &nop;
6137 }
6138 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006139 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006140 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006141 {
6142 PyObject* cnt;
6143 int is_true;
6144 int jump_if_true;
6145 switch(nextop) {
6146 case POP_JUMP_IF_FALSE:
6147 case POP_JUMP_IF_TRUE:
6148 cnt = PyList_GET_ITEM(consts, oparg);
6149 is_true = PyObject_IsTrue(cnt);
6150 if (is_true == -1) {
6151 goto error;
6152 }
6153 inst->i_opcode = NOP;
6154 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6155 if (is_true == jump_if_true) {
6156 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6157 bb->b_nofallthrough = 1;
6158 }
6159 else {
6160 bb->b_instr[i+1].i_opcode = NOP;
6161 }
6162 break;
6163 case JUMP_IF_FALSE_OR_POP:
6164 case JUMP_IF_TRUE_OR_POP:
6165 cnt = PyList_GET_ITEM(consts, oparg);
6166 is_true = PyObject_IsTrue(cnt);
6167 if (is_true == -1) {
6168 goto error;
6169 }
6170 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6171 if (is_true == jump_if_true) {
6172 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6173 bb->b_nofallthrough = 1;
6174 }
6175 else {
6176 inst->i_opcode = NOP;
6177 bb->b_instr[i+1].i_opcode = NOP;
6178 }
6179 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006180 }
6181 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006182 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006183
6184 /* Try to fold tuples of constants.
6185 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6186 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6187 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6188 case BUILD_TUPLE:
6189 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6190 switch(oparg) {
6191 case 1:
6192 inst->i_opcode = NOP;
6193 bb->b_instr[i+1].i_opcode = NOP;
6194 break;
6195 case 2:
6196 inst->i_opcode = ROT_TWO;
6197 bb->b_instr[i+1].i_opcode = NOP;
6198 break;
6199 case 3:
6200 inst->i_opcode = ROT_THREE;
6201 bb->b_instr[i+1].i_opcode = ROT_TWO;
6202 }
6203 break;
6204 }
6205 if (i >= oparg) {
6206 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6207 goto error;
6208 }
6209 }
6210 break;
6211
6212 /* Simplify conditional jump to conditional jump where the
6213 result of the first test implies the success of a similar
6214 test or the failure of the opposite test.
6215 Arises in code like:
6216 "a and b or c"
6217 "(a and b) and c"
6218 "(a or b) or c"
6219 "(a or b) and c"
6220 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6221 --> x:JUMP_IF_FALSE_OR_POP z
6222 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6223 --> x:POP_JUMP_IF_FALSE y+1
6224 where y+1 is the instruction following the second test.
6225 */
6226 case JUMP_IF_FALSE_OR_POP:
6227 switch(target->i_opcode) {
6228 case POP_JUMP_IF_FALSE:
6229 *inst = *target;
Mark Shannon266b4622020-11-17 19:30:14 +00006230 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006231 break;
6232 case JUMP_ABSOLUTE:
6233 case JUMP_FORWARD:
6234 case JUMP_IF_FALSE_OR_POP:
Mark Shannon266b4622020-11-17 19:30:14 +00006235 if (inst->i_target != target->i_target) {
6236 inst->i_target = target->i_target;
6237 --i;
6238 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006239 break;
6240 case JUMP_IF_TRUE_OR_POP:
6241 assert (inst->i_target->b_iused == 1);
6242 inst->i_opcode = POP_JUMP_IF_FALSE;
6243 inst->i_target = inst->i_target->b_next;
Mark Shannon266b4622020-11-17 19:30:14 +00006244 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006245 break;
6246 }
6247 break;
6248
6249 case JUMP_IF_TRUE_OR_POP:
6250 switch(target->i_opcode) {
6251 case POP_JUMP_IF_TRUE:
6252 *inst = *target;
Mark Shannon266b4622020-11-17 19:30:14 +00006253 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006254 break;
6255 case JUMP_ABSOLUTE:
6256 case JUMP_FORWARD:
6257 case JUMP_IF_TRUE_OR_POP:
Mark Shannon266b4622020-11-17 19:30:14 +00006258 if (inst->i_target != target->i_target) {
6259 inst->i_target = target->i_target;
6260 --i;
6261 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006262 break;
6263 case JUMP_IF_FALSE_OR_POP:
6264 assert (inst->i_target->b_iused == 1);
6265 inst->i_opcode = POP_JUMP_IF_TRUE;
6266 inst->i_target = inst->i_target->b_next;
Mark Shannon266b4622020-11-17 19:30:14 +00006267 --i;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006268 break;
6269 }
6270 break;
6271
6272 case POP_JUMP_IF_FALSE:
6273 switch(target->i_opcode) {
6274 case JUMP_ABSOLUTE:
6275 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006276 if (inst->i_target != target->i_target) {
6277 inst->i_target = target->i_target;
6278 --i;
6279 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006280 break;
6281 }
6282 break;
6283
6284 case POP_JUMP_IF_TRUE:
6285 switch(target->i_opcode) {
6286 case JUMP_ABSOLUTE:
6287 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006288 if (inst->i_target != target->i_target) {
6289 inst->i_target = target->i_target;
6290 --i;
6291 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006292 break;
6293 }
6294 break;
6295
6296 case JUMP_ABSOLUTE:
6297 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006298 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006299 switch(target->i_opcode) {
6300 case JUMP_FORWARD:
Mark Shannon266b4622020-11-17 19:30:14 +00006301 if (inst->i_target != target->i_target) {
6302 inst->i_target = target->i_target;
6303 --i;
6304 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006305 break;
6306 case JUMP_ABSOLUTE:
Mark Shannon266b4622020-11-17 19:30:14 +00006307 if (inst->i_target != target->i_target) {
6308 inst->i_target = target->i_target;
6309 inst->i_opcode = target->i_opcode;
6310 --i;
6311 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006312 break;
6313 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006314 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6315 basicblock *to_copy = inst->i_target;
6316 *inst = to_copy->b_instr[0];
6317 for (i = 1; i < to_copy->b_iused; i++) {
6318 int index = compiler_next_instr(bb);
6319 if (index < 0) {
6320 return -1;
6321 }
6322 bb->b_instr[index] = to_copy->b_instr[i];
6323 }
6324 bb->b_exit = 1;
6325 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006326 break;
6327 }
6328 }
6329 return 0;
6330error:
6331 return -1;
6332}
6333
6334
6335static void
6336clean_basic_block(basicblock *bb) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006337 /* Remove NOPs. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006338 int dest = 0;
Mark Shannon877df852020-11-12 09:43:29 +00006339 int prev_lineno = -1;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006340 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006341 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006342 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006343 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006344 if (lineno < 0) {
6345 continue;
6346 }
Mark Shannon266b4622020-11-17 19:30:14 +00006347 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006348 if (prev_lineno == lineno) {
6349 continue;
6350 }
Mark Shannon266b4622020-11-17 19:30:14 +00006351 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006352 if (src < bb->b_iused - 1) {
6353 int next_lineno = bb->b_instr[src+1].i_lineno;
6354 if (next_lineno < 0 || next_lineno == lineno) {
6355 bb->b_instr[src+1].i_lineno = lineno;
6356 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006357 }
6358 }
Mark Shannon266b4622020-11-17 19:30:14 +00006359 else {
6360 basicblock* next = bb->b_next;
6361 while (next && next->b_iused == 0) {
6362 next = next->b_next;
6363 }
6364 /* or if last instruction in BB and next BB has same line number */
6365 if (next) {
6366 if (lineno == next->b_instr[0].i_lineno) {
6367 continue;
6368 }
6369 }
6370 }
6371
Mark Shannon6e8128f2020-07-30 10:03:00 +01006372 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006373 if (dest != src) {
6374 bb->b_instr[dest] = bb->b_instr[src];
6375 }
6376 dest++;
6377 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006378 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006379 assert(dest <= bb->b_iused);
6380 bb->b_iused = dest;
6381}
6382
Mark Shannon266b4622020-11-17 19:30:14 +00006383static int
6384normalize_basic_block(basicblock *bb) {
6385 /* Mark blocks as exit and/or nofallthrough.
6386 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006387 for (int i = 0; i < bb->b_iused; i++) {
6388 switch(bb->b_instr[i].i_opcode) {
6389 case RETURN_VALUE:
6390 case RAISE_VARARGS:
6391 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006392 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00006393 bb->b_nofallthrough = 1;
6394 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006395 case JUMP_ABSOLUTE:
6396 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006397 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006398 /* fall through */
6399 case POP_JUMP_IF_FALSE:
6400 case POP_JUMP_IF_TRUE:
6401 case JUMP_IF_FALSE_OR_POP:
6402 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00006403 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00006404 if (i != bb->b_iused-1) {
6405 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6406 return -1;
6407 }
Mark Shannon5977a792020-12-02 13:31:40 +00006408 /* Skip over empty basic blocks. */
6409 while (bb->b_instr[i].i_target->b_iused == 0) {
6410 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
6411 }
6412
Mark Shannoncc75ab72020-11-12 19:49:33 +00006413 }
6414 }
Mark Shannon266b4622020-11-17 19:30:14 +00006415 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006416}
6417
Mark Shannon6e8128f2020-07-30 10:03:00 +01006418static int
6419mark_reachable(struct assembler *a) {
6420 basicblock **stack, **sp;
6421 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6422 if (stack == NULL) {
6423 return -1;
6424 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006425 a->a_entry->b_reachable = 1;
6426 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006427 while (sp > stack) {
6428 basicblock *b = *(--sp);
Mark Shannoncc75ab72020-11-12 19:49:33 +00006429 if (b->b_next && !b->b_nofallthrough && b->b_next->b_reachable == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006430 b->b_next->b_reachable = 1;
6431 *sp++ = b->b_next;
6432 }
6433 for (int i = 0; i < b->b_iused; i++) {
6434 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006435 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006436 target = b->b_instr[i].i_target;
6437 if (target->b_reachable == 0) {
6438 target->b_reachable = 1;
6439 *sp++ = target;
6440 }
6441 }
6442 }
6443 }
6444 PyObject_Free(stack);
6445 return 0;
6446}
6447
Mark Shannon5977a792020-12-02 13:31:40 +00006448/* If an instruction has no line number, but it's predecessor in the BB does,
6449 * then copy the line number. This reduces the size of the line number table,
6450 * but has no impact on the generated line number events.
6451 */
6452static void
6453minimize_lineno_table(struct assembler *a) {
6454 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6455 int prev_lineno = -1;
6456 for (int i = 0; i < b->b_iused; i++) {
6457 if (b->b_instr[i].i_lineno < 0) {
6458 b->b_instr[i].i_lineno = prev_lineno;
6459 }
6460 else {
6461 prev_lineno = b->b_instr[i].i_lineno;
6462 }
6463 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006464
Mark Shannon5977a792020-12-02 13:31:40 +00006465 }
6466}
6467
6468/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01006469 The consts object should still be in list form to allow new constants
6470 to be appended.
6471
6472 All transformations keep the code size the same or smaller.
6473 For those that reduce size, the gaps are initially filled with
6474 NOPs. Later those NOPs are removed.
6475*/
6476
6477static int
6478optimize_cfg(struct assembler *a, PyObject *consts)
6479{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006480 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006481 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006482 return -1;
6483 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006484 clean_basic_block(b);
6485 assert(b->b_reachable == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006486 }
6487 if (mark_reachable(a)) {
6488 return -1;
6489 }
6490 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006491 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6492 if (b->b_reachable == 0) {
6493 b->b_iused = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006494 }
6495 }
Mark Shannon5977a792020-12-02 13:31:40 +00006496 minimize_lineno_table(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006497 return 0;
6498}
6499
Mark Shannon5977a792020-12-02 13:31:40 +00006500static inline int
6501is_exit_without_lineno(basicblock *b) {
6502 return b->b_exit && b->b_instr[0].i_lineno < 0;
6503}
6504
6505/* PEP 626 mandates that the f_lineno of a frame is correct
6506 * after a frame terminates. It would be prohibitively expensive
6507 * to continuously update the f_lineno field at runtime,
6508 * so we make sure that all exiting instruction (raises and returns)
6509 * have a valid line number, allowing us to compute f_lineno lazily.
6510 * We can do this by duplicating the exit blocks without line number
6511 * so that none have more than one predecessor. We can then safely
6512 * copy the line number from the sole predecessor block.
6513 */
6514static int
6515ensure_exits_have_lineno(struct compiler *c)
6516{
Mark Shannoneaccc122020-12-04 15:22:12 +00006517 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006518 /* Copy all exit blocks without line number that are targets of a jump.
6519 */
6520 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6521 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
6522 switch (b->b_instr[b->b_iused-1].i_opcode) {
6523 /* Note: Only actual jumps, not exception handlers */
6524 case SETUP_ASYNC_WITH:
6525 case SETUP_WITH:
6526 case SETUP_FINALLY:
6527 continue;
6528 }
6529 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6530 if (is_exit_without_lineno(target)) {
6531 basicblock *new_target = compiler_copy_block(c, target);
6532 if (new_target == NULL) {
6533 return -1;
6534 }
6535 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6536 b->b_instr[b->b_iused-1].i_target = new_target;
6537 }
6538 }
Mark Shannoneaccc122020-12-04 15:22:12 +00006539 entry = b;
6540 }
6541 assert(entry != NULL);
6542 if (is_exit_without_lineno(entry)) {
6543 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00006544 }
6545 /* Any remaining reachable exit blocks without line number can only be reached by
6546 * fall through, and thus can only have a single predecessor */
6547 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6548 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
6549 if (is_exit_without_lineno(b->b_next)) {
6550 assert(b->b_next->b_iused > 0);
6551 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6552 }
6553 }
6554 }
6555 return 0;
6556}
6557
6558
Mark Shannon6e8128f2020-07-30 10:03:00 +01006559/* Retained for API compatibility.
6560 * Optimization is now done in optimize_cfg */
6561
6562PyObject *
6563PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6564 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6565{
6566 Py_INCREF(code);
6567 return code;
6568}
6569