blob: c2fcf096fbad4494a25a0e8be5e1caeafd7c4e30 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001/*
2 * This file compiles an abstract syntax tree (AST) into Python bytecode.
3 *
4 * The primary entry point is PyAST_Compile(), which returns a
5 * PyCodeObject. The compiler makes several passes to build the code
6 * object:
7 * 1. Checks for future statements. See future.c
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008 * 2. Builds a symbol table. See symtable.c.
Thomas Wouters89f507f2006-12-13 04:49:30 +00009 * 3. Generate code for basic blocks. See compiler_mod() in this file.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000010 * 4. Assemble the basic blocks into final code. See assemble() in
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000011 * this file.
Mark Shannon6e8128f2020-07-30 10:03:00 +010012 * 5. Optimize the byte code (peephole optimizations).
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013 *
14 * Note that compiler_mod() suggests module, but the module ast type
15 * (mod_ty) has cases for expressions and interactive statements.
Nick Coghlan944d3eb2005-11-16 12:46:55 +000016 *
Jeremy Hyltone9357b22006-03-01 15:47:05 +000017 * CAUTION: The VISIT_* macros abort the current function when they
18 * encounter a problem. So don't invoke them when there is memory
19 * which needs to be released. Code blocks are OK, as the compiler
Thomas Wouters89f507f2006-12-13 04:49:30 +000020 * structure takes care of releasing those. Use the arena to manage
21 * objects.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000022 */
Guido van Rossum10dc2e81990-11-18 17:27:39 +000023
Guido van Rossum79f25d91997-04-29 20:08:16 +000024#include "Python.h"
Victor Stinnerc9bc2902020-10-27 02:24:34 +010025#include "pycore_long.h" // _PyLong_GetZero()
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Ammar Askare92d3932020-01-15 11:48:40 -050027#include "Python-ast.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000028#include "ast.h"
29#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000030#include "symtable.h"
Mark Shannon582aaf12020-08-04 17:30:11 +010031#define NEED_OPCODE_JUMP_TABLES
Guido van Rossum10dc2e81990-11-18 17:27:39 +000032#include "opcode.h"
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030033#include "wordcode_helpers.h"
Guido van Rossumb05a5c71997-05-07 17:46:13 +000034
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000035#define DEFAULT_BLOCK_SIZE 16
36#define DEFAULT_BLOCKS 8
37#define DEFAULT_CODE_SIZE 128
38#define DEFAULT_LNOTAB_SIZE 16
Jeremy Hylton29906ee2001-02-27 04:23:34 +000039
Nick Coghlan650f0d02007-04-15 12:05:43 +000040#define COMP_GENEXP 0
41#define COMP_LISTCOMP 1
42#define COMP_SETCOMP 2
Guido van Rossum992d4a32007-07-11 13:09:30 +000043#define COMP_DICTCOMP 3
Nick Coghlan650f0d02007-04-15 12:05:43 +000044
Pablo Galindo90235812020-03-15 04:29:22 +000045#define IS_TOP_LEVEL_AWAIT(c) ( \
46 (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \
47 && (c->u->u_ste->ste_type == ModuleBlock))
48
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000049struct instr {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 unsigned char i_opcode;
51 int i_oparg;
52 struct basicblock_ *i_target; /* target block (if jump instruction) */
53 int i_lineno;
Guido van Rossum3f5da241990-12-20 15:06:42 +000054};
55
Mark Shannon582aaf12020-08-04 17:30:11 +010056#define LOG_BITS_PER_INT 5
57#define MASK_LOW_LOG_BITS 31
58
59static inline int
60is_bit_set_in_table(uint32_t *table, int bitindex) {
61 /* Is the relevant bit set in the relevant word? */
62 /* 256 bits fit into 8 32-bits words.
63 * Word is indexed by (bitindex>>ln(size of int in bits)).
64 * Bit within word is the low bits of bitindex.
65 */
66 uint32_t word = table[bitindex >> LOG_BITS_PER_INT];
67 return (word >> (bitindex & MASK_LOW_LOG_BITS)) & 1;
68}
69
70static inline int
71is_relative_jump(struct instr *i)
72{
73 return is_bit_set_in_table(_PyOpcode_RelativeJump, i->i_opcode);
74}
75
76static inline int
77is_jump(struct instr *i)
78{
79 return is_bit_set_in_table(_PyOpcode_Jump, i->i_opcode);
80}
81
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000082typedef struct basicblock_ {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000083 /* Each basicblock in a compilation unit is linked via b_list in the
84 reverse order that the block are allocated. b_list points to the next
85 block, not to be confused with b_next, which is next by control flow. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 struct basicblock_ *b_list;
87 /* number of instructions used */
88 int b_iused;
89 /* length of instruction array (b_instr) */
90 int b_ialloc;
91 /* pointer to an array of instructions, initially NULL */
92 struct instr *b_instr;
93 /* If b_next is non-NULL, it is a pointer to the next
94 block reached by normal control flow. */
95 struct basicblock_ *b_next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 /* b_return is true if a RETURN_VALUE opcode is inserted. */
97 unsigned b_return : 1;
Mark Shannon6e8128f2020-07-30 10:03:00 +010098 unsigned b_reachable : 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +000099 /* Basic block has no fall through (it ends with a return, raise or jump) */
100 unsigned b_nofallthrough : 1;
101 /* Basic block exits scope (it ends with a return or raise) */
102 unsigned b_exit : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 /* depth of stack upon entry of block, computed by stackdepth() */
104 int b_startdepth;
105 /* instruction offset for block, computed by assemble_jump_offsets() */
106 int b_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000107} basicblock;
108
109/* fblockinfo tracks the current frame block.
110
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000111A frame block is used to handle loops, try/except, and try/finally.
112It's called a frame block to distinguish it from a basic block in the
113compiler IR.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114*/
115
Mark Shannon02d126a2020-09-25 14:04:19 +0100116enum fblocktype { WHILE_LOOP, FOR_LOOP, TRY_EXCEPT, FINALLY_TRY, FINALLY_END,
117 WITH, ASYNC_WITH, HANDLER_CLEANUP, POP_VALUE, EXCEPTION_HANDLER };
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000118
119struct fblockinfo {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 enum fblocktype fb_type;
121 basicblock *fb_block;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200122 /* (optional) type-specific exit or cleanup block */
123 basicblock *fb_exit;
Mark Shannonfee55262019-11-21 09:11:43 +0000124 /* (optional) additional information required for unwinding */
125 void *fb_datum;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000126};
127
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100128enum {
129 COMPILER_SCOPE_MODULE,
130 COMPILER_SCOPE_CLASS,
131 COMPILER_SCOPE_FUNCTION,
Yury Selivanov75445082015-05-11 22:57:16 -0400132 COMPILER_SCOPE_ASYNC_FUNCTION,
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400133 COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100134 COMPILER_SCOPE_COMPREHENSION,
135};
136
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000137/* The following items change on entry and exit of code blocks.
138 They must be saved and restored when returning to a block.
139*/
140struct compiler_unit {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 PySTEntryObject *u_ste;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 PyObject *u_name;
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400144 PyObject *u_qualname; /* dot-separated qualified name (lazy) */
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100145 int u_scope_type;
146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 /* The following fields are dicts that map objects to
148 the index of them in co_XXX. The index is used as
149 the argument for opcodes that refer to those collections.
150 */
151 PyObject *u_consts; /* all constants */
152 PyObject *u_names; /* all names */
153 PyObject *u_varnames; /* local variables */
154 PyObject *u_cellvars; /* cell variables */
155 PyObject *u_freevars; /* free variables */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 PyObject *u_private; /* for private name mangling */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000158
Victor Stinnerf8e32212013-11-19 23:56:34 +0100159 Py_ssize_t u_argcount; /* number of arguments for block */
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100160 Py_ssize_t u_posonlyargcount; /* number of positional only arguments for block */
Victor Stinnerf8e32212013-11-19 23:56:34 +0100161 Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 /* Pointer to the most recently allocated block. By following b_list
163 members, you can reach all early allocated blocks. */
164 basicblock *u_blocks;
165 basicblock *u_curblock; /* pointer to current block */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 int u_nfblocks;
168 struct fblockinfo u_fblock[CO_MAXBLOCKS];
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 int u_firstlineno; /* the first lineno of the block */
171 int u_lineno; /* the lineno for the current stmt */
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000172 int u_col_offset; /* the offset of the current stmt */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000173};
174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175/* This struct captures the global state of a compilation.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000177The u pointer points to the current compilation unit, while units
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178for enclosing blocks are stored in c_stack. The u and c_stack are
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000179managed by compiler_enter_scope() and compiler_exit_scope().
Nick Coghlanaab9c2b2012-11-04 23:14:34 +1000180
181Note that we don't track recursion levels during compilation - the
182task of detecting and rejecting excessive levels of nesting is
183handled by the symbol analysis pass.
184
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000185*/
186
187struct compiler {
Victor Stinner14e461d2013-08-26 22:28:21 +0200188 PyObject *c_filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 struct symtable *c_st;
190 PyFutureFeatures *c_future; /* pointer to module's __future__ */
191 PyCompilerFlags *c_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000192
Georg Brandl8334fd92010-12-04 10:26:46 +0000193 int c_optimize; /* optimization level */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 int c_interactive; /* true if in interactive mode */
195 int c_nestlevel;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100196 int c_do_not_emit_bytecode; /* The compiler won't emit any bytecode
197 if this value is different from zero.
198 This can be used to temporarily visit
199 nodes without emitting bytecode to
200 check only errors. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201
INADA Naokic2e16072018-11-26 21:23:22 +0900202 PyObject *c_const_cache; /* Python dict holding all constants,
203 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 struct compiler_unit *u; /* compiler state for current block */
205 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
206 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207};
208
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100209static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000210static void compiler_free(struct compiler *);
211static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500212static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100214static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100215static int compiler_addop_j(struct compiler *, int, basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200217static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000218static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
219
220static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
221static int compiler_visit_stmt(struct compiler *, stmt_ty);
222static int compiler_visit_keyword(struct compiler *, keyword_ty);
223static int compiler_visit_expr(struct compiler *, expr_ty);
224static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700225static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200226static int compiler_subscript(struct compiler *, expr_ty);
227static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000228
Andy Lester76d58772020-03-10 21:18:12 -0500229static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100230static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +0200231static int expr_constant(expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000232
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500233static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400234static int compiler_async_with(struct compiler *, stmt_ty, int);
235static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100236static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100237 asdl_expr_seq *args,
238 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500239static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400240static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000241
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700242static int compiler_sync_comprehension_generator(
243 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100244 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200245 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700246 expr_ty elt, expr_ty val, int type);
247
248static int compiler_async_comprehension_generator(
249 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100250 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200251 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700252 expr_ty elt, expr_ty val, int type);
253
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000255static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400257#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000259PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000260_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* Name mangling: __private becomes _classname__private.
263 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200264 PyObject *result;
265 size_t nlen, plen, ipriv;
266 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200268 PyUnicode_READ_CHAR(ident, 0) != '_' ||
269 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 Py_INCREF(ident);
271 return ident;
272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200273 nlen = PyUnicode_GET_LENGTH(ident);
274 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 The only time a name with a dot can occur is when
278 we are compiling an import statement that has a
279 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 TODO(jhylton): Decide whether we want to support
282 mangling of the module name, e.g. __M.X.
283 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200284 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
285 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
286 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Py_INCREF(ident);
288 return ident; /* Don't mangle __whatever__ */
289 }
290 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200291 ipriv = 0;
292 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
293 ipriv++;
294 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_INCREF(ident);
296 return ident; /* Don't mangle if class is just underscores */
297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200298 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000299
Antoine Pitrou55bff892013-04-06 21:21:04 +0200300 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
301 PyErr_SetString(PyExc_OverflowError,
302 "private identifier too large to be mangled");
303 return NULL;
304 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000305
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200306 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
307 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
308 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
309
310 result = PyUnicode_New(1 + nlen + plen, maxchar);
311 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200313 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
314 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200315 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
316 Py_DECREF(result);
317 return NULL;
318 }
319 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
320 Py_DECREF(result);
321 return NULL;
322 }
Victor Stinner8f825062012-04-27 13:55:39 +0200323 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200324 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000325}
326
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000327static int
328compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000331
INADA Naokic2e16072018-11-26 21:23:22 +0900332 c->c_const_cache = PyDict_New();
333 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900335 }
336
337 c->c_stack = PyList_New(0);
338 if (!c->c_stack) {
339 Py_CLEAR(c->c_const_cache);
340 return 0;
341 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344}
345
346PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200347PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
348 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 struct compiler c;
351 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200352 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (!__doc__) {
356 __doc__ = PyUnicode_InternFromString("__doc__");
357 if (!__doc__)
358 return NULL;
359 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000360 if (!__annotations__) {
361 __annotations__ = PyUnicode_InternFromString("__annotations__");
362 if (!__annotations__)
363 return NULL;
364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (!compiler_init(&c))
366 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200367 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 c.c_filename = filename;
369 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200370 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (c.c_future == NULL)
372 goto finally;
373 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 flags = &local_flags;
375 }
376 merged = c.c_future->ff_features | flags->cf_flags;
377 c.c_future->ff_features = merged;
378 flags->cf_flags = merged;
379 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200380 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 c.c_nestlevel = 0;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +0100382 c.c_do_not_emit_bytecode = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000383
Pablo Galindod112c602020-03-18 23:02:09 +0000384 _PyASTOptimizeState state;
385 state.optimize = c.c_optimize;
386 state.ff_features = merged;
387
388 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900389 goto finally;
390 }
391
Victor Stinner14e461d2013-08-26 22:28:21 +0200392 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (c.c_st == NULL) {
394 if (!PyErr_Occurred())
395 PyErr_SetString(PyExc_SystemError, "no symtable");
396 goto finally;
397 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400
Thomas Wouters1175c432006-02-27 22:49:54 +0000401 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 compiler_free(&c);
403 assert(co || PyErr_Occurred());
404 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000405}
406
407PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200408PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
409 int optimize, PyArena *arena)
410{
411 PyObject *filename;
412 PyCodeObject *co;
413 filename = PyUnicode_DecodeFSDefault(filename_str);
414 if (filename == NULL)
415 return NULL;
416 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
417 Py_DECREF(filename);
418 return co;
419
420}
421
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000422static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000423compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (c->c_st)
426 PySymtable_Free(c->c_st);
427 if (c->c_future)
428 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200429 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900430 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000432}
433
Guido van Rossum79f25d91997-04-29 20:08:16 +0000434static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000435list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 Py_ssize_t i, n;
438 PyObject *v, *k;
439 PyObject *dict = PyDict_New();
440 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 n = PyList_Size(list);
443 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100444 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (!v) {
446 Py_DECREF(dict);
447 return NULL;
448 }
449 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300450 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 Py_DECREF(v);
452 Py_DECREF(dict);
453 return NULL;
454 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_DECREF(v);
456 }
457 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000458}
459
460/* Return new dict containing names from src that match scope(s).
461
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000462src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000464values are integers, starting at offset and increasing by one for
465each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000466*/
467
468static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100469dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700471 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500473 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 assert(offset >= 0);
476 if (dest == NULL)
477 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000478
Meador Inge2ca63152012-07-18 14:20:11 -0500479 /* Sort the keys so that we have a deterministic order on the indexes
480 saved in the returned dictionary. These indexes are used as indexes
481 into the free and cell var storage. Therefore if they aren't
482 deterministic, then the generated bytecode is not deterministic.
483 */
484 sorted_keys = PyDict_Keys(src);
485 if (sorted_keys == NULL)
486 return NULL;
487 if (PyList_Sort(sorted_keys) != 0) {
488 Py_DECREF(sorted_keys);
489 return NULL;
490 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500491 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500492
493 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* XXX this should probably be a macro in symtable.h */
495 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500496 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200497 v = PyDict_GetItemWithError(src, k);
498 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 vi = PyLong_AS_LONG(v);
500 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300503 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500505 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_DECREF(dest);
507 return NULL;
508 }
509 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300510 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500511 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 Py_DECREF(item);
513 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return NULL;
515 }
516 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 }
518 }
Meador Inge2ca63152012-07-18 14:20:11 -0500519 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000521}
522
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000523static void
524compiler_unit_check(struct compiler_unit *u)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 basicblock *block;
527 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700528 assert((uintptr_t)block != 0xcbcbcbcbU);
529 assert((uintptr_t)block != 0xfbfbfbfbU);
530 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (block->b_instr != NULL) {
532 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100533 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 assert(block->b_ialloc >= block->b_iused);
535 }
536 else {
537 assert (block->b_iused == 0);
538 assert (block->b_ialloc == 0);
539 }
540 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541}
542
543static void
544compiler_unit_free(struct compiler_unit *u)
545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 compiler_unit_check(u);
549 b = u->u_blocks;
550 while (b != NULL) {
551 if (b->b_instr)
552 PyObject_Free((void *)b->b_instr);
553 next = b->b_list;
554 PyObject_Free((void *)b);
555 b = next;
556 }
557 Py_CLEAR(u->u_ste);
558 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400559 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 Py_CLEAR(u->u_consts);
561 Py_CLEAR(u->u_names);
562 Py_CLEAR(u->u_varnames);
563 Py_CLEAR(u->u_freevars);
564 Py_CLEAR(u->u_cellvars);
565 Py_CLEAR(u->u_private);
566 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567}
568
569static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100570compiler_enter_scope(struct compiler *c, identifier name,
571 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100574 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575
Andy Lester7668a8b2020-03-24 23:26:44 -0500576 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 struct compiler_unit));
578 if (!u) {
579 PyErr_NoMemory();
580 return 0;
581 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100582 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100584 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 u->u_kwonlyargcount = 0;
586 u->u_ste = PySymtable_Lookup(c->c_st, key);
587 if (!u->u_ste) {
588 compiler_unit_free(u);
589 return 0;
590 }
591 Py_INCREF(name);
592 u->u_name = name;
593 u->u_varnames = list2dict(u->u_ste->ste_varnames);
594 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
595 if (!u->u_varnames || !u->u_cellvars) {
596 compiler_unit_free(u);
597 return 0;
598 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500599 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000600 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500601 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300602 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500603 int res;
604 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200605 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500606 name = _PyUnicode_FromId(&PyId___class__);
607 if (!name) {
608 compiler_unit_free(u);
609 return 0;
610 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100611 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500612 if (res < 0) {
613 compiler_unit_free(u);
614 return 0;
615 }
616 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200619 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (!u->u_freevars) {
621 compiler_unit_free(u);
622 return 0;
623 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 u->u_blocks = NULL;
626 u->u_nfblocks = 0;
627 u->u_firstlineno = lineno;
628 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000629 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 u->u_consts = PyDict_New();
631 if (!u->u_consts) {
632 compiler_unit_free(u);
633 return 0;
634 }
635 u->u_names = PyDict_New();
636 if (!u->u_names) {
637 compiler_unit_free(u);
638 return 0;
639 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 /* Push the old compiler_unit on the stack. */
644 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400645 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
647 Py_XDECREF(capsule);
648 compiler_unit_free(u);
649 return 0;
650 }
651 Py_DECREF(capsule);
652 u->u_private = c->u->u_private;
653 Py_XINCREF(u->u_private);
654 }
655 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100658
659 block = compiler_new_block(c);
660 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100662 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000663
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400664 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
665 if (!compiler_set_qualname(c))
666 return 0;
667 }
668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000670}
671
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000672static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000673compiler_exit_scope(struct compiler *c)
674{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100675 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 c->c_nestlevel--;
679 compiler_unit_free(c->u);
680 /* Restore c->u to the parent unit. */
681 n = PyList_GET_SIZE(c->c_stack) - 1;
682 if (n >= 0) {
683 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400684 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 assert(c->u);
686 /* we are deleting from a list so this really shouldn't fail */
687 if (PySequence_DelItem(c->c_stack, n) < 0)
688 Py_FatalError("compiler_exit_scope()");
689 compiler_unit_check(c->u);
690 }
691 else
692 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000693
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000694}
695
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400696static int
697compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100699 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400700 _Py_static_string(dot_locals, ".<locals>");
701 Py_ssize_t stack_size;
702 struct compiler_unit *u = c->u;
703 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100704
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400705 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100706 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400707 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400708 if (stack_size > 1) {
709 int scope, force_global = 0;
710 struct compiler_unit *parent;
711 PyObject *mangled, *capsule;
712
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400713 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400714 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400715 assert(parent);
716
Yury Selivanov75445082015-05-11 22:57:16 -0400717 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
718 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
719 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400720 assert(u->u_name);
721 mangled = _Py_Mangle(parent->u_private, u->u_name);
722 if (!mangled)
723 return 0;
724 scope = PyST_GetScope(parent->u_ste, mangled);
725 Py_DECREF(mangled);
726 assert(scope != GLOBAL_IMPLICIT);
727 if (scope == GLOBAL_EXPLICIT)
728 force_global = 1;
729 }
730
731 if (!force_global) {
732 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400733 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400734 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
735 dot_locals_str = _PyUnicode_FromId(&dot_locals);
736 if (dot_locals_str == NULL)
737 return 0;
738 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
739 if (base == NULL)
740 return 0;
741 }
742 else {
743 Py_INCREF(parent->u_qualname);
744 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400745 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100746 }
747 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400748
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400749 if (base != NULL) {
750 dot_str = _PyUnicode_FromId(&dot);
751 if (dot_str == NULL) {
752 Py_DECREF(base);
753 return 0;
754 }
755 name = PyUnicode_Concat(base, dot_str);
756 Py_DECREF(base);
757 if (name == NULL)
758 return 0;
759 PyUnicode_Append(&name, u->u_name);
760 if (name == NULL)
761 return 0;
762 }
763 else {
764 Py_INCREF(u->u_name);
765 name = u->u_name;
766 }
767 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100768
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400769 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100770}
771
Eric V. Smith235a6f02015-09-19 14:51:32 -0400772
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000773/* Allocate a new block and return a pointer to it.
774 Returns NULL on error.
775*/
776
777static basicblock *
778compiler_new_block(struct compiler *c)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 basicblock *b;
781 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500784 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 if (b == NULL) {
786 PyErr_NoMemory();
787 return NULL;
788 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 /* Extend the singly linked list of blocks with new block. */
790 b->b_list = u->u_blocks;
791 u->u_blocks = b;
792 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793}
794
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000796compiler_next_block(struct compiler *c)
797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 basicblock *block = compiler_new_block(c);
799 if (block == NULL)
800 return NULL;
801 c->u->u_curblock->b_next = block;
802 c->u->u_curblock = block;
803 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000804}
805
806static basicblock *
807compiler_use_next_block(struct compiler *c, basicblock *block)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 assert(block != NULL);
810 c->u->u_curblock->b_next = block;
811 c->u->u_curblock = block;
812 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813}
814
815/* Returns the offset of the next instruction in the current block's
816 b_instr array. Resizes the b_instr as necessary.
817 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000818*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819
820static int
Andy Lester76d58772020-03-10 21:18:12 -0500821compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 assert(b != NULL);
824 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500825 b->b_instr = (struct instr *)PyObject_Calloc(
826 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 if (b->b_instr == NULL) {
828 PyErr_NoMemory();
829 return -1;
830 }
831 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 }
833 else if (b->b_iused == b->b_ialloc) {
834 struct instr *tmp;
835 size_t oldsize, newsize;
836 oldsize = b->b_ialloc * sizeof(struct instr);
837 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000838
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700839 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyErr_NoMemory();
841 return -1;
842 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 if (newsize == 0) {
845 PyErr_NoMemory();
846 return -1;
847 }
848 b->b_ialloc <<= 1;
849 tmp = (struct instr *)PyObject_Realloc(
850 (void *)b->b_instr, newsize);
851 if (tmp == NULL) {
852 PyErr_NoMemory();
853 return -1;
854 }
855 b->b_instr = tmp;
856 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
857 }
858 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000859}
860
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200861/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000862
Christian Heimes2202f872008-02-06 14:31:34 +0000863 The line number is reset in the following cases:
864 - when entering a new scope
865 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200866 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200867 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000868*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000869
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200870#define SET_LOC(c, x) \
871 (c)->u->u_lineno = (x)->lineno; \
872 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000873
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200874/* Return the stack effect of opcode with argument oparg.
875
876 Some opcodes have different stack effect when jump to the target and
877 when not jump. The 'jump' parameter specifies the case:
878
879 * 0 -- when not jump
880 * 1 -- when jump
881 * -1 -- maximal
882 */
883/* XXX Make the stack effect of WITH_CLEANUP_START and
884 WITH_CLEANUP_FINISH deterministic. */
885static int
886stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300889 case NOP:
890 case EXTENDED_ARG:
891 return 0;
892
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200893 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 case POP_TOP:
895 return -1;
896 case ROT_TWO:
897 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200898 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return 0;
900 case DUP_TOP:
901 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000902 case DUP_TOP_TWO:
903 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000904
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200905 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 case UNARY_POSITIVE:
907 case UNARY_NEGATIVE:
908 case UNARY_NOT:
909 case UNARY_INVERT:
910 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 case SET_ADD:
913 case LIST_APPEND:
914 return -1;
915 case MAP_ADD:
916 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000917
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200918 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 case BINARY_POWER:
920 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400921 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case BINARY_MODULO:
923 case BINARY_ADD:
924 case BINARY_SUBTRACT:
925 case BINARY_SUBSCR:
926 case BINARY_FLOOR_DIVIDE:
927 case BINARY_TRUE_DIVIDE:
928 return -1;
929 case INPLACE_FLOOR_DIVIDE:
930 case INPLACE_TRUE_DIVIDE:
931 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 case INPLACE_ADD:
934 case INPLACE_SUBTRACT:
935 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400936 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 case INPLACE_MODULO:
938 return -1;
939 case STORE_SUBSCR:
940 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 case DELETE_SUBSCR:
942 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 case BINARY_LSHIFT:
945 case BINARY_RSHIFT:
946 case BINARY_AND:
947 case BINARY_XOR:
948 case BINARY_OR:
949 return -1;
950 case INPLACE_POWER:
951 return -1;
952 case GET_ITER:
953 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 case PRINT_EXPR:
956 return -1;
957 case LOAD_BUILD_CLASS:
958 return 1;
959 case INPLACE_LSHIFT:
960 case INPLACE_RSHIFT:
961 case INPLACE_AND:
962 case INPLACE_XOR:
963 case INPLACE_OR:
964 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200967 /* 1 in the normal flow.
968 * Restore the stack position and push 6 values before jumping to
969 * the handler if an exception be raised. */
970 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case RETURN_VALUE:
972 return -1;
973 case IMPORT_STAR:
974 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700975 case SETUP_ANNOTATIONS:
976 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 case YIELD_VALUE:
978 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500979 case YIELD_FROM:
980 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 case POP_BLOCK:
982 return 0;
983 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200984 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 case STORE_NAME:
987 return -1;
988 case DELETE_NAME:
989 return 0;
990 case UNPACK_SEQUENCE:
991 return oparg-1;
992 case UNPACK_EX:
993 return (oparg&0xFF) + (oparg>>8);
994 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200995 /* -1 at end of iterator, 1 if continue iterating. */
996 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 case STORE_ATTR:
999 return -2;
1000 case DELETE_ATTR:
1001 return -1;
1002 case STORE_GLOBAL:
1003 return -1;
1004 case DELETE_GLOBAL:
1005 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 case LOAD_CONST:
1007 return 1;
1008 case LOAD_NAME:
1009 return 1;
1010 case BUILD_TUPLE:
1011 case BUILD_LIST:
1012 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001013 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return 1-oparg;
1015 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001016 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001017 case BUILD_CONST_KEY_MAP:
1018 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 case LOAD_ATTR:
1020 return 0;
1021 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001022 case IS_OP:
1023 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001025 case JUMP_IF_NOT_EXC_MATCH:
1026 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 case IMPORT_NAME:
1028 return -1;
1029 case IMPORT_FROM:
1030 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001031
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001032 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 case JUMP_ABSOLUTE:
1035 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001037 case JUMP_IF_TRUE_OR_POP:
1038 case JUMP_IF_FALSE_OR_POP:
1039 return jump ? 0 : -1;
1040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 case POP_JUMP_IF_FALSE:
1042 case POP_JUMP_IF_TRUE:
1043 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 case LOAD_GLOBAL:
1046 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001048 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001050 /* 0 in the normal flow.
1051 * Restore the stack position and push 6 values before jumping to
1052 * the handler if an exception be raised. */
1053 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001054 case RERAISE:
1055 return -3;
1056
1057 case WITH_EXCEPT_START:
1058 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 case LOAD_FAST:
1061 return 1;
1062 case STORE_FAST:
1063 return -1;
1064 case DELETE_FAST:
1065 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 case RAISE_VARARGS:
1068 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001069
1070 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001072 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001073 case CALL_METHOD:
1074 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001076 return -oparg-1;
1077 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001078 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001079 case MAKE_FUNCTION:
1080 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1081 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 case BUILD_SLICE:
1083 if (oparg == 3)
1084 return -2;
1085 else
1086 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001088 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 case LOAD_CLOSURE:
1090 return 1;
1091 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001092 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 return 1;
1094 case STORE_DEREF:
1095 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001096 case DELETE_DEREF:
1097 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001098
1099 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001100 case GET_AWAITABLE:
1101 return 0;
1102 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001103 /* 0 in the normal flow.
1104 * Restore the stack position to the position before the result
1105 * of __aenter__ and push 6 values before jumping to the handler
1106 * if an exception be raised. */
1107 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001108 case BEFORE_ASYNC_WITH:
1109 return 1;
1110 case GET_AITER:
1111 return 0;
1112 case GET_ANEXT:
1113 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001114 case GET_YIELD_FROM_ITER:
1115 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001116 case END_ASYNC_FOR:
1117 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001118 case FORMAT_VALUE:
1119 /* If there's a fmt_spec on the stack, we go from 2->1,
1120 else 1->1. */
1121 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001122 case LOAD_METHOD:
1123 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001124 case LOAD_ASSERTION_ERROR:
1125 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001126 case LIST_TO_TUPLE:
1127 return 0;
1128 case LIST_EXTEND:
1129 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001130 case DICT_MERGE:
1131 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001132 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001134 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 }
Larry Hastings3a907972013-11-23 14:49:22 -08001136 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001137}
1138
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001139int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001140PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1141{
1142 return stack_effect(opcode, oparg, jump);
1143}
1144
1145int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001146PyCompile_OpcodeStackEffect(int opcode, int oparg)
1147{
1148 return stack_effect(opcode, oparg, -1);
1149}
1150
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001151/* Add an opcode with no argument.
1152 Returns 0 on failure, 1 on success.
1153*/
1154
1155static int
1156compiler_addop(struct compiler *c, int opcode)
1157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 basicblock *b;
1159 struct instr *i;
1160 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001161 assert(!HAS_ARG(opcode));
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001162 if (c->c_do_not_emit_bytecode) {
1163 return 1;
1164 }
Andy Lester76d58772020-03-10 21:18:12 -05001165 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 if (off < 0)
1167 return 0;
1168 b = c->u->u_curblock;
1169 i = &b->b_instr[off];
1170 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001171 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 if (opcode == RETURN_VALUE)
1173 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001174 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001176}
1177
Victor Stinnerf8e32212013-11-19 23:56:34 +01001178static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001179compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001180{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001181 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001183
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001184 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001186 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001188 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001189 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001190 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 return -1;
1193 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001194 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 Py_DECREF(v);
1196 return -1;
1197 }
1198 Py_DECREF(v);
1199 }
1200 else
1201 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001202 return arg;
1203}
1204
INADA Naokic2e16072018-11-26 21:23:22 +09001205// Merge const *o* recursively and return constant key object.
1206static PyObject*
1207merge_consts_recursive(struct compiler *c, PyObject *o)
1208{
1209 // None and Ellipsis are singleton, and key is the singleton.
1210 // No need to merge object and key.
1211 if (o == Py_None || o == Py_Ellipsis) {
1212 Py_INCREF(o);
1213 return o;
1214 }
1215
1216 PyObject *key = _PyCode_ConstantKey(o);
1217 if (key == NULL) {
1218 return NULL;
1219 }
1220
1221 // t is borrowed reference
1222 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1223 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001224 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001225 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001226 Py_DECREF(key);
1227 return t;
1228 }
1229
INADA Naokif7e4d362018-11-29 00:58:46 +09001230 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001231 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001232 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001233 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001234 Py_ssize_t len = PyTuple_GET_SIZE(o);
1235 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001236 PyObject *item = PyTuple_GET_ITEM(o, i);
1237 PyObject *u = merge_consts_recursive(c, item);
1238 if (u == NULL) {
1239 Py_DECREF(key);
1240 return NULL;
1241 }
1242
1243 // See _PyCode_ConstantKey()
1244 PyObject *v; // borrowed
1245 if (PyTuple_CheckExact(u)) {
1246 v = PyTuple_GET_ITEM(u, 1);
1247 }
1248 else {
1249 v = u;
1250 }
1251 if (v != item) {
1252 Py_INCREF(v);
1253 PyTuple_SET_ITEM(o, i, v);
1254 Py_DECREF(item);
1255 }
1256
1257 Py_DECREF(u);
1258 }
1259 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001260 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001261 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001262 // constant keys.
1263 // See _PyCode_ConstantKey() for detail.
1264 assert(PyTuple_CheckExact(key));
1265 assert(PyTuple_GET_SIZE(key) == 2);
1266
1267 Py_ssize_t len = PySet_GET_SIZE(o);
1268 if (len == 0) { // empty frozenset should not be re-created.
1269 return key;
1270 }
1271 PyObject *tuple = PyTuple_New(len);
1272 if (tuple == NULL) {
1273 Py_DECREF(key);
1274 return NULL;
1275 }
1276 Py_ssize_t i = 0, pos = 0;
1277 PyObject *item;
1278 Py_hash_t hash;
1279 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1280 PyObject *k = merge_consts_recursive(c, item);
1281 if (k == NULL) {
1282 Py_DECREF(tuple);
1283 Py_DECREF(key);
1284 return NULL;
1285 }
1286 PyObject *u;
1287 if (PyTuple_CheckExact(k)) {
1288 u = PyTuple_GET_ITEM(k, 1);
1289 Py_INCREF(u);
1290 Py_DECREF(k);
1291 }
1292 else {
1293 u = k;
1294 }
1295 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1296 i++;
1297 }
1298
1299 // Instead of rewriting o, we create new frozenset and embed in the
1300 // key tuple. Caller should get merged frozenset from the key tuple.
1301 PyObject *new = PyFrozenSet_New(tuple);
1302 Py_DECREF(tuple);
1303 if (new == NULL) {
1304 Py_DECREF(key);
1305 return NULL;
1306 }
1307 assert(PyTuple_GET_ITEM(key, 1) == o);
1308 Py_DECREF(o);
1309 PyTuple_SET_ITEM(key, 1, new);
1310 }
INADA Naokic2e16072018-11-26 21:23:22 +09001311
1312 return key;
1313}
1314
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001315static Py_ssize_t
1316compiler_add_const(struct compiler *c, PyObject *o)
1317{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001318 if (c->c_do_not_emit_bytecode) {
1319 return 0;
1320 }
1321
INADA Naokic2e16072018-11-26 21:23:22 +09001322 PyObject *key = merge_consts_recursive(c, o);
1323 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001324 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001325 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001326
Andy Lester76d58772020-03-10 21:18:12 -05001327 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001328 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001330}
1331
1332static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001333compiler_addop_load_const(struct compiler *c, PyObject *o)
1334{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001335 if (c->c_do_not_emit_bytecode) {
1336 return 1;
1337 }
1338
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001339 Py_ssize_t arg = compiler_add_const(c, o);
1340 if (arg < 0)
1341 return 0;
1342 return compiler_addop_i(c, LOAD_CONST, arg);
1343}
1344
1345static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001346compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001348{
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001349 if (c->c_do_not_emit_bytecode) {
1350 return 1;
1351 }
1352
Andy Lester76d58772020-03-10 21:18:12 -05001353 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001354 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001355 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001356 return compiler_addop_i(c, opcode, arg);
1357}
1358
1359static int
1360compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001362{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001363 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001364
1365 if (c->c_do_not_emit_bytecode) {
1366 return 1;
1367 }
1368
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001369 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1370 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001371 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001372 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373 Py_DECREF(mangled);
1374 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001375 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376 return compiler_addop_i(c, opcode, arg);
1377}
1378
1379/* Add an opcode with an integer argument.
1380 Returns 0 on failure, 1 on success.
1381*/
1382
1383static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001384compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 struct instr *i;
1387 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001388
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001389 if (c->c_do_not_emit_bytecode) {
1390 return 1;
1391 }
1392
Victor Stinner2ad474b2016-03-01 23:34:47 +01001393 /* oparg value is unsigned, but a signed C int is usually used to store
1394 it in the C code (like Python/ceval.c).
1395
1396 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1397
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001398 The argument of a concrete bytecode instruction is limited to 8-bit.
1399 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1400 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001401 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001402
Andy Lester76d58772020-03-10 21:18:12 -05001403 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 if (off < 0)
1405 return 0;
1406 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001407 i->i_opcode = opcode;
1408 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001409 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001411}
1412
1413static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001414compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 struct instr *i;
1417 int off;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001418
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001419 if (c->c_do_not_emit_bytecode) {
1420 return 1;
1421 }
1422
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001423 assert(HAS_ARG(opcode));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 assert(b != NULL);
Andy Lester76d58772020-03-10 21:18:12 -05001425 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (off < 0)
1427 return 0;
1428 i = &c->u->u_curblock->b_instr[off];
1429 i->i_opcode = opcode;
1430 i->i_target = b;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001431 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001433}
1434
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +01001435/* NEXT_BLOCK() creates an implicit jump from the current block
1436 to the new block.
1437
1438 The returns inside this macro make it impossible to decref objects
1439 created in the local function. Local objects should use the arena.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441#define NEXT_BLOCK(C) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 if (compiler_next_block((C)) == NULL) \
1443 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001444}
1445
1446#define ADDOP(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (!compiler_addop((C), (OP))) \
1448 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449}
1450
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001451#define ADDOP_IN_SCOPE(C, OP) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 if (!compiler_addop((C), (OP))) { \
1453 compiler_exit_scope(c); \
1454 return 0; \
1455 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001456}
1457
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001458#define ADDOP_LOAD_CONST(C, O) { \
1459 if (!compiler_addop_load_const((C), (O))) \
1460 return 0; \
1461}
1462
1463/* Same as ADDOP_LOAD_CONST, but steals a reference. */
1464#define ADDOP_LOAD_CONST_NEW(C, O) { \
1465 PyObject *__new_const = (O); \
1466 if (__new_const == NULL) { \
1467 return 0; \
1468 } \
1469 if (!compiler_addop_load_const((C), __new_const)) { \
1470 Py_DECREF(__new_const); \
1471 return 0; \
1472 } \
1473 Py_DECREF(__new_const); \
1474}
1475
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476#define ADDOP_O(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1478 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001479}
1480
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001481/* Same as ADDOP_O, but steals a reference. */
1482#define ADDOP_N(C, OP, O, TYPE) { \
1483 if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \
1484 Py_DECREF((O)); \
1485 return 0; \
1486 } \
1487 Py_DECREF((O)); \
1488}
1489
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001490#define ADDOP_NAME(C, OP, O, TYPE) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
1492 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001493}
1494
1495#define ADDOP_I(C, OP, O) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (!compiler_addop_i((C), (OP), (O))) \
1497 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001498}
1499
Mark Shannon582aaf12020-08-04 17:30:11 +01001500#define ADDOP_JUMP(C, OP, O) { \
1501 if (!compiler_addop_j((C), (OP), (O))) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503}
1504
Mark Shannon9af0e472020-01-14 10:12:45 +00001505#define ADDOP_COMPARE(C, CMP) { \
1506 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1507 return 0; \
1508}
1509
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001510/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1511 the ASDL name to synthesize the name of the C type and the visit function.
1512*/
1513
1514#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (!compiler_visit_ ## TYPE((C), (V))) \
1516 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001517}
1518
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001519#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (!compiler_visit_ ## TYPE((C), (V))) { \
1521 compiler_exit_scope(c); \
1522 return 0; \
1523 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001524}
1525
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 if (!compiler_visit_slice((C), (V), (CTX))) \
1528 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001529}
1530
1531#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001533 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1535 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1536 if (!compiler_visit_ ## TYPE((C), elt)) \
1537 return 0; \
1538 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001539}
1540
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001541#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001543 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1545 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1546 if (!compiler_visit_ ## TYPE((C), elt)) { \
1547 compiler_exit_scope(c); \
1548 return 0; \
1549 } \
1550 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001551}
1552
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001553/* These macros allows to check only for errors and not emmit bytecode
1554 * while visiting nodes.
1555*/
1556
1557#define BEGIN_DO_NOT_EMIT_BYTECODE { \
1558 c->c_do_not_emit_bytecode++;
1559
1560#define END_DO_NOT_EMIT_BYTECODE \
1561 c->c_do_not_emit_bytecode--; \
1562}
1563
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001564/* Search if variable annotations are present statically in a block. */
1565
1566static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001567find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001568{
1569 int i, j, res = 0;
1570 stmt_ty st;
1571
1572 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1573 st = (stmt_ty)asdl_seq_GET(stmts, i);
1574 switch (st->kind) {
1575 case AnnAssign_kind:
1576 return 1;
1577 case For_kind:
1578 res = find_ann(st->v.For.body) ||
1579 find_ann(st->v.For.orelse);
1580 break;
1581 case AsyncFor_kind:
1582 res = find_ann(st->v.AsyncFor.body) ||
1583 find_ann(st->v.AsyncFor.orelse);
1584 break;
1585 case While_kind:
1586 res = find_ann(st->v.While.body) ||
1587 find_ann(st->v.While.orelse);
1588 break;
1589 case If_kind:
1590 res = find_ann(st->v.If.body) ||
1591 find_ann(st->v.If.orelse);
1592 break;
1593 case With_kind:
1594 res = find_ann(st->v.With.body);
1595 break;
1596 case AsyncWith_kind:
1597 res = find_ann(st->v.AsyncWith.body);
1598 break;
1599 case Try_kind:
1600 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1601 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1602 st->v.Try.handlers, j);
1603 if (find_ann(handler->v.ExceptHandler.body)) {
1604 return 1;
1605 }
1606 }
1607 res = find_ann(st->v.Try.body) ||
1608 find_ann(st->v.Try.finalbody) ||
1609 find_ann(st->v.Try.orelse);
1610 break;
1611 default:
1612 res = 0;
1613 }
1614 if (res) {
1615 break;
1616 }
1617 }
1618 return res;
1619}
1620
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001621/*
1622 * Frame block handling functions
1623 */
1624
1625static int
1626compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001627 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001628{
1629 struct fblockinfo *f;
1630 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001631 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001632 }
1633 f = &c->u->u_fblock[c->u->u_nfblocks++];
1634 f->fb_type = t;
1635 f->fb_block = b;
1636 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001637 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001638 return 1;
1639}
1640
1641static void
1642compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1643{
1644 struct compiler_unit *u = c->u;
1645 assert(u->u_nfblocks > 0);
1646 u->u_nfblocks--;
1647 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1648 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1649}
1650
Mark Shannonfee55262019-11-21 09:11:43 +00001651static int
1652compiler_call_exit_with_nones(struct compiler *c) {
1653 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1654 ADDOP(c, DUP_TOP);
1655 ADDOP(c, DUP_TOP);
1656 ADDOP_I(c, CALL_FUNCTION, 3);
1657 return 1;
1658}
1659
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001660/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001661 * popping the blocks will be restored afterwards, unless another
1662 * return, break or continue is found. In which case, the TOS will
1663 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001664 */
1665static int
1666compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1667 int preserve_tos)
1668{
1669 switch (info->fb_type) {
1670 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001671 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001672 return 1;
1673
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001674 case FOR_LOOP:
1675 /* Pop the iterator */
1676 if (preserve_tos) {
1677 ADDOP(c, ROT_TWO);
1678 }
1679 ADDOP(c, POP_TOP);
1680 return 1;
1681
Mark Shannon02d126a2020-09-25 14:04:19 +01001682 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001683 ADDOP(c, POP_BLOCK);
1684 return 1;
1685
1686 case FINALLY_TRY:
1687 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001688 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001689 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1690 return 0;
1691 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001692 }
Mark Shannon88dce262019-12-30 09:53:36 +00001693 /* Emit the finally block, restoring the line number when done */
1694 int saved_lineno = c->u->u_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001695 VISIT_SEQ(c, stmt, info->fb_datum);
Mark Shannon88dce262019-12-30 09:53:36 +00001696 c->u->u_lineno = saved_lineno;
Mark Shannonfee55262019-11-21 09:11:43 +00001697 if (preserve_tos) {
1698 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001699 }
1700 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001701
Mark Shannonfee55262019-11-21 09:11:43 +00001702 case FINALLY_END:
1703 if (preserve_tos) {
1704 ADDOP(c, ROT_FOUR);
1705 }
1706 ADDOP(c, POP_TOP);
1707 ADDOP(c, POP_TOP);
1708 ADDOP(c, POP_TOP);
1709 if (preserve_tos) {
1710 ADDOP(c, ROT_FOUR);
1711 }
1712 ADDOP(c, POP_EXCEPT);
1713 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001714
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001715 case WITH:
1716 case ASYNC_WITH:
1717 ADDOP(c, POP_BLOCK);
1718 if (preserve_tos) {
1719 ADDOP(c, ROT_TWO);
1720 }
Mark Shannonfee55262019-11-21 09:11:43 +00001721 if(!compiler_call_exit_with_nones(c)) {
1722 return 0;
1723 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001724 if (info->fb_type == ASYNC_WITH) {
1725 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001726 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001727 ADDOP(c, YIELD_FROM);
1728 }
Mark Shannonfee55262019-11-21 09:11:43 +00001729 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001730 return 1;
1731
1732 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001733 if (info->fb_datum) {
1734 ADDOP(c, POP_BLOCK);
1735 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001736 if (preserve_tos) {
1737 ADDOP(c, ROT_FOUR);
1738 }
Mark Shannonfee55262019-11-21 09:11:43 +00001739 ADDOP(c, POP_EXCEPT);
1740 if (info->fb_datum) {
1741 ADDOP_LOAD_CONST(c, Py_None);
1742 compiler_nameop(c, info->fb_datum, Store);
1743 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001744 }
Mark Shannonfee55262019-11-21 09:11:43 +00001745 return 1;
1746
1747 case POP_VALUE:
1748 if (preserve_tos) {
1749 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001750 }
Mark Shannonfee55262019-11-21 09:11:43 +00001751 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001752 return 1;
1753 }
1754 Py_UNREACHABLE();
1755}
1756
Mark Shannonfee55262019-11-21 09:11:43 +00001757/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1758static int
1759compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1760 if (c->u->u_nfblocks == 0) {
1761 return 1;
1762 }
1763 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1764 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1765 *loop = top;
1766 return 1;
1767 }
1768 struct fblockinfo copy = *top;
1769 c->u->u_nfblocks--;
1770 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1771 return 0;
1772 }
1773 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1774 return 0;
1775 }
1776 c->u->u_fblock[c->u->u_nfblocks] = copy;
1777 c->u->u_nfblocks++;
1778 return 1;
1779}
1780
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001781/* Compile a sequence of statements, checking for a docstring
1782 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783
1784static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001785compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001787 int i = 0;
1788 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001789 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001790
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001791 /* Set current line number to the line number of first statement.
1792 This way line number for SETUP_ANNOTATIONS will always
1793 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301794 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001795 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001796 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001797 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001798 }
1799 /* Every annotated class and module should have __annotations__. */
1800 if (find_ann(stmts)) {
1801 ADDOP(c, SETUP_ANNOTATIONS);
1802 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001803 if (!asdl_seq_LEN(stmts))
1804 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001805 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001806 if (c->c_optimize < 2) {
1807 docstring = _PyAST_GetDocString(stmts);
1808 if (docstring) {
1809 i = 1;
1810 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1811 assert(st->kind == Expr_kind);
1812 VISIT(c, expr, st->v.Expr.value);
1813 if (!compiler_nameop(c, __doc__, Store))
1814 return 0;
1815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001817 for (; i < asdl_seq_LEN(stmts); i++)
1818 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820}
1821
1822static PyCodeObject *
1823compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 PyCodeObject *co;
1826 int addNone = 1;
1827 static PyObject *module;
1828 if (!module) {
1829 module = PyUnicode_InternFromString("<module>");
1830 if (!module)
1831 return NULL;
1832 }
1833 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001834 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return NULL;
1836 switch (mod->kind) {
1837 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001838 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 compiler_exit_scope(c);
1840 return 0;
1841 }
1842 break;
1843 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001844 if (find_ann(mod->v.Interactive.body)) {
1845 ADDOP(c, SETUP_ANNOTATIONS);
1846 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001848 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 break;
1850 case Expression_kind:
1851 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1852 addNone = 0;
1853 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 default:
1855 PyErr_Format(PyExc_SystemError,
1856 "module kind %d should not be possible",
1857 mod->kind);
1858 return 0;
1859 }
1860 co = assemble(c, addNone);
1861 compiler_exit_scope(c);
1862 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001863}
1864
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865/* The test for LOCAL must come before the test for FREE in order to
1866 handle classes where name is both local and free. The local var is
1867 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001868*/
1869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870static int
1871get_ref_type(struct compiler *c, PyObject *name)
1872{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001873 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001874 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001875 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001876 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001877 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001879 _Py_FatalErrorFormat(__func__,
1880 "unknown scope for %.100s in %.100s(%s)\n"
1881 "symbols: %s\nlocals: %s\nglobals: %s",
1882 PyUnicode_AsUTF8(name),
1883 PyUnicode_AsUTF8(c->u->u_name),
1884 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1885 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1886 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1887 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891}
1892
1893static int
1894compiler_lookup_arg(PyObject *dict, PyObject *name)
1895{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001896 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001897 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001899 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001900 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901}
1902
1903static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001904compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001906 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001907 if (qualname == NULL)
1908 qualname = co->co_name;
1909
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910 if (free) {
1911 for (i = 0; i < free; ++i) {
1912 /* Bypass com_addop_varname because it will generate
1913 LOAD_DEREF but LOAD_CLOSURE is needed.
1914 */
1915 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1916 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001918 /* Special case: If a class contains a method with a
1919 free variable that has the same name as a method,
1920 the name will be considered free *and* local in the
1921 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001922 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001923 */
1924 reftype = get_ref_type(c, name);
1925 if (reftype == CELL)
1926 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1927 else /* (reftype == FREE) */
1928 arg = compiler_lookup_arg(c->u->u_freevars, name);
1929 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001930 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001931 "lookup %s in %s %d %d\n"
1932 "freevars of %s: %s\n",
1933 PyUnicode_AsUTF8(PyObject_Repr(name)),
1934 PyUnicode_AsUTF8(c->u->u_name),
1935 reftype, arg,
1936 PyUnicode_AsUTF8(co->co_name),
1937 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001938 }
1939 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 flags |= 0x08;
1942 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001944 ADDOP_LOAD_CONST(c, (PyObject*)co);
1945 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001946 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948}
1949
1950static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001951compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 if (!decos)
1956 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1959 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1960 }
1961 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962}
1963
1964static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001965compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1966 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001967{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001968 /* Push a dict of keyword-only default values.
1969
1970 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1971 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001972 int i;
1973 PyObject *keys = NULL;
1974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1976 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1977 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1978 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001979 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001980 if (!mangled) {
1981 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001983 if (keys == NULL) {
1984 keys = PyList_New(1);
1985 if (keys == NULL) {
1986 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001987 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001988 }
1989 PyList_SET_ITEM(keys, 0, mangled);
1990 }
1991 else {
1992 int res = PyList_Append(keys, mangled);
1993 Py_DECREF(mangled);
1994 if (res == -1) {
1995 goto error;
1996 }
1997 }
1998 if (!compiler_visit_expr(c, default_)) {
1999 goto error;
2000 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
2002 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002003 if (keys != NULL) {
2004 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2005 PyObject *keys_tuple = PyList_AsTuple(keys);
2006 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002007 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002008 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002009 assert(default_count > 0);
2010 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 }
2012 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002013 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002014 }
2015
2016error:
2017 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002018 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002019}
2020
2021static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002022compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2023{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002024 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002025 return 1;
2026}
2027
2028static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002029compiler_visit_argannotation(struct compiler *c, identifier id,
2030 expr_ty annotation, PyObject *names)
2031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (annotation) {
Victor Stinner065efc32014-02-18 22:07:56 +01002033 PyObject *mangled;
Batuhan Taskaya044a1042020-10-06 23:03:02 +03002034 VISIT(c, annexpr, annotation);
Victor Stinner065efc32014-02-18 22:07:56 +01002035 mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002036 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002037 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002038 if (PyList_Append(names, mangled) < 0) {
2039 Py_DECREF(mangled);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002040 return 0;
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002041 }
2042 Py_DECREF(mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002044 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002045}
2046
2047static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002048compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Neal Norwitzc1505362006-12-28 06:47:50 +00002049 PyObject *names)
2050{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002051 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 for (i = 0; i < asdl_seq_LEN(args); i++) {
2053 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002054 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 c,
2056 arg->arg,
2057 arg->annotation,
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002058 names))
2059 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002061 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002062}
2063
2064static int
2065compiler_visit_annotations(struct compiler *c, arguments_ty args,
2066 expr_ty returns)
2067{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002068 /* Push arg annotation dict.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002069 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002070
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002071 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 */
2073 static identifier return_str;
2074 PyObject *names;
Victor Stinnerad9a0662013-11-19 22:23:20 +01002075 Py_ssize_t len;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 names = PyList_New(0);
2077 if (!names)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002078 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002079
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002080 if (!compiler_visit_argannotations(c, args->args, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 goto error;
Pablo Galindoa0c01bf2019-05-31 15:19:50 +01002082 if (!compiler_visit_argannotations(c, args->posonlyargs, names))
2083 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002084 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002085 !compiler_visit_argannotation(c, args->vararg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002086 args->vararg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 goto error;
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002088 if (!compiler_visit_argannotations(c, args->kwonlyargs, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 goto error;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002090 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002091 !compiler_visit_argannotation(c, args->kwarg->arg,
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002092 args->kwarg->annotation, names))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 goto error;
Neal Norwitzc1505362006-12-28 06:47:50 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (!return_str) {
2096 return_str = PyUnicode_InternFromString("return");
2097 if (!return_str)
2098 goto error;
2099 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002100 if (!compiler_visit_argannotation(c, return_str, returns, names)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 goto error;
2102 }
2103
2104 len = PyList_GET_SIZE(names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 if (len) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002106 PyObject *keytuple = PyList_AsTuple(names);
2107 Py_DECREF(names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002108 ADDOP_LOAD_CONST_NEW(c, keytuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002109 ADDOP_I(c, BUILD_CONST_KEY_MAP, len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002110 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002112 else {
2113 Py_DECREF(names);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002114 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002115 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002116
2117error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 Py_DECREF(names);
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03002119 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002120}
2121
2122static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002123compiler_visit_defaults(struct compiler *c, arguments_ty args)
2124{
2125 VISIT_SEQ(c, expr, args->defaults);
2126 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2127 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002128}
2129
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002130static Py_ssize_t
2131compiler_default_arguments(struct compiler *c, arguments_ty args)
2132{
2133 Py_ssize_t funcflags = 0;
2134 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002135 if (!compiler_visit_defaults(c, args))
2136 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002137 funcflags |= 0x01;
2138 }
2139 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002140 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002141 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002142 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002143 return -1;
2144 }
2145 else if (res > 0) {
2146 funcflags |= 0x02;
2147 }
2148 }
2149 return funcflags;
2150}
2151
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002152static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002153forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2154{
2155
2156 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2157 compiler_error(c, "cannot assign to __debug__");
2158 return 1;
2159 }
2160 return 0;
2161}
2162
2163static int
2164compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2165{
2166 if (arg != NULL) {
2167 if (forbidden_name(c, arg->arg, Store))
2168 return 0;
2169 }
2170 return 1;
2171}
2172
2173static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002174compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002175{
2176 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002177 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002178 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2179 return 0;
2180 }
2181 }
2182 return 1;
2183}
2184
2185static int
2186compiler_check_debug_args(struct compiler *c, arguments_ty args)
2187{
2188 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2189 return 0;
2190 if (!compiler_check_debug_args_seq(c, args->args))
2191 return 0;
2192 if (!compiler_check_debug_one_arg(c, args->vararg))
2193 return 0;
2194 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2195 return 0;
2196 if (!compiler_check_debug_one_arg(c, args->kwarg))
2197 return 0;
2198 return 1;
2199}
2200
2201static int
Yury Selivanov75445082015-05-11 22:57:16 -04002202compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002205 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002206 arguments_ty args;
2207 expr_ty returns;
2208 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002209 asdl_expr_seq* decos;
2210 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002211 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002212 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002213 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002214 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002215
Yury Selivanov75445082015-05-11 22:57:16 -04002216 if (is_async) {
2217 assert(s->kind == AsyncFunctionDef_kind);
2218
2219 args = s->v.AsyncFunctionDef.args;
2220 returns = s->v.AsyncFunctionDef.returns;
2221 decos = s->v.AsyncFunctionDef.decorator_list;
2222 name = s->v.AsyncFunctionDef.name;
2223 body = s->v.AsyncFunctionDef.body;
2224
2225 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2226 } else {
2227 assert(s->kind == FunctionDef_kind);
2228
2229 args = s->v.FunctionDef.args;
2230 returns = s->v.FunctionDef.returns;
2231 decos = s->v.FunctionDef.decorator_list;
2232 name = s->v.FunctionDef.name;
2233 body = s->v.FunctionDef.body;
2234
2235 scope_type = COMPILER_SCOPE_FUNCTION;
2236 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002238 if (!compiler_check_debug_args(c, args))
2239 return 0;
2240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 if (!compiler_decorators(c, decos))
2242 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002243
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002244 firstlineno = s->lineno;
2245 if (asdl_seq_LEN(decos)) {
2246 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2247 }
2248
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002249 funcflags = compiler_default_arguments(c, args);
2250 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002252 }
2253
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002254 annotations = compiler_visit_annotations(c, args, returns);
2255 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002256 return 0;
2257 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002258 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002259 funcflags |= 0x04;
2260 }
2261
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002262 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002263 return 0;
2264 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265
INADA Naokicb41b272017-02-23 00:31:59 +09002266 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002267 if (c->c_optimize < 2) {
2268 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002269 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002270 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 compiler_exit_scope(c);
2272 return 0;
2273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002276 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002278 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002279 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002280 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002282 qualname = c->u->u_qualname;
2283 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002285 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002286 Py_XDECREF(qualname);
2287 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002289 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002290
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002291 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002292 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 /* decorators */
2296 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2297 ADDOP_I(c, CALL_FUNCTION, 1);
2298 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299
Yury Selivanov75445082015-05-11 22:57:16 -04002300 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002301}
2302
2303static int
2304compiler_class(struct compiler *c, stmt_ty s)
2305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 PyCodeObject *co;
2307 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002308 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002309 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (!compiler_decorators(c, decos))
2312 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002313
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002314 firstlineno = s->lineno;
2315 if (asdl_seq_LEN(decos)) {
2316 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2317 }
2318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 /* ultimately generate code for:
2320 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2321 where:
2322 <func> is a function/closure created from the class body;
2323 it has a single argument (__locals__) where the dict
2324 (or MutableSequence) representing the locals is passed
2325 <name> is the class name
2326 <bases> is the positional arguments and *varargs argument
2327 <keywords> is the keyword arguments and **kwds argument
2328 This borrows from compiler_call.
2329 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002332 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002333 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return 0;
2335 /* this block represents what we do in the new scope */
2336 {
2337 /* use the class name for name mangling */
2338 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002339 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* load (global) __name__ ... */
2341 str = PyUnicode_InternFromString("__name__");
2342 if (!str || !compiler_nameop(c, str, Load)) {
2343 Py_XDECREF(str);
2344 compiler_exit_scope(c);
2345 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002346 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 Py_DECREF(str);
2348 /* ... and store it as __module__ */
2349 str = PyUnicode_InternFromString("__module__");
2350 if (!str || !compiler_nameop(c, str, Store)) {
2351 Py_XDECREF(str);
2352 compiler_exit_scope(c);
2353 return 0;
2354 }
2355 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002356 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002357 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002358 str = PyUnicode_InternFromString("__qualname__");
2359 if (!str || !compiler_nameop(c, str, Store)) {
2360 Py_XDECREF(str);
2361 compiler_exit_scope(c);
2362 return 0;
2363 }
2364 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002366 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 compiler_exit_scope(c);
2368 return 0;
2369 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002370 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002371 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002372 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002373 str = PyUnicode_InternFromString("__class__");
2374 if (str == NULL) {
2375 compiler_exit_scope(c);
2376 return 0;
2377 }
2378 i = compiler_lookup_arg(c->u->u_cellvars, str);
2379 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002380 if (i < 0) {
2381 compiler_exit_scope(c);
2382 return 0;
2383 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002384 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002387 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002388 str = PyUnicode_InternFromString("__classcell__");
2389 if (!str || !compiler_nameop(c, str, Store)) {
2390 Py_XDECREF(str);
2391 compiler_exit_scope(c);
2392 return 0;
2393 }
2394 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002396 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002397 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002398 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002399 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002400 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002401 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 /* create the code object */
2403 co = assemble(c, 1);
2404 }
2405 /* leave the new scope */
2406 compiler_exit_scope(c);
2407 if (co == NULL)
2408 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* 2. load the 'build_class' function */
2411 ADDOP(c, LOAD_BUILD_CLASS);
2412
2413 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002414 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 Py_DECREF(co);
2416
2417 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002418 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419
2420 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002421 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return 0;
2423
2424 /* 6. apply decorators */
2425 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2426 ADDOP_I(c, CALL_FUNCTION, 1);
2427 }
2428
2429 /* 7. store into <name> */
2430 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2431 return 0;
2432 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002433}
2434
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002435/* Return 0 if the expression is a constant value except named singletons.
2436 Return 1 otherwise. */
2437static int
2438check_is_arg(expr_ty e)
2439{
2440 if (e->kind != Constant_kind) {
2441 return 1;
2442 }
2443 PyObject *value = e->v.Constant.value;
2444 return (value == Py_None
2445 || value == Py_False
2446 || value == Py_True
2447 || value == Py_Ellipsis);
2448}
2449
2450/* Check operands of identity chacks ("is" and "is not").
2451 Emit a warning if any operand is a constant except named singletons.
2452 Return 0 on error.
2453 */
2454static int
2455check_compare(struct compiler *c, expr_ty e)
2456{
2457 Py_ssize_t i, n;
2458 int left = check_is_arg(e->v.Compare.left);
2459 n = asdl_seq_LEN(e->v.Compare.ops);
2460 for (i = 0; i < n; i++) {
2461 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2462 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2463 if (op == Is || op == IsNot) {
2464 if (!right || !left) {
2465 const char *msg = (op == Is)
2466 ? "\"is\" with a literal. Did you mean \"==\"?"
2467 : "\"is not\" with a literal. Did you mean \"!=\"?";
2468 return compiler_warn(c, msg);
2469 }
2470 }
2471 left = right;
2472 }
2473 return 1;
2474}
2475
Mark Shannon9af0e472020-01-14 10:12:45 +00002476static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002477{
Mark Shannon9af0e472020-01-14 10:12:45 +00002478 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002479 switch (op) {
2480 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002481 cmp = Py_EQ;
2482 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002483 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002484 cmp = Py_NE;
2485 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002486 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002487 cmp = Py_LT;
2488 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002489 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002490 cmp = Py_LE;
2491 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002492 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002493 cmp = Py_GT;
2494 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002495 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002496 cmp = Py_GE;
2497 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002498 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002499 ADDOP_I(c, IS_OP, 0);
2500 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002501 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002502 ADDOP_I(c, IS_OP, 1);
2503 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002504 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002505 ADDOP_I(c, CONTAINS_OP, 0);
2506 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002507 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002508 ADDOP_I(c, CONTAINS_OP, 1);
2509 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002510 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002511 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002512 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002513 ADDOP_I(c, COMPARE_OP, cmp);
2514 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002515}
2516
Mark Shannon9af0e472020-01-14 10:12:45 +00002517
2518
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002519static int
2520compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2521{
2522 switch (e->kind) {
2523 case UnaryOp_kind:
2524 if (e->v.UnaryOp.op == Not)
2525 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2526 /* fallback to general implementation */
2527 break;
2528 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002529 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002530 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2531 assert(n >= 0);
2532 int cond2 = e->v.BoolOp.op == Or;
2533 basicblock *next2 = next;
2534 if (!cond2 != !cond) {
2535 next2 = compiler_new_block(c);
2536 if (next2 == NULL)
2537 return 0;
2538 }
2539 for (i = 0; i < n; ++i) {
2540 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2541 return 0;
2542 }
2543 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2544 return 0;
2545 if (next2 != next)
2546 compiler_use_next_block(c, next2);
2547 return 1;
2548 }
2549 case IfExp_kind: {
2550 basicblock *end, *next2;
2551 end = compiler_new_block(c);
2552 if (end == NULL)
2553 return 0;
2554 next2 = compiler_new_block(c);
2555 if (next2 == NULL)
2556 return 0;
2557 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2558 return 0;
2559 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2560 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002561 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002562 compiler_use_next_block(c, next2);
2563 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2564 return 0;
2565 compiler_use_next_block(c, end);
2566 return 1;
2567 }
2568 case Compare_kind: {
2569 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2570 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002571 if (!check_compare(c, e)) {
2572 return 0;
2573 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002574 basicblock *cleanup = compiler_new_block(c);
2575 if (cleanup == NULL)
2576 return 0;
2577 VISIT(c, expr, e->v.Compare.left);
2578 for (i = 0; i < n; i++) {
2579 VISIT(c, expr,
2580 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2581 ADDOP(c, DUP_TOP);
2582 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002583 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002584 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002585 NEXT_BLOCK(c);
2586 }
2587 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002588 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002589 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002590 basicblock *end = compiler_new_block(c);
2591 if (end == NULL)
2592 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01002593 ADDOP_JUMP(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002594 compiler_use_next_block(c, cleanup);
2595 ADDOP(c, POP_TOP);
2596 if (!cond) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002597 ADDOP_JUMP(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002598 }
2599 compiler_use_next_block(c, end);
2600 return 1;
2601 }
2602 /* fallback to general implementation */
2603 break;
2604 }
2605 default:
2606 /* fallback to general implementation */
2607 break;
2608 }
2609
2610 /* general implementation */
2611 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002612 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002613 return 1;
2614}
2615
2616static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002617compiler_ifexp(struct compiler *c, expr_ty e)
2618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 basicblock *end, *next;
2620
2621 assert(e->kind == IfExp_kind);
2622 end = compiler_new_block(c);
2623 if (end == NULL)
2624 return 0;
2625 next = compiler_new_block(c);
2626 if (next == NULL)
2627 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002628 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2629 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002631 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 compiler_use_next_block(c, next);
2633 VISIT(c, expr, e->v.IfExp.orelse);
2634 compiler_use_next_block(c, end);
2635 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002636}
2637
2638static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639compiler_lambda(struct compiler *c, expr_ty e)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002642 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002644 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 arguments_ty args = e->v.Lambda.args;
2646 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002647
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002648 if (!compiler_check_debug_args(c, args))
2649 return 0;
2650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 if (!name) {
2652 name = PyUnicode_InternFromString("<lambda>");
2653 if (!name)
2654 return 0;
2655 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002657 funcflags = compiler_default_arguments(c, args);
2658 if (funcflags == -1) {
2659 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002661
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002662 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002663 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 /* Make None the first constant, so the lambda can't have a
2667 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002668 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002672 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2674 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2675 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002676 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 }
2678 else {
2679 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002680 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002682 qualname = c->u->u_qualname;
2683 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002685 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002687
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002688 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002689 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 Py_DECREF(co);
2691
2692 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002693}
2694
2695static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002696compiler_if(struct compiler *c, stmt_ty s)
2697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 basicblock *end, *next;
2699 int constant;
2700 assert(s->kind == If_kind);
2701 end = compiler_new_block(c);
2702 if (end == NULL)
2703 return 0;
2704
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002705 constant = expr_constant(s->v.If.test);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002706 /* constant = 0: "if 0"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 * constant = 1: "if 1", "if 2", ...
2708 * constant = -1: rest */
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002709 if (constant == 0) {
2710 BEGIN_DO_NOT_EMIT_BYTECODE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 VISIT_SEQ(c, stmt, s->v.If.body);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002712 END_DO_NOT_EMIT_BYTECODE
2713 if (s->v.If.orelse) {
2714 VISIT_SEQ(c, stmt, s->v.If.orelse);
2715 }
2716 } else if (constant == 1) {
2717 VISIT_SEQ(c, stmt, s->v.If.body);
2718 if (s->v.If.orelse) {
2719 BEGIN_DO_NOT_EMIT_BYTECODE
2720 VISIT_SEQ(c, stmt, s->v.If.orelse);
2721 END_DO_NOT_EMIT_BYTECODE
2722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 } else {
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002724 if (asdl_seq_LEN(s->v.If.orelse)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 next = compiler_new_block(c);
2726 if (next == NULL)
2727 return 0;
2728 }
Mark Shannonfee55262019-11-21 09:11:43 +00002729 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 next = end;
Mark Shannonfee55262019-11-21 09:11:43 +00002731 }
2732 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002733 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002734 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 VISIT_SEQ(c, stmt, s->v.If.body);
Antoine Pitroue7811fc2014-09-18 03:06:50 +02002736 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon582aaf12020-08-04 17:30:11 +01002737 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 compiler_use_next_block(c, next);
2739 VISIT_SEQ(c, stmt, s->v.If.orelse);
2740 }
2741 }
2742 compiler_use_next_block(c, end);
2743 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744}
2745
2746static int
2747compiler_for(struct compiler *c, stmt_ty s)
2748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 basicblock *start, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 start = compiler_new_block(c);
2752 cleanup = compiler_new_block(c);
2753 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002754 if (start == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002756 }
2757 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002759 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 VISIT(c, expr, s->v.For.iter);
2761 ADDOP(c, GET_ITER);
2762 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002763 ADDOP_JUMP(c, FOR_ITER, cleanup);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 VISIT(c, expr, s->v.For.target);
2765 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002766 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002768
2769 compiler_pop_fblock(c, FOR_LOOP, start);
2770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 VISIT_SEQ(c, stmt, s->v.For.orelse);
2772 compiler_use_next_block(c, end);
2773 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774}
2775
Yury Selivanov75445082015-05-11 22:57:16 -04002776
2777static int
2778compiler_async_for(struct compiler *c, stmt_ty s)
2779{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002780 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002781 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002782 c->u->u_ste->ste_coroutine = 1;
2783 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002784 return compiler_error(c, "'async for' outside async function");
2785 }
2786
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002787 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002788 except = compiler_new_block(c);
2789 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002790
Mark Shannonfee55262019-11-21 09:11:43 +00002791 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002792 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002793 }
Yury Selivanov75445082015-05-11 22:57:16 -04002794 VISIT(c, expr, s->v.AsyncFor.iter);
2795 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002796
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002797 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002798 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002799 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002800 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002801 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002802 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002803 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002804 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002805 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002806 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002807
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002808 /* Success block for __anext__ */
2809 VISIT(c, expr, s->v.AsyncFor.target);
2810 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002811 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002812
2813 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002814
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002815 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002816 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002817
2818 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002819 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002820
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002821 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002822 VISIT_SEQ(c, stmt, s->v.For.orelse);
2823
2824 compiler_use_next_block(c, end);
2825
2826 return 1;
2827}
2828
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829static int
2830compiler_while(struct compiler *c, stmt_ty s)
2831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002832 basicblock *loop, *orelse, *end, *anchor = NULL;
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02002833 int constant = expr_constant(s->v.While.test);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 if (constant == 0) {
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002836 BEGIN_DO_NOT_EMIT_BYTECODE
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002837 // Push a dummy block so the VISIT_SEQ knows that we are
2838 // inside a while loop so it can correctly evaluate syntax
2839 // errors.
Mark Shannonfee55262019-11-21 09:11:43 +00002840 if (!compiler_push_fblock(c, WHILE_LOOP, NULL, NULL, NULL)) {
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002841 return 0;
2842 }
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002843 VISIT_SEQ(c, stmt, s->v.While.body);
Pablo Galindo6c3e66a2019-10-30 11:53:26 +00002844 // Remove the dummy block now that is not needed.
2845 compiler_pop_fblock(c, WHILE_LOOP, NULL);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002846 END_DO_NOT_EMIT_BYTECODE
2847 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 VISIT_SEQ(c, stmt, s->v.While.orelse);
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01002849 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 return 1;
2851 }
2852 loop = compiler_new_block(c);
2853 end = compiler_new_block(c);
2854 if (constant == -1) {
2855 anchor = compiler_new_block(c);
2856 if (anchor == NULL)
2857 return 0;
2858 }
2859 if (loop == NULL || end == NULL)
2860 return 0;
2861 if (s->v.While.orelse) {
2862 orelse = compiler_new_block(c);
2863 if (orelse == NULL)
2864 return 0;
2865 }
2866 else
2867 orelse = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 compiler_use_next_block(c, loop);
Mark Shannonfee55262019-11-21 09:11:43 +00002870 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 return 0;
2872 if (constant == -1) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002873 if (!compiler_jump_if(c, s->v.While.test, anchor, 0))
2874 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 }
2876 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002877 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 /* XXX should the two POP instructions be in a separate block
2880 if there is no else clause ?
2881 */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002882
Benjamin Peterson3cda0ed2014-12-13 16:06:19 -05002883 if (constant == -1)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 compiler_use_next_block(c, anchor);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002885 compiler_pop_fblock(c, WHILE_LOOP, loop);
2886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 if (orelse != NULL) /* what if orelse is just pass? */
2888 VISIT_SEQ(c, stmt, s->v.While.orelse);
2889 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);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002920 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002921}
2922
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002923static int
2924compiler_break(struct compiler *c)
2925{
Mark Shannonfee55262019-11-21 09:11:43 +00002926 struct fblockinfo *loop = NULL;
2927 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2928 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002929 }
Mark Shannonfee55262019-11-21 09:11:43 +00002930 if (loop == NULL) {
2931 return compiler_error(c, "'break' outside loop");
2932 }
2933 if (!compiler_unwind_fblock(c, loop, 0)) {
2934 return 0;
2935 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002936 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannonfee55262019-11-21 09:11:43 +00002937 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002938}
2939
2940static int
2941compiler_continue(struct compiler *c)
2942{
Mark Shannonfee55262019-11-21 09:11:43 +00002943 struct fblockinfo *loop = NULL;
2944 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2945 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002946 }
Mark Shannonfee55262019-11-21 09:11:43 +00002947 if (loop == NULL) {
2948 return compiler_error(c, "'continue' not properly in loop");
2949 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002950 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannonfee55262019-11-21 09:11:43 +00002951 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002952}
2953
2954
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002955/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002956
2957 SETUP_FINALLY L
2958 <code for body>
2959 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002960 <code for finalbody>
2961 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002962 L:
2963 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002964 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002965
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002966 The special instructions use the block stack. Each block
2967 stack entry contains the instruction that created it (here
2968 SETUP_FINALLY), the level of the value stack at the time the
2969 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002970
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002971 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 Pushes the current value stack level and the label
2973 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002974 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002975 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002978 when a SETUP_FINALLY entry is found, the raised and the caught
2979 exceptions are pushed onto the value stack (and the exception
2980 condition is cleared), and the interpreter jumps to the label
2981 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002982*/
2983
2984static int
2985compiler_try_finally(struct compiler *c, stmt_ty s)
2986{
Mark Shannonfee55262019-11-21 09:11:43 +00002987 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002989 body = compiler_new_block(c);
2990 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002991 exit = compiler_new_block(c);
2992 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002993 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002994
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002995 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002996 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002997 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002998 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002999 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003000 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
3001 if (!compiler_try_except(c, s))
3002 return 0;
3003 }
3004 else {
3005 VISIT_SEQ(c, stmt, s->v.Try.body);
3006 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003007 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00003008 compiler_pop_fblock(c, FINALLY_TRY, body);
3009 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon582aaf12020-08-04 17:30:11 +01003010 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00003011 /* `finally` block */
3012 compiler_use_next_block(c, end);
3013 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
3014 return 0;
3015 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
3016 compiler_pop_fblock(c, FINALLY_END, end);
3017 ADDOP(c, RERAISE);
3018 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003019 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003020}
3021
3022/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00003023 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003024 (The contents of the value stack is shown in [], with the top
3025 at the right; 'tb' is trace-back info, 'val' the exception's
3026 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003027
3028 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003029 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 [] <code for S>
3031 [] POP_BLOCK
3032 [] JUMP_FORWARD L0
3033
3034 [tb, val, exc] L1: DUP )
3035 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00003036 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003037 [tb, val, exc] POP
3038 [tb, val] <assign to V1> (or POP if no V1)
3039 [tb] POP
3040 [] <code for S1>
3041 JUMP_FORWARD L0
3042
3043 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003044 .............................etc.......................
3045
Mark Shannonfee55262019-11-21 09:11:43 +00003046 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003047
3048 [] L0: <next statement>
3049
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003050 Of course, parts are not generated if Vi or Ei is not present.
3051*/
3052static int
3053compiler_try_except(struct compiler *c, stmt_ty s)
3054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003056 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003058 body = compiler_new_block(c);
3059 except = compiler_new_block(c);
3060 orelse = compiler_new_block(c);
3061 end = compiler_new_block(c);
3062 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3063 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003064 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003065 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003066 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003068 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003069 ADDOP(c, POP_BLOCK);
Mark Shannon02d126a2020-09-25 14:04:19 +01003070 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon582aaf12020-08-04 17:30:11 +01003071 ADDOP_JUMP(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003072 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003073 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003074 /* Runtime will push a block here, so we need to account for that */
3075 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3076 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003077 for (i = 0; i < n; i++) {
3078 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003079 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 if (!handler->v.ExceptHandler.type && i < n-1)
3081 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003082 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003083 except = compiler_new_block(c);
3084 if (except == NULL)
3085 return 0;
3086 if (handler->v.ExceptHandler.type) {
3087 ADDOP(c, DUP_TOP);
3088 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003089 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 }
3091 ADDOP(c, POP_TOP);
3092 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003093 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003094
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003095 cleanup_end = compiler_new_block(c);
3096 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003097 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003098 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003099 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003100
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3102 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003104 /*
3105 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003106 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003107 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003108 try:
3109 # body
3110 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003111 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003112 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003113 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003115 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003116 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003117 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003118 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003119 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003120
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003121 /* second # body */
3122 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003123 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003124 ADDOP(c, POP_BLOCK);
3125 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003126 /* name = None; del name; # Mark as artificial */
3127 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003128 ADDOP_LOAD_CONST(c, Py_None);
3129 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3130 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003131 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132
Mark Shannonfee55262019-11-21 09:11:43 +00003133 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003134 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135
Mark Shannon877df852020-11-12 09:43:29 +00003136 /* name = None; del name; # Mark as artificial */
3137 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003138 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003139 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003140 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141
Mark Shannonfee55262019-11-21 09:11:43 +00003142 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003143 }
3144 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003145 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003147 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003148 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003149 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150
Guido van Rossumb940e112007-01-10 16:19:56 +00003151 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003152 ADDOP(c, POP_TOP);
3153 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003154 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003155 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003156 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003157 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003158 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003159 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 compiler_use_next_block(c, except);
3162 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003163 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonfee55262019-11-21 09:11:43 +00003164 ADDOP(c, RERAISE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003165 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003166 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003167 compiler_use_next_block(c, end);
3168 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003169}
3170
3171static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003172compiler_try(struct compiler *c, stmt_ty s) {
3173 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3174 return compiler_try_finally(c, s);
3175 else
3176 return compiler_try_except(c, s);
3177}
3178
3179
3180static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003181compiler_import_as(struct compiler *c, identifier name, identifier asname)
3182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 /* The IMPORT_NAME opcode was already generated. This function
3184 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003186 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003187 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003188 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003189 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3190 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003191 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003192 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003193 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003195 while (1) {
3196 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003198 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003199 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003200 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003201 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003202 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003203 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003204 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003205 if (dot == -1) {
3206 break;
3207 }
3208 ADDOP(c, ROT_TWO);
3209 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003211 if (!compiler_nameop(c, asname, Store)) {
3212 return 0;
3213 }
3214 ADDOP(c, POP_TOP);
3215 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 }
3217 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003218}
3219
3220static int
3221compiler_import(struct compiler *c, stmt_ty s)
3222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003223 /* The Import node stores a module name like a.b.c as a single
3224 string. This is convenient for all cases except
3225 import a.b.c as d
3226 where we need to parse that string to extract the individual
3227 module names.
3228 XXX Perhaps change the representation to make this case simpler?
3229 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003230 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003231
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003232 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 for (i = 0; i < n; i++) {
3234 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3235 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003237 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003238 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003239 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003241 if (alias->asname) {
3242 r = compiler_import_as(c, alias->name, alias->asname);
3243 if (!r)
3244 return r;
3245 }
3246 else {
3247 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003248 Py_ssize_t dot = PyUnicode_FindChar(
3249 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003250 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003251 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003252 if (tmp == NULL)
3253 return 0;
3254 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003255 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003256 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 Py_DECREF(tmp);
3258 }
3259 if (!r)
3260 return r;
3261 }
3262 }
3263 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003264}
3265
3266static int
3267compiler_from_import(struct compiler *c, stmt_ty s)
3268{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003269 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003270 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 if (!empty_string) {
3274 empty_string = PyUnicode_FromString("");
3275 if (!empty_string)
3276 return 0;
3277 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003278
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003279 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003280
3281 names = PyTuple_New(n);
3282 if (!names)
3283 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 /* build up the names */
3286 for (i = 0; i < n; i++) {
3287 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3288 Py_INCREF(alias->name);
3289 PyTuple_SET_ITEM(names, i, alias->name);
3290 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003293 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 Py_DECREF(names);
3295 return compiler_error(c, "from __future__ imports must occur "
3296 "at the beginning of the file");
3297 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003298 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 if (s->v.ImportFrom.module) {
3301 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3302 }
3303 else {
3304 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3305 }
3306 for (i = 0; i < n; i++) {
3307 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3308 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003310 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003311 assert(n == 1);
3312 ADDOP(c, IMPORT_STAR);
3313 return 1;
3314 }
3315
3316 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3317 store_name = alias->name;
3318 if (alias->asname)
3319 store_name = alias->asname;
3320
3321 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003322 return 0;
3323 }
3324 }
3325 /* remove imported module */
3326 ADDOP(c, POP_TOP);
3327 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003328}
3329
3330static int
3331compiler_assert(struct compiler *c, stmt_ty s)
3332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003333 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003334
Georg Brandl8334fd92010-12-04 10:26:46 +00003335 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003337 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003338 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3339 {
3340 if (!compiler_warn(c, "assertion is always true, "
3341 "perhaps remove parentheses?"))
3342 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003343 return 0;
3344 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003345 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003346 end = compiler_new_block(c);
3347 if (end == NULL)
3348 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003349 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3350 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003351 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003352 if (s->v.Assert.msg) {
3353 VISIT(c, expr, s->v.Assert.msg);
3354 ADDOP_I(c, CALL_FUNCTION, 1);
3355 }
3356 ADDOP_I(c, RAISE_VARARGS, 1);
3357 compiler_use_next_block(c, end);
3358 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003359}
3360
3361static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003362compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3363{
3364 if (c->c_interactive && c->c_nestlevel <= 1) {
3365 VISIT(c, expr, value);
3366 ADDOP(c, PRINT_EXPR);
3367 return 1;
3368 }
3369
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003370 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003371 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003372 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003373 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003374 }
3375
3376 VISIT(c, expr, value);
3377 ADDOP(c, POP_TOP);
3378 return 1;
3379}
3380
3381static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003382compiler_visit_stmt(struct compiler *c, stmt_ty s)
3383{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003384 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003387 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 switch (s->kind) {
3390 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003391 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 case ClassDef_kind:
3393 return compiler_class(c, s);
3394 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003395 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003396 case Delete_kind:
3397 VISIT_SEQ(c, expr, s->v.Delete.targets)
3398 break;
3399 case Assign_kind:
3400 n = asdl_seq_LEN(s->v.Assign.targets);
3401 VISIT(c, expr, s->v.Assign.value);
3402 for (i = 0; i < n; i++) {
3403 if (i < n - 1)
3404 ADDOP(c, DUP_TOP);
3405 VISIT(c, expr,
3406 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3407 }
3408 break;
3409 case AugAssign_kind:
3410 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003411 case AnnAssign_kind:
3412 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003413 case For_kind:
3414 return compiler_for(c, s);
3415 case While_kind:
3416 return compiler_while(c, s);
3417 case If_kind:
3418 return compiler_if(c, s);
3419 case Raise_kind:
3420 n = 0;
3421 if (s->v.Raise.exc) {
3422 VISIT(c, expr, s->v.Raise.exc);
3423 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003424 if (s->v.Raise.cause) {
3425 VISIT(c, expr, s->v.Raise.cause);
3426 n++;
3427 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003428 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003429 ADDOP_I(c, RAISE_VARARGS, (int)n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003430 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003431 case Try_kind:
3432 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003433 case Assert_kind:
3434 return compiler_assert(c, s);
3435 case Import_kind:
3436 return compiler_import(c, s);
3437 case ImportFrom_kind:
3438 return compiler_from_import(c, s);
3439 case Global_kind:
3440 case Nonlocal_kind:
3441 break;
3442 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003443 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003444 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003445 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003446 break;
3447 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003448 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003449 case Continue_kind:
3450 return compiler_continue(c);
3451 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003452 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003453 case AsyncFunctionDef_kind:
3454 return compiler_function(c, s, 1);
3455 case AsyncWith_kind:
3456 return compiler_async_with(c, s, 0);
3457 case AsyncFor_kind:
3458 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003459 }
Yury Selivanov75445082015-05-11 22:57:16 -04003460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003461 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003462}
3463
3464static int
3465unaryop(unaryop_ty op)
3466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003467 switch (op) {
3468 case Invert:
3469 return UNARY_INVERT;
3470 case Not:
3471 return UNARY_NOT;
3472 case UAdd:
3473 return UNARY_POSITIVE;
3474 case USub:
3475 return UNARY_NEGATIVE;
3476 default:
3477 PyErr_Format(PyExc_SystemError,
3478 "unary op %d should not be possible", op);
3479 return 0;
3480 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481}
3482
3483static int
Andy Lester76d58772020-03-10 21:18:12 -05003484binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003486 switch (op) {
3487 case Add:
3488 return BINARY_ADD;
3489 case Sub:
3490 return BINARY_SUBTRACT;
3491 case Mult:
3492 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003493 case MatMult:
3494 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003495 case Div:
3496 return BINARY_TRUE_DIVIDE;
3497 case Mod:
3498 return BINARY_MODULO;
3499 case Pow:
3500 return BINARY_POWER;
3501 case LShift:
3502 return BINARY_LSHIFT;
3503 case RShift:
3504 return BINARY_RSHIFT;
3505 case BitOr:
3506 return BINARY_OR;
3507 case BitXor:
3508 return BINARY_XOR;
3509 case BitAnd:
3510 return BINARY_AND;
3511 case FloorDiv:
3512 return BINARY_FLOOR_DIVIDE;
3513 default:
3514 PyErr_Format(PyExc_SystemError,
3515 "binary op %d should not be possible", op);
3516 return 0;
3517 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003518}
3519
3520static int
Andy Lester76d58772020-03-10 21:18:12 -05003521inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 switch (op) {
3524 case Add:
3525 return INPLACE_ADD;
3526 case Sub:
3527 return INPLACE_SUBTRACT;
3528 case Mult:
3529 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003530 case MatMult:
3531 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003532 case Div:
3533 return INPLACE_TRUE_DIVIDE;
3534 case Mod:
3535 return INPLACE_MODULO;
3536 case Pow:
3537 return INPLACE_POWER;
3538 case LShift:
3539 return INPLACE_LSHIFT;
3540 case RShift:
3541 return INPLACE_RSHIFT;
3542 case BitOr:
3543 return INPLACE_OR;
3544 case BitXor:
3545 return INPLACE_XOR;
3546 case BitAnd:
3547 return INPLACE_AND;
3548 case FloorDiv:
3549 return INPLACE_FLOOR_DIVIDE;
3550 default:
3551 PyErr_Format(PyExc_SystemError,
3552 "inplace binary op %d should not be possible", op);
3553 return 0;
3554 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003555}
3556
3557static int
3558compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3559{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003560 int op, scope;
3561 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003562 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003564 PyObject *dict = c->u->u_names;
3565 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003566
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003567 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3568 !_PyUnicode_EqualToASCIIString(name, "True") &&
3569 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003570
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003571 if (forbidden_name(c, name, ctx))
3572 return 0;
3573
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003574 mangled = _Py_Mangle(c->u->u_private, name);
3575 if (!mangled)
3576 return 0;
3577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003578 op = 0;
3579 optype = OP_NAME;
3580 scope = PyST_GetScope(c->u->u_ste, mangled);
3581 switch (scope) {
3582 case FREE:
3583 dict = c->u->u_freevars;
3584 optype = OP_DEREF;
3585 break;
3586 case CELL:
3587 dict = c->u->u_cellvars;
3588 optype = OP_DEREF;
3589 break;
3590 case LOCAL:
3591 if (c->u->u_ste->ste_type == FunctionBlock)
3592 optype = OP_FAST;
3593 break;
3594 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003595 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003596 optype = OP_GLOBAL;
3597 break;
3598 case GLOBAL_EXPLICIT:
3599 optype = OP_GLOBAL;
3600 break;
3601 default:
3602 /* scope can be 0 */
3603 break;
3604 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003606 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003607 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003609 switch (optype) {
3610 case OP_DEREF:
3611 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003612 case Load:
3613 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3614 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003615 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003616 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003617 }
3618 break;
3619 case OP_FAST:
3620 switch (ctx) {
3621 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003622 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003623 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003624 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003625 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003626 return 1;
3627 case OP_GLOBAL:
3628 switch (ctx) {
3629 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003630 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003631 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003632 }
3633 break;
3634 case OP_NAME:
3635 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003636 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003637 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003638 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003639 }
3640 break;
3641 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003643 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003644 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003645 Py_DECREF(mangled);
3646 if (arg < 0)
3647 return 0;
3648 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003649}
3650
3651static int
3652compiler_boolop(struct compiler *c, expr_ty e)
3653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003654 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003655 int jumpi;
3656 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003657 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003659 assert(e->kind == BoolOp_kind);
3660 if (e->v.BoolOp.op == And)
3661 jumpi = JUMP_IF_FALSE_OR_POP;
3662 else
3663 jumpi = JUMP_IF_TRUE_OR_POP;
3664 end = compiler_new_block(c);
3665 if (end == NULL)
3666 return 0;
3667 s = e->v.BoolOp.values;
3668 n = asdl_seq_LEN(s) - 1;
3669 assert(n >= 0);
3670 for (i = 0; i < n; ++i) {
3671 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003672 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003673 basicblock *next = compiler_new_block(c);
3674 if (next == NULL) {
3675 return 0;
3676 }
3677 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003678 }
3679 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3680 compiler_use_next_block(c, end);
3681 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003682}
3683
3684static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003685starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003686 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003687{
3688 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003689 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003690 if (n > 2 && are_all_items_const(elts, 0, n)) {
3691 PyObject *folded = PyTuple_New(n);
3692 if (folded == NULL) {
3693 return 0;
3694 }
3695 PyObject *val;
3696 for (i = 0; i < n; i++) {
3697 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3698 Py_INCREF(val);
3699 PyTuple_SET_ITEM(folded, i, val);
3700 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003701 if (tuple) {
3702 ADDOP_LOAD_CONST_NEW(c, folded);
3703 } else {
3704 if (add == SET_ADD) {
3705 Py_SETREF(folded, PyFrozenSet_New(folded));
3706 if (folded == NULL) {
3707 return 0;
3708 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003709 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003710 ADDOP_I(c, build, pushed);
3711 ADDOP_LOAD_CONST_NEW(c, folded);
3712 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003713 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003714 return 1;
3715 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003716
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003717 for (i = 0; i < n; i++) {
3718 expr_ty elt = asdl_seq_GET(elts, i);
3719 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003720 seen_star = 1;
3721 }
3722 }
3723 if (seen_star) {
3724 seen_star = 0;
3725 for (i = 0; i < n; i++) {
3726 expr_ty elt = asdl_seq_GET(elts, i);
3727 if (elt->kind == Starred_kind) {
3728 if (seen_star == 0) {
3729 ADDOP_I(c, build, i+pushed);
3730 seen_star = 1;
3731 }
3732 VISIT(c, expr, elt->v.Starred.value);
3733 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003734 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003735 else {
3736 VISIT(c, expr, elt);
3737 if (seen_star) {
3738 ADDOP_I(c, add, 1);
3739 }
3740 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003741 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003742 assert(seen_star);
3743 if (tuple) {
3744 ADDOP(c, LIST_TO_TUPLE);
3745 }
3746 }
3747 else {
3748 for (i = 0; i < n; i++) {
3749 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003750 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003751 }
3752 if (tuple) {
3753 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3754 } else {
3755 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003756 }
3757 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003758 return 1;
3759}
3760
3761static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003762assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003763{
3764 Py_ssize_t n = asdl_seq_LEN(elts);
3765 Py_ssize_t i;
3766 int seen_star = 0;
3767 for (i = 0; i < n; i++) {
3768 expr_ty elt = asdl_seq_GET(elts, i);
3769 if (elt->kind == Starred_kind && !seen_star) {
3770 if ((i >= (1 << 8)) ||
3771 (n-i-1 >= (INT_MAX >> 8)))
3772 return compiler_error(c,
3773 "too many expressions in "
3774 "star-unpacking assignment");
3775 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3776 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003777 }
3778 else if (elt->kind == Starred_kind) {
3779 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003780 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003781 }
3782 }
3783 if (!seen_star) {
3784 ADDOP_I(c, UNPACK_SEQUENCE, n);
3785 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003786 for (i = 0; i < n; i++) {
3787 expr_ty elt = asdl_seq_GET(elts, i);
3788 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3789 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003790 return 1;
3791}
3792
3793static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003794compiler_list(struct compiler *c, expr_ty e)
3795{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003796 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003797 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003798 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003799 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003800 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003801 return starunpack_helper(c, elts, 0, BUILD_LIST,
3802 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003803 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003804 else
3805 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003806 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003807}
3808
3809static int
3810compiler_tuple(struct compiler *c, expr_ty e)
3811{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003812 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003813 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003814 return assignment_helper(c, elts);
3815 }
3816 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003817 return starunpack_helper(c, elts, 0, BUILD_LIST,
3818 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003819 }
3820 else
3821 VISIT_SEQ(c, expr, elts);
3822 return 1;
3823}
3824
3825static int
3826compiler_set(struct compiler *c, expr_ty e)
3827{
Mark Shannon13bc1392020-01-23 09:25:17 +00003828 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3829 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003830}
3831
3832static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003833are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003834{
3835 Py_ssize_t i;
3836 for (i = begin; i < end; i++) {
3837 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003838 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003839 return 0;
3840 }
3841 return 1;
3842}
3843
3844static int
3845compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3846{
3847 Py_ssize_t i, n = end - begin;
3848 PyObject *keys, *key;
3849 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3850 for (i = begin; i < end; i++) {
3851 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3852 }
3853 keys = PyTuple_New(n);
3854 if (keys == NULL) {
3855 return 0;
3856 }
3857 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003858 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003859 Py_INCREF(key);
3860 PyTuple_SET_ITEM(keys, i - begin, key);
3861 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003862 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003863 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3864 }
3865 else {
3866 for (i = begin; i < end; i++) {
3867 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3868 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3869 }
3870 ADDOP_I(c, BUILD_MAP, n);
3871 }
3872 return 1;
3873}
3874
3875static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003876compiler_dict(struct compiler *c, expr_ty e)
3877{
Victor Stinner976bb402016-03-23 11:36:19 +01003878 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003879 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003880 int is_unpacking = 0;
3881 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003882 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003883 elements = 0;
3884 for (i = 0; i < n; i++) {
3885 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003886 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003887 if (elements) {
3888 if (!compiler_subdict(c, e, i - elements, i)) {
3889 return 0;
3890 }
3891 if (have_dict) {
3892 ADDOP_I(c, DICT_UPDATE, 1);
3893 }
3894 have_dict = 1;
3895 elements = 0;
3896 }
3897 if (have_dict == 0) {
3898 ADDOP_I(c, BUILD_MAP, 0);
3899 have_dict = 1;
3900 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003901 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003902 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003903 }
3904 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003905 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003906 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003907 return 0;
3908 }
3909 if (have_dict) {
3910 ADDOP_I(c, DICT_UPDATE, 1);
3911 }
3912 have_dict = 1;
3913 elements = 0;
3914 }
3915 else {
3916 elements++;
3917 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003918 }
3919 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003920 if (elements) {
3921 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003922 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003923 }
3924 if (have_dict) {
3925 ADDOP_I(c, DICT_UPDATE, 1);
3926 }
3927 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003928 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003929 if (!have_dict) {
3930 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003931 }
3932 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003933}
3934
3935static int
3936compiler_compare(struct compiler *c, expr_ty e)
3937{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003938 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003939
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003940 if (!check_compare(c, e)) {
3941 return 0;
3942 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003943 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003944 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3945 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3946 if (n == 0) {
3947 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003948 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003949 }
3950 else {
3951 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003952 if (cleanup == NULL)
3953 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003954 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003955 VISIT(c, expr,
3956 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003957 ADDOP(c, DUP_TOP);
3958 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003959 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003960 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003961 NEXT_BLOCK(c);
3962 }
3963 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003964 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003965 basicblock *end = compiler_new_block(c);
3966 if (end == NULL)
3967 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003968 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003969 compiler_use_next_block(c, cleanup);
3970 ADDOP(c, ROT_TWO);
3971 ADDOP(c, POP_TOP);
3972 compiler_use_next_block(c, end);
3973 }
3974 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003975}
3976
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003977static PyTypeObject *
3978infer_type(expr_ty e)
3979{
3980 switch (e->kind) {
3981 case Tuple_kind:
3982 return &PyTuple_Type;
3983 case List_kind:
3984 case ListComp_kind:
3985 return &PyList_Type;
3986 case Dict_kind:
3987 case DictComp_kind:
3988 return &PyDict_Type;
3989 case Set_kind:
3990 case SetComp_kind:
3991 return &PySet_Type;
3992 case GeneratorExp_kind:
3993 return &PyGen_Type;
3994 case Lambda_kind:
3995 return &PyFunction_Type;
3996 case JoinedStr_kind:
3997 case FormattedValue_kind:
3998 return &PyUnicode_Type;
3999 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01004000 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004001 default:
4002 return NULL;
4003 }
4004}
4005
4006static int
4007check_caller(struct compiler *c, expr_ty e)
4008{
4009 switch (e->kind) {
4010 case Constant_kind:
4011 case Tuple_kind:
4012 case List_kind:
4013 case ListComp_kind:
4014 case Dict_kind:
4015 case DictComp_kind:
4016 case Set_kind:
4017 case SetComp_kind:
4018 case GeneratorExp_kind:
4019 case JoinedStr_kind:
4020 case FormattedValue_kind:
4021 return compiler_warn(c, "'%.200s' object is not callable; "
4022 "perhaps you missed a comma?",
4023 infer_type(e)->tp_name);
4024 default:
4025 return 1;
4026 }
4027}
4028
4029static int
4030check_subscripter(struct compiler *c, expr_ty e)
4031{
4032 PyObject *v;
4033
4034 switch (e->kind) {
4035 case Constant_kind:
4036 v = e->v.Constant.value;
4037 if (!(v == Py_None || v == Py_Ellipsis ||
4038 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
4039 PyAnySet_Check(v)))
4040 {
4041 return 1;
4042 }
4043 /* fall through */
4044 case Set_kind:
4045 case SetComp_kind:
4046 case GeneratorExp_kind:
4047 case Lambda_kind:
4048 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4049 "perhaps you missed a comma?",
4050 infer_type(e)->tp_name);
4051 default:
4052 return 1;
4053 }
4054}
4055
4056static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004057check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004058{
4059 PyObject *v;
4060
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004061 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004062 if (index_type == NULL
4063 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4064 || index_type == &PySlice_Type) {
4065 return 1;
4066 }
4067
4068 switch (e->kind) {
4069 case Constant_kind:
4070 v = e->v.Constant.value;
4071 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4072 return 1;
4073 }
4074 /* fall through */
4075 case Tuple_kind:
4076 case List_kind:
4077 case ListComp_kind:
4078 case JoinedStr_kind:
4079 case FormattedValue_kind:
4080 return compiler_warn(c, "%.200s indices must be integers or slices, "
4081 "not %.200s; "
4082 "perhaps you missed a comma?",
4083 infer_type(e)->tp_name,
4084 index_type->tp_name);
4085 default:
4086 return 1;
4087 }
4088}
4089
Zackery Spytz97f5de02019-03-22 01:30:32 -06004090// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004091static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004092maybe_optimize_method_call(struct compiler *c, expr_ty e)
4093{
4094 Py_ssize_t argsl, i;
4095 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004096 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004097
4098 /* Check that the call node is an attribute access, and that
4099 the call doesn't have keyword parameters. */
4100 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4101 asdl_seq_LEN(e->v.Call.keywords))
4102 return -1;
4103
4104 /* Check that there are no *varargs types of arguments. */
4105 argsl = asdl_seq_LEN(args);
4106 for (i = 0; i < argsl; i++) {
4107 expr_ty elt = asdl_seq_GET(args, i);
4108 if (elt->kind == Starred_kind) {
4109 return -1;
4110 }
4111 }
4112
4113 /* Alright, we can optimize the code. */
4114 VISIT(c, expr, meth->v.Attribute.value);
4115 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4116 VISIT_SEQ(c, expr, e->v.Call.args);
4117 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4118 return 1;
4119}
4120
4121static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004122validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004123{
4124 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4125 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004126 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4127 if (key->arg == NULL) {
4128 continue;
4129 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004130 if (forbidden_name(c, key->arg, Store)) {
4131 return -1;
4132 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004133 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004134 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4135 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4136 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4137 if (msg == NULL) {
4138 return -1;
4139 }
4140 c->u->u_col_offset = other->col_offset;
4141 compiler_error(c, PyUnicode_AsUTF8(msg));
4142 Py_DECREF(msg);
4143 return -1;
4144 }
4145 }
4146 }
4147 return 0;
4148}
4149
4150static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004151compiler_call(struct compiler *c, expr_ty e)
4152{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004153 int ret = maybe_optimize_method_call(c, e);
4154 if (ret >= 0) {
4155 return ret;
4156 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004157 if (!check_caller(c, e->v.Call.func)) {
4158 return 0;
4159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004160 VISIT(c, expr, e->v.Call.func);
4161 return compiler_call_helper(c, 0,
4162 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004163 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004164}
4165
Eric V. Smith235a6f02015-09-19 14:51:32 -04004166static int
4167compiler_joined_str(struct compiler *c, expr_ty e)
4168{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004169 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004170 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4171 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004172 return 1;
4173}
4174
Eric V. Smitha78c7952015-11-03 12:45:05 -05004175/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004176static int
4177compiler_formatted_value(struct compiler *c, expr_ty e)
4178{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004179 /* Our oparg encodes 2 pieces of information: the conversion
4180 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004181
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004182 Convert the conversion char to 3 bits:
4183 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004184 !s : 001 0x1 FVC_STR
4185 !r : 010 0x2 FVC_REPR
4186 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004187
Eric V. Smitha78c7952015-11-03 12:45:05 -05004188 next bit is whether or not we have a format spec:
4189 yes : 100 0x4
4190 no : 000 0x0
4191 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004192
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004193 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004194 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004195
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004196 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004197 VISIT(c, expr, e->v.FormattedValue.value);
4198
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004199 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004200 case 's': oparg = FVC_STR; break;
4201 case 'r': oparg = FVC_REPR; break;
4202 case 'a': oparg = FVC_ASCII; break;
4203 case -1: oparg = FVC_NONE; break;
4204 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004205 PyErr_Format(PyExc_SystemError,
4206 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004207 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004208 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004209 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004210 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004211 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004212 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004213 }
4214
Eric V. Smitha78c7952015-11-03 12:45:05 -05004215 /* And push our opcode and oparg */
4216 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004217
Eric V. Smith235a6f02015-09-19 14:51:32 -04004218 return 1;
4219}
4220
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004221static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004222compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004223{
4224 Py_ssize_t i, n = end - begin;
4225 keyword_ty kw;
4226 PyObject *keys, *key;
4227 assert(n > 0);
4228 if (n > 1) {
4229 for (i = begin; i < end; i++) {
4230 kw = asdl_seq_GET(keywords, i);
4231 VISIT(c, expr, kw->value);
4232 }
4233 keys = PyTuple_New(n);
4234 if (keys == NULL) {
4235 return 0;
4236 }
4237 for (i = begin; i < end; i++) {
4238 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4239 Py_INCREF(key);
4240 PyTuple_SET_ITEM(keys, i - begin, key);
4241 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004242 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004243 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4244 }
4245 else {
4246 /* a for loop only executes once */
4247 for (i = begin; i < end; i++) {
4248 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004249 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004250 VISIT(c, expr, kw->value);
4251 }
4252 ADDOP_I(c, BUILD_MAP, n);
4253 }
4254 return 1;
4255}
4256
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004257/* shared code between compiler_call and compiler_class */
4258static int
4259compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004260 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004261 asdl_expr_seq *args,
4262 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004263{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004264 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004265
Pablo Galindo254ec782020-04-03 20:37:13 +01004266 if (validate_keywords(c, keywords) == -1) {
4267 return 0;
4268 }
4269
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004270 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004271 nkwelts = asdl_seq_LEN(keywords);
4272
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004273 for (i = 0; i < nelts; i++) {
4274 expr_ty elt = asdl_seq_GET(args, i);
4275 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004276 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004277 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004278 }
4279 for (i = 0; i < nkwelts; i++) {
4280 keyword_ty kw = asdl_seq_GET(keywords, i);
4281 if (kw->arg == NULL) {
4282 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004283 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004284 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004285
Mark Shannon13bc1392020-01-23 09:25:17 +00004286 /* No * or ** args, so can use faster calling sequence */
4287 for (i = 0; i < nelts; i++) {
4288 expr_ty elt = asdl_seq_GET(args, i);
4289 assert(elt->kind != Starred_kind);
4290 VISIT(c, expr, elt);
4291 }
4292 if (nkwelts) {
4293 PyObject *names;
4294 VISIT_SEQ(c, keyword, keywords);
4295 names = PyTuple_New(nkwelts);
4296 if (names == NULL) {
4297 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004298 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004299 for (i = 0; i < nkwelts; i++) {
4300 keyword_ty kw = asdl_seq_GET(keywords, i);
4301 Py_INCREF(kw->arg);
4302 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004303 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004304 ADDOP_LOAD_CONST_NEW(c, names);
4305 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4306 return 1;
4307 }
4308 else {
4309 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4310 return 1;
4311 }
4312
4313ex_call:
4314
4315 /* Do positional arguments. */
4316 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4317 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4318 }
4319 else if (starunpack_helper(c, args, n, BUILD_LIST,
4320 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4321 return 0;
4322 }
4323 /* Then keyword arguments */
4324 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004325 /* Has a new dict been pushed */
4326 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004327
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004328 nseen = 0; /* the number of keyword arguments on the stack following */
4329 for (i = 0; i < nkwelts; i++) {
4330 keyword_ty kw = asdl_seq_GET(keywords, i);
4331 if (kw->arg == NULL) {
4332 /* A keyword argument unpacking. */
4333 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004334 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004335 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004336 }
Mark Shannondb64f122020-06-01 10:42:42 +01004337 if (have_dict) {
4338 ADDOP_I(c, DICT_MERGE, 1);
4339 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004340 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004341 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004342 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004343 if (!have_dict) {
4344 ADDOP_I(c, BUILD_MAP, 0);
4345 have_dict = 1;
4346 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004347 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004348 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004349 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004350 else {
4351 nseen++;
4352 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004353 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004354 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004355 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004356 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004357 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004358 }
4359 if (have_dict) {
4360 ADDOP_I(c, DICT_MERGE, 1);
4361 }
4362 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004363 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004364 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004365 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004366 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4367 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004368}
4369
Nick Coghlan650f0d02007-04-15 12:05:43 +00004370
4371/* List and set comprehensions and generator expressions work by creating a
4372 nested function to perform the actual iteration. This means that the
4373 iteration variables don't leak into the current scope.
4374 The defined function is called immediately following its definition, with the
4375 result of that call being the result of the expression.
4376 The LC/SC version returns the populated container, while the GE version is
4377 flagged in symtable.c as a generator, so it returns the generator object
4378 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004379
4380 Possible cleanups:
4381 - iterate over the generator sequence instead of using recursion
4382*/
4383
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004384
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004385static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004386compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004387 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004388 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004389 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004390{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004391 comprehension_ty gen;
4392 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4393 if (gen->is_async) {
4394 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004395 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004396 } else {
4397 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004398 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004399 }
4400}
4401
4402static int
4403compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004404 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004405 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004406 expr_ty elt, expr_ty val, int type)
4407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004408 /* generate code for the iterator, then each of the ifs,
4409 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004411 comprehension_ty gen;
4412 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004413 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004415 start = compiler_new_block(c);
4416 skip = compiler_new_block(c);
4417 if_cleanup = compiler_new_block(c);
4418 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004420 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4421 anchor == NULL)
4422 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 if (gen_index == 0) {
4427 /* Receive outermost iter as an implicit argument */
4428 c->u->u_argcount = 1;
4429 ADDOP_I(c, LOAD_FAST, 0);
4430 }
4431 else {
4432 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004433 /* Fast path for the temporary variable assignment idiom:
4434 for y in [f(x)]
4435 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004436 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004437 switch (gen->iter->kind) {
4438 case List_kind:
4439 elts = gen->iter->v.List.elts;
4440 break;
4441 case Tuple_kind:
4442 elts = gen->iter->v.Tuple.elts;
4443 break;
4444 default:
4445 elts = NULL;
4446 }
4447 if (asdl_seq_LEN(elts) == 1) {
4448 expr_ty elt = asdl_seq_GET(elts, 0);
4449 if (elt->kind != Starred_kind) {
4450 VISIT(c, expr, elt);
4451 start = NULL;
4452 }
4453 }
4454 if (start) {
4455 VISIT(c, expr, gen->iter);
4456 ADDOP(c, GET_ITER);
4457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004458 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004459 if (start) {
4460 depth++;
4461 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004462 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004463 NEXT_BLOCK(c);
4464 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004465 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004467 /* XXX this needs to be cleaned up...a lot! */
4468 n = asdl_seq_LEN(gen->ifs);
4469 for (i = 0; i < n; i++) {
4470 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004471 if (!compiler_jump_if(c, e, if_cleanup, 0))
4472 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004473 NEXT_BLOCK(c);
4474 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476 if (++gen_index < asdl_seq_LEN(generators))
4477 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004478 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004479 elt, val, type))
4480 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004482 /* only append after the last for generator */
4483 if (gen_index >= asdl_seq_LEN(generators)) {
4484 /* comprehension specific code */
4485 switch (type) {
4486 case COMP_GENEXP:
4487 VISIT(c, expr, elt);
4488 ADDOP(c, YIELD_VALUE);
4489 ADDOP(c, POP_TOP);
4490 break;
4491 case COMP_LISTCOMP:
4492 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004493 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004494 break;
4495 case COMP_SETCOMP:
4496 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004497 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004498 break;
4499 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004500 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004501 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004502 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004503 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004504 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004505 break;
4506 default:
4507 return 0;
4508 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004510 compiler_use_next_block(c, skip);
4511 }
4512 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004513 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004514 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004515 compiler_use_next_block(c, anchor);
4516 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004517
4518 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004519}
4520
4521static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004522compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004523 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004524 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004525 expr_ty elt, expr_ty val, int type)
4526{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004527 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004528 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004529 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004530 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004532 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004533
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004534 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004535 return 0;
4536 }
4537
4538 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4539
4540 if (gen_index == 0) {
4541 /* Receive outermost iter as an implicit argument */
4542 c->u->u_argcount = 1;
4543 ADDOP_I(c, LOAD_FAST, 0);
4544 }
4545 else {
4546 /* Sub-iter - calculate on the fly */
4547 VISIT(c, expr, gen->iter);
4548 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004549 }
4550
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004551 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004552
Mark Shannon582aaf12020-08-04 17:30:11 +01004553 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004555 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004556 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004558 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004559
4560 n = asdl_seq_LEN(gen->ifs);
4561 for (i = 0; i < n; i++) {
4562 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004563 if (!compiler_jump_if(c, e, if_cleanup, 0))
4564 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004565 NEXT_BLOCK(c);
4566 }
4567
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004568 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004569 if (++gen_index < asdl_seq_LEN(generators))
4570 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004571 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004572 elt, val, type))
4573 return 0;
4574
4575 /* only append after the last for generator */
4576 if (gen_index >= asdl_seq_LEN(generators)) {
4577 /* comprehension specific code */
4578 switch (type) {
4579 case COMP_GENEXP:
4580 VISIT(c, expr, elt);
4581 ADDOP(c, YIELD_VALUE);
4582 ADDOP(c, POP_TOP);
4583 break;
4584 case COMP_LISTCOMP:
4585 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004586 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004587 break;
4588 case COMP_SETCOMP:
4589 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004590 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004591 break;
4592 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004593 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004594 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004595 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004596 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004597 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004598 break;
4599 default:
4600 return 0;
4601 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004602 }
4603 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004604 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004605
4606 compiler_use_next_block(c, except);
4607 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004608
4609 return 1;
4610}
4611
4612static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004613compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004614 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004615 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004617 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004618 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004619 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004620 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004621 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004622
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004623
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004624 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004625
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004626 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004627 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4628 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004629 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004630 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004631 }
4632
4633 is_async_generator = c->u->u_ste->ste_coroutine;
4634
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004635 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004636 compiler_error(c, "asynchronous comprehension outside of "
4637 "an asynchronous function");
4638 goto error_in_scope;
4639 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004641 if (type != COMP_GENEXP) {
4642 int op;
4643 switch (type) {
4644 case COMP_LISTCOMP:
4645 op = BUILD_LIST;
4646 break;
4647 case COMP_SETCOMP:
4648 op = BUILD_SET;
4649 break;
4650 case COMP_DICTCOMP:
4651 op = BUILD_MAP;
4652 break;
4653 default:
4654 PyErr_Format(PyExc_SystemError,
4655 "unknown comprehension type %d", type);
4656 goto error_in_scope;
4657 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004659 ADDOP_I(c, op, 0);
4660 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004661
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004662 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004663 val, type))
4664 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004666 if (type != COMP_GENEXP) {
4667 ADDOP(c, RETURN_VALUE);
4668 }
4669
4670 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004671 qualname = c->u->u_qualname;
4672 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004673 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004674 if (top_level_await && is_async_generator){
4675 c->u->u_ste->ste_coroutine = 1;
4676 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004677 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004678 goto error;
4679
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004680 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004681 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004682 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004683 Py_DECREF(co);
4684
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004685 VISIT(c, expr, outermost->iter);
4686
4687 if (outermost->is_async) {
4688 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004689 } else {
4690 ADDOP(c, GET_ITER);
4691 }
4692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004693 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004694
4695 if (is_async_generator && type != COMP_GENEXP) {
4696 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004697 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004698 ADDOP(c, YIELD_FROM);
4699 }
4700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004701 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004702error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004703 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004704error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004705 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004706 Py_XDECREF(co);
4707 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004708}
4709
4710static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004711compiler_genexp(struct compiler *c, expr_ty e)
4712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004713 static identifier name;
4714 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004715 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004716 if (!name)
4717 return 0;
4718 }
4719 assert(e->kind == GeneratorExp_kind);
4720 return compiler_comprehension(c, e, COMP_GENEXP, name,
4721 e->v.GeneratorExp.generators,
4722 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004723}
4724
4725static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004726compiler_listcomp(struct compiler *c, expr_ty e)
4727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004728 static identifier name;
4729 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004730 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004731 if (!name)
4732 return 0;
4733 }
4734 assert(e->kind == ListComp_kind);
4735 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4736 e->v.ListComp.generators,
4737 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004738}
4739
4740static int
4741compiler_setcomp(struct compiler *c, expr_ty e)
4742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004743 static identifier name;
4744 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004745 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004746 if (!name)
4747 return 0;
4748 }
4749 assert(e->kind == SetComp_kind);
4750 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4751 e->v.SetComp.generators,
4752 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004753}
4754
4755
4756static int
4757compiler_dictcomp(struct compiler *c, expr_ty e)
4758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004759 static identifier name;
4760 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004761 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004762 if (!name)
4763 return 0;
4764 }
4765 assert(e->kind == DictComp_kind);
4766 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4767 e->v.DictComp.generators,
4768 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004769}
4770
4771
4772static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004773compiler_visit_keyword(struct compiler *c, keyword_ty k)
4774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004775 VISIT(c, expr, k->value);
4776 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004777}
4778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004779/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004780 whether they are true or false.
4781
4782 Return values: 1 for true, 0 for false, -1 for non-constant.
4783 */
4784
4785static int
Serhiy Storchaka3dfbaf52017-12-25 12:47:50 +02004786expr_constant(expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004787{
Serhiy Storchaka3f228112018-09-27 17:42:37 +03004788 if (e->kind == Constant_kind) {
4789 return PyObject_IsTrue(e->v.Constant.value);
Benjamin Peterson442f2092012-12-06 17:41:04 -05004790 }
Serhiy Storchaka3325a672017-12-15 12:35:48 +02004791 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004792}
4793
Mark Shannonfee55262019-11-21 09:11:43 +00004794static int
4795compiler_with_except_finish(struct compiler *c) {
4796 basicblock *exit;
4797 exit = compiler_new_block(c);
4798 if (exit == NULL)
4799 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004800 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004801 ADDOP(c, RERAISE);
4802 compiler_use_next_block(c, exit);
4803 ADDOP(c, POP_TOP);
4804 ADDOP(c, POP_TOP);
4805 ADDOP(c, POP_TOP);
4806 ADDOP(c, POP_EXCEPT);
4807 ADDOP(c, POP_TOP);
4808 return 1;
4809}
Yury Selivanov75445082015-05-11 22:57:16 -04004810
4811/*
4812 Implements the async with statement.
4813
4814 The semantics outlined in that PEP are as follows:
4815
4816 async with EXPR as VAR:
4817 BLOCK
4818
4819 It is implemented roughly as:
4820
4821 context = EXPR
4822 exit = context.__aexit__ # not calling it
4823 value = await context.__aenter__()
4824 try:
4825 VAR = value # if VAR present in the syntax
4826 BLOCK
4827 finally:
4828 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004829 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004830 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004831 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004832 if not (await exit(*exc)):
4833 raise
4834 */
4835static int
4836compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4837{
Mark Shannonfee55262019-11-21 09:11:43 +00004838 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004839 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4840
4841 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004842 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004843 c->u->u_ste->ste_coroutine = 1;
4844 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004845 return compiler_error(c, "'async with' outside async function");
4846 }
Yury Selivanov75445082015-05-11 22:57:16 -04004847
4848 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004849 final = compiler_new_block(c);
4850 exit = compiler_new_block(c);
4851 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004852 return 0;
4853
4854 /* Evaluate EXPR */
4855 VISIT(c, expr, item->context_expr);
4856
4857 ADDOP(c, BEFORE_ASYNC_WITH);
4858 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004859 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004860 ADDOP(c, YIELD_FROM);
4861
Mark Shannon582aaf12020-08-04 17:30:11 +01004862 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004863
4864 /* SETUP_ASYNC_WITH pushes a finally block. */
4865 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004866 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004867 return 0;
4868 }
4869
4870 if (item->optional_vars) {
4871 VISIT(c, expr, item->optional_vars);
4872 }
4873 else {
4874 /* Discard result from context.__aenter__() */
4875 ADDOP(c, POP_TOP);
4876 }
4877
4878 pos++;
4879 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4880 /* BLOCK code */
4881 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4882 else if (!compiler_async_with(c, s, pos))
4883 return 0;
4884
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004885 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004886 ADDOP(c, POP_BLOCK);
4887 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004888
Mark Shannonfee55262019-11-21 09:11:43 +00004889 /* For successful outcome:
4890 * call __exit__(None, None, None)
4891 */
4892 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004893 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004894 ADDOP(c, GET_AWAITABLE);
4895 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4896 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004897
Mark Shannonfee55262019-11-21 09:11:43 +00004898 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004899
Mark Shannon582aaf12020-08-04 17:30:11 +01004900 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004901
4902 /* For exceptional outcome: */
4903 compiler_use_next_block(c, final);
4904
4905 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004906 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004907 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004908 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004909 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004910
Mark Shannonfee55262019-11-21 09:11:43 +00004911compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004912 return 1;
4913}
4914
4915
Guido van Rossumc2e20742006-02-27 22:32:47 +00004916/*
4917 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004918 with EXPR as VAR:
4919 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004920 is implemented as:
4921 <code for EXPR>
4922 SETUP_WITH E
4923 <code to store to VAR> or POP_TOP
4924 <code for BLOCK>
4925 LOAD_CONST (None, None, None)
4926 CALL_FUNCTION_EX 0
4927 JUMP_FORWARD EXIT
4928 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4929 POP_JUMP_IF_TRUE T:
4930 RERAISE
4931 T: POP_TOP * 3 (remove exception from stack)
4932 POP_EXCEPT
4933 POP_TOP
4934 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004935 */
Mark Shannonfee55262019-11-21 09:11:43 +00004936
Guido van Rossumc2e20742006-02-27 22:32:47 +00004937static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004938compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004939{
Mark Shannonfee55262019-11-21 09:11:43 +00004940 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004941 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004942
4943 assert(s->kind == With_kind);
4944
Guido van Rossumc2e20742006-02-27 22:32:47 +00004945 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004946 final = compiler_new_block(c);
4947 exit = compiler_new_block(c);
4948 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004949 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004950
Thomas Wouters477c8d52006-05-27 19:21:47 +00004951 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004952 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004953 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004954 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004955
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004956 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004957 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004958 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004959 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004960 }
4961
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004962 if (item->optional_vars) {
4963 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004964 }
4965 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004967 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004968 }
4969
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004970 pos++;
4971 if (pos == asdl_seq_LEN(s->v.With.items))
4972 /* BLOCK code */
4973 VISIT_SEQ(c, stmt, s->v.With.body)
4974 else if (!compiler_with(c, s, pos))
4975 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004976
Guido van Rossumc2e20742006-02-27 22:32:47 +00004977 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004978 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004979
Mark Shannonfee55262019-11-21 09:11:43 +00004980 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004981
Mark Shannonfee55262019-11-21 09:11:43 +00004982 /* For successful outcome:
4983 * call __exit__(None, None, None)
4984 */
4985 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004986 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004987 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004988 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004989
Mark Shannonfee55262019-11-21 09:11:43 +00004990 /* For exceptional outcome: */
4991 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004992
Mark Shannonfee55262019-11-21 09:11:43 +00004993 ADDOP(c, WITH_EXCEPT_START);
4994 compiler_with_except_finish(c);
4995
4996 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004997 return 1;
4998}
4999
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005000static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005001compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005003 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07005004 case NamedExpr_kind:
5005 VISIT(c, expr, e->v.NamedExpr.value);
5006 ADDOP(c, DUP_TOP);
5007 VISIT(c, expr, e->v.NamedExpr.target);
5008 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005009 case BoolOp_kind:
5010 return compiler_boolop(c, e);
5011 case BinOp_kind:
5012 VISIT(c, expr, e->v.BinOp.left);
5013 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05005014 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005015 break;
5016 case UnaryOp_kind:
5017 VISIT(c, expr, e->v.UnaryOp.operand);
5018 ADDOP(c, unaryop(e->v.UnaryOp.op));
5019 break;
5020 case Lambda_kind:
5021 return compiler_lambda(c, e);
5022 case IfExp_kind:
5023 return compiler_ifexp(c, e);
5024 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005025 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005026 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005027 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005028 case GeneratorExp_kind:
5029 return compiler_genexp(c, e);
5030 case ListComp_kind:
5031 return compiler_listcomp(c, e);
5032 case SetComp_kind:
5033 return compiler_setcomp(c, e);
5034 case DictComp_kind:
5035 return compiler_dictcomp(c, e);
5036 case Yield_kind:
5037 if (c->u->u_ste->ste_type != FunctionBlock)
5038 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005039 if (e->v.Yield.value) {
5040 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 }
5042 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005043 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005044 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005045 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005046 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005047 case YieldFrom_kind:
5048 if (c->u->u_ste->ste_type != FunctionBlock)
5049 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005050
5051 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5052 return compiler_error(c, "'yield from' inside async function");
5053
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005054 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005055 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005056 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005057 ADDOP(c, YIELD_FROM);
5058 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005059 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005060 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005061 if (c->u->u_ste->ste_type != FunctionBlock){
5062 return compiler_error(c, "'await' outside function");
5063 }
Yury Selivanov75445082015-05-11 22:57:16 -04005064
Victor Stinner331a6a52019-05-27 16:39:22 +02005065 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005066 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5067 return compiler_error(c, "'await' outside async function");
5068 }
5069 }
Yury Selivanov75445082015-05-11 22:57:16 -04005070
5071 VISIT(c, expr, e->v.Await.value);
5072 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005073 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005074 ADDOP(c, YIELD_FROM);
5075 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005076 case Compare_kind:
5077 return compiler_compare(c, e);
5078 case Call_kind:
5079 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005080 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005081 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005082 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005083 case JoinedStr_kind:
5084 return compiler_joined_str(c, e);
5085 case FormattedValue_kind:
5086 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005087 /* The following exprs can be assignment targets. */
5088 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005089 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005090 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005091 case Load:
5092 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5093 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005094 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005095 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5096 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5098 break;
5099 case Del:
5100 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5101 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005102 }
5103 break;
5104 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005105 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005106 case Starred_kind:
5107 switch (e->v.Starred.ctx) {
5108 case Store:
5109 /* In all legitimate cases, the Starred node was already replaced
5110 * by compiler_list/compiler_tuple. XXX: is that okay? */
5111 return compiler_error(c,
5112 "starred assignment target must be in a list or tuple");
5113 default:
5114 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005115 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005116 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005117 break;
5118 case Slice_kind:
5119 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 case Name_kind:
5121 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5122 /* child nodes of List and Tuple will have expr_context set */
5123 case List_kind:
5124 return compiler_list(c, e);
5125 case Tuple_kind:
5126 return compiler_tuple(c, e);
5127 }
5128 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005129}
5130
5131static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005132compiler_visit_expr(struct compiler *c, expr_ty e)
5133{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005134 int old_lineno = c->u->u_lineno;
5135 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005136 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005137 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005138 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005139 c->u->u_col_offset = old_col_offset;
5140 return res;
5141}
5142
5143static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005144compiler_augassign(struct compiler *c, stmt_ty s)
5145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005146 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005147 expr_ty e = s->v.AugAssign.target;
5148
5149 int old_lineno = c->u->u_lineno;
5150 int old_col_offset = c->u->u_col_offset;
5151 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005153 switch (e->kind) {
5154 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005155 VISIT(c, expr, e->v.Attribute.value);
5156 ADDOP(c, DUP_TOP);
5157 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005158 break;
5159 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005160 VISIT(c, expr, e->v.Subscript.value);
5161 VISIT(c, expr, e->v.Subscript.slice);
5162 ADDOP(c, DUP_TOP_TWO);
5163 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005164 break;
5165 case Name_kind:
5166 if (!compiler_nameop(c, e->v.Name.id, Load))
5167 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005168 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005169 default:
5170 PyErr_Format(PyExc_SystemError,
5171 "invalid node type (%d) for augmented assignment",
5172 e->kind);
5173 return 0;
5174 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005175
5176 c->u->u_lineno = old_lineno;
5177 c->u->u_col_offset = old_col_offset;
5178
5179 VISIT(c, expr, s->v.AugAssign.value);
5180 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5181
5182 SET_LOC(c, e);
5183
5184 switch (e->kind) {
5185 case Attribute_kind:
5186 ADDOP(c, ROT_TWO);
5187 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5188 break;
5189 case Subscript_kind:
5190 ADDOP(c, ROT_THREE);
5191 ADDOP(c, STORE_SUBSCR);
5192 break;
5193 case Name_kind:
5194 return compiler_nameop(c, e->v.Name.id, Store);
5195 default:
5196 Py_UNREACHABLE();
5197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005198 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005199}
5200
5201static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005202check_ann_expr(struct compiler *c, expr_ty e)
5203{
5204 VISIT(c, expr, e);
5205 ADDOP(c, POP_TOP);
5206 return 1;
5207}
5208
5209static int
5210check_annotation(struct compiler *c, stmt_ty s)
5211{
5212 /* Annotations are only evaluated in a module or class. */
5213 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5214 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5215 return check_ann_expr(c, s->v.AnnAssign.annotation);
5216 }
5217 return 1;
5218}
5219
5220static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005221check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005222{
5223 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005224 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005225 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005226 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005227 return 0;
5228 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005229 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5230 return 0;
5231 }
5232 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5233 return 0;
5234 }
5235 return 1;
5236 case Tuple_kind: {
5237 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005238 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005239 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005240 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005241 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005242 return 0;
5243 }
5244 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005245 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005246 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005247 default:
5248 return check_ann_expr(c, e);
5249 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005250}
5251
5252static int
5253compiler_annassign(struct compiler *c, stmt_ty s)
5254{
5255 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005256 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005257
5258 assert(s->kind == AnnAssign_kind);
5259
5260 /* We perform the actual assignment first. */
5261 if (s->v.AnnAssign.value) {
5262 VISIT(c, expr, s->v.AnnAssign.value);
5263 VISIT(c, expr, targ);
5264 }
5265 switch (targ->kind) {
5266 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005267 if (forbidden_name(c, targ->v.Name.id, Store))
5268 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005269 /* If we have a simple name in a module or class, store annotation. */
5270 if (s->v.AnnAssign.simple &&
5271 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5272 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005273 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005274 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005275 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005276 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005277 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005278 }
5279 break;
5280 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005281 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5282 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005283 if (!s->v.AnnAssign.value &&
5284 !check_ann_expr(c, targ->v.Attribute.value)) {
5285 return 0;
5286 }
5287 break;
5288 case Subscript_kind:
5289 if (!s->v.AnnAssign.value &&
5290 (!check_ann_expr(c, targ->v.Subscript.value) ||
5291 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5292 return 0;
5293 }
5294 break;
5295 default:
5296 PyErr_Format(PyExc_SystemError,
5297 "invalid node type (%d) for annotated assignment",
5298 targ->kind);
5299 return 0;
5300 }
5301 /* Annotation is evaluated last. */
5302 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5303 return 0;
5304 }
5305 return 1;
5306}
5307
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005308/* Raises a SyntaxError and returns 0.
5309 If something goes wrong, a different exception may be raised.
5310*/
5311
5312static int
5313compiler_error(struct compiler *c, const char *errstr)
5314{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005315 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005316 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005317
Victor Stinner14e461d2013-08-26 22:28:21 +02005318 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005319 if (!loc) {
5320 Py_INCREF(Py_None);
5321 loc = Py_None;
5322 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005323 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005324 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005325 if (!u)
5326 goto exit;
5327 v = Py_BuildValue("(zO)", errstr, u);
5328 if (!v)
5329 goto exit;
5330 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005331 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005332 Py_DECREF(loc);
5333 Py_XDECREF(u);
5334 Py_XDECREF(v);
5335 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005336}
5337
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005338/* Emits a SyntaxWarning and returns 1 on success.
5339 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5340 and returns 0.
5341*/
5342static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005343compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005344{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005345 va_list vargs;
5346#ifdef HAVE_STDARG_PROTOTYPES
5347 va_start(vargs, format);
5348#else
5349 va_start(vargs);
5350#endif
5351 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5352 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005353 if (msg == NULL) {
5354 return 0;
5355 }
5356 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5357 c->u->u_lineno, NULL, NULL) < 0)
5358 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005359 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005360 /* Replace the SyntaxWarning exception with a SyntaxError
5361 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005362 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005363 assert(PyUnicode_AsUTF8(msg) != NULL);
5364 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005365 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005366 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005367 return 0;
5368 }
5369 Py_DECREF(msg);
5370 return 1;
5371}
5372
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005373static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005374compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005375{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005376 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005377 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005378
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005379 if (ctx == Load) {
5380 if (!check_subscripter(c, e->v.Subscript.value)) {
5381 return 0;
5382 }
5383 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5384 return 0;
5385 }
5386 }
5387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005388 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005390 case Store: op = STORE_SUBSCR; break;
5391 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005393 assert(op);
5394 VISIT(c, expr, e->v.Subscript.value);
5395 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005396 ADDOP(c, op);
5397 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005398}
5399
5400static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005401compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005403 int n = 2;
5404 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005406 /* only handles the cases where BUILD_SLICE is emitted */
5407 if (s->v.Slice.lower) {
5408 VISIT(c, expr, s->v.Slice.lower);
5409 }
5410 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005411 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005412 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005414 if (s->v.Slice.upper) {
5415 VISIT(c, expr, s->v.Slice.upper);
5416 }
5417 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005418 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005419 }
5420
5421 if (s->v.Slice.step) {
5422 n++;
5423 VISIT(c, expr, s->v.Slice.step);
5424 }
5425 ADDOP_I(c, BUILD_SLICE, n);
5426 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005427}
5428
Thomas Wouters89f507f2006-12-13 04:49:30 +00005429/* End of the compiler section, beginning of the assembler section */
5430
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005431/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005432 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005433
5434 XXX must handle implicit jumps from one block to next
5435*/
5436
Thomas Wouters89f507f2006-12-13 04:49:30 +00005437struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005438 PyObject *a_bytecode; /* string containing bytecode */
5439 int a_offset; /* offset into bytecode */
5440 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005441 PyObject *a_lnotab; /* string containing lnotab */
5442 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005443 int a_prevlineno; /* lineno of last emitted line in line table */
5444 int a_lineno; /* lineno of last emitted instruction */
5445 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005446 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005447};
5448
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005449Py_LOCAL_INLINE(void)
5450stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005451{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005452 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005453 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005454 assert(b->b_startdepth < 0);
5455 b->b_startdepth = depth;
5456 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005457 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005458}
5459
5460/* Find the flow path that needs the largest stack. We assume that
5461 * cycles in the flow graph have no net effect on the stack depth.
5462 */
5463static int
5464stackdepth(struct compiler *c)
5465{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005466 basicblock *b, *entryblock = NULL;
5467 basicblock **stack, **sp;
5468 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005469 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005470 b->b_startdepth = INT_MIN;
5471 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005472 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005473 }
5474 if (!entryblock)
5475 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005476 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5477 if (!stack) {
5478 PyErr_NoMemory();
5479 return -1;
5480 }
5481
5482 sp = stack;
5483 stackdepth_push(&sp, entryblock, 0);
5484 while (sp != stack) {
5485 b = *--sp;
5486 int depth = b->b_startdepth;
5487 assert(depth >= 0);
5488 basicblock *next = b->b_next;
5489 for (int i = 0; i < b->b_iused; i++) {
5490 struct instr *instr = &b->b_instr[i];
5491 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5492 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005493 _Py_FatalErrorFormat(__func__,
5494 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005495 }
5496 int new_depth = depth + effect;
5497 if (new_depth > maxdepth) {
5498 maxdepth = new_depth;
5499 }
5500 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005501 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005502 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5503 assert(effect != PY_INVALID_STACK_EFFECT);
5504 int target_depth = depth + effect;
5505 if (target_depth > maxdepth) {
5506 maxdepth = target_depth;
5507 }
5508 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005509 stackdepth_push(&sp, instr->i_target, target_depth);
5510 }
5511 depth = new_depth;
5512 if (instr->i_opcode == JUMP_ABSOLUTE ||
5513 instr->i_opcode == JUMP_FORWARD ||
5514 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005515 instr->i_opcode == RAISE_VARARGS ||
5516 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005517 {
5518 /* remaining code is dead */
5519 next = NULL;
5520 break;
5521 }
5522 }
5523 if (next != NULL) {
5524 stackdepth_push(&sp, next, depth);
5525 }
5526 }
5527 PyObject_Free(stack);
5528 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005529}
5530
5531static int
5532assemble_init(struct assembler *a, int nblocks, int firstlineno)
5533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005534 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005535 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005536 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005538 if (a->a_bytecode == NULL) {
5539 goto error;
5540 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005541 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005542 if (a->a_lnotab == NULL) {
5543 goto error;
5544 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005545 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005546 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005547 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005548 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005549 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005550error:
5551 Py_XDECREF(a->a_bytecode);
5552 Py_XDECREF(a->a_lnotab);
5553 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005554}
5555
5556static void
5557assemble_free(struct assembler *a)
5558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005559 Py_XDECREF(a->a_bytecode);
5560 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005561}
5562
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005563static int
5564blocksize(basicblock *b)
5565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005566 int i;
5567 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005569 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005570 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005571 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005572}
5573
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005574static int
Mark Shannon877df852020-11-12 09:43:29 +00005575assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005576{
Mark Shannon877df852020-11-12 09:43:29 +00005577 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005578 if (a->a_lnotab_off + 2 >= len) {
5579 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5580 return 0;
5581 }
Mark Shannon877df852020-11-12 09:43:29 +00005582 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005583 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005585 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005586 *lnotab++ = bdelta;
5587 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005588 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005589}
5590
Mark Shannon877df852020-11-12 09:43:29 +00005591/* Appends a range to the end of the line number table. See
5592 * Objects/lnotab_notes.txt for the description of the line number table. */
5593
5594static int
5595assemble_line_range(struct assembler *a)
5596{
5597 int ldelta, bdelta;
5598 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5599 if (bdelta == 0) {
5600 return 1;
5601 }
5602 if (a->a_lineno < 0) {
5603 ldelta = -128;
5604 }
5605 else {
5606 ldelta = a->a_lineno - a->a_prevlineno;
5607 a->a_prevlineno = a->a_lineno;
5608 while (ldelta > 127) {
5609 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5610 return 0;
5611 }
5612 ldelta -= 127;
5613 }
5614 while (ldelta < -127) {
5615 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5616 return 0;
5617 }
5618 ldelta += 127;
5619 }
5620 }
5621 assert(-128 <= ldelta && ldelta < 128);
5622 while (bdelta > 254) {
5623 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5624 return 0;
5625 }
5626 ldelta = a->a_lineno < 0 ? -128 : 0;
5627 bdelta -= 254;
5628 }
5629 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5630 return 0;
5631 }
5632 a->a_lineno_start = a->a_offset;
5633 return 1;
5634}
5635
5636static int
5637assemble_lnotab(struct assembler *a, struct instr *i)
5638{
5639 if (i->i_lineno == a->a_lineno) {
5640 return 1;
5641 }
5642 if (!assemble_line_range(a)) {
5643 return 0;
5644 }
5645 a->a_lineno = i->i_lineno;
5646 return 1;
5647}
5648
5649
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005650/* assemble_emit()
5651 Extend the bytecode with a new instruction.
5652 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005653*/
5654
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005655static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005656assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005657{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005658 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005659 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005660 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005661
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005662 arg = i->i_oparg;
5663 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005664 if (i->i_lineno && !assemble_lnotab(a, i))
5665 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005666 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 if (len > PY_SSIZE_T_MAX / 2)
5668 return 0;
5669 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5670 return 0;
5671 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005672 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005673 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005674 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005675 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005676}
5677
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005678static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005679assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005681 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005682 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005683 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005685 /* Compute the size of each block and fixup jump args.
5686 Replace block pointer with position in bytecode. */
5687 do {
5688 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005689 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 bsize = blocksize(b);
5691 b->b_offset = totsize;
5692 totsize += bsize;
5693 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005694 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005695 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5696 bsize = b->b_offset;
5697 for (i = 0; i < b->b_iused; i++) {
5698 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005699 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005700 /* Relative jumps are computed relative to
5701 the instruction pointer after fetching
5702 the jump instruction.
5703 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005704 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005705 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005706 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005707 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005708 instr->i_oparg -= bsize;
5709 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005710 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005711 if (instrsize(instr->i_oparg) != isize) {
5712 extended_arg_recompile = 1;
5713 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005714 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005715 }
5716 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005718 /* XXX: This is an awful hack that could hurt performance, but
5719 on the bright side it should work until we come up
5720 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005722 The issue is that in the first loop blocksize() is called
5723 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005724 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005725 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 So we loop until we stop seeing new EXTENDED_ARGs.
5728 The only EXTENDED_ARGs that could be popping up are
5729 ones in jump instructions. So this should converge
5730 fairly quickly.
5731 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005732 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005733}
5734
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005735static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005736dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005739 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005741 tuple = PyTuple_New(size);
5742 if (tuple == NULL)
5743 return NULL;
5744 while (PyDict_Next(dict, &pos, &k, &v)) {
5745 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005746 Py_INCREF(k);
5747 assert((i - offset) < size);
5748 assert((i - offset) >= 0);
5749 PyTuple_SET_ITEM(tuple, i - offset, k);
5750 }
5751 return tuple;
5752}
5753
5754static PyObject *
5755consts_dict_keys_inorder(PyObject *dict)
5756{
5757 PyObject *consts, *k, *v;
5758 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5759
5760 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5761 if (consts == NULL)
5762 return NULL;
5763 while (PyDict_Next(dict, &pos, &k, &v)) {
5764 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005765 /* The keys of the dictionary can be tuples wrapping a contant.
5766 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5767 * the object we want is always second. */
5768 if (PyTuple_CheckExact(k)) {
5769 k = PyTuple_GET_ITEM(k, 1);
5770 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005771 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005772 assert(i < size);
5773 assert(i >= 0);
5774 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005775 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005776 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005777}
5778
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005779static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005780compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005782 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005783 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005784 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005785 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005786 if (ste->ste_nested)
5787 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005788 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005789 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005790 if (!ste->ste_generator && ste->ste_coroutine)
5791 flags |= CO_COROUTINE;
5792 if (ste->ste_generator && ste->ste_coroutine)
5793 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005794 if (ste->ste_varargs)
5795 flags |= CO_VARARGS;
5796 if (ste->ste_varkeywords)
5797 flags |= CO_VARKEYWORDS;
5798 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005800 /* (Only) inherit compilerflags in PyCF_MASK */
5801 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005802
Pablo Galindo90235812020-03-15 04:29:22 +00005803 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005804 ste->ste_coroutine &&
5805 !ste->ste_generator) {
5806 flags |= CO_COROUTINE;
5807 }
5808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005809 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005810}
5811
INADA Naokic2e16072018-11-26 21:23:22 +09005812// Merge *tuple* with constant cache.
5813// Unlike merge_consts_recursive(), this function doesn't work recursively.
5814static int
5815merge_const_tuple(struct compiler *c, PyObject **tuple)
5816{
5817 assert(PyTuple_CheckExact(*tuple));
5818
5819 PyObject *key = _PyCode_ConstantKey(*tuple);
5820 if (key == NULL) {
5821 return 0;
5822 }
5823
5824 // t is borrowed reference
5825 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5826 Py_DECREF(key);
5827 if (t == NULL) {
5828 return 0;
5829 }
5830 if (t == key) { // tuple is new constant.
5831 return 1;
5832 }
5833
5834 PyObject *u = PyTuple_GET_ITEM(t, 1);
5835 Py_INCREF(u);
5836 Py_DECREF(*tuple);
5837 *tuple = u;
5838 return 1;
5839}
5840
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005841static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005842makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005844 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005845 PyObject *names = NULL;
5846 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005847 PyObject *name = NULL;
5848 PyObject *freevars = NULL;
5849 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005850 Py_ssize_t nlocals;
5851 int nlocals_int;
5852 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005853 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005855 names = dict_keys_inorder(c->u->u_names, 0);
5856 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005857 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005858 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005859 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005860 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5861 if (!cellvars)
5862 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005863 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 if (!freevars)
5865 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005866
INADA Naokic2e16072018-11-26 21:23:22 +09005867 if (!merge_const_tuple(c, &names) ||
5868 !merge_const_tuple(c, &varnames) ||
5869 !merge_const_tuple(c, &cellvars) ||
5870 !merge_const_tuple(c, &freevars))
5871 {
5872 goto error;
5873 }
5874
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005875 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005876 assert(nlocals < INT_MAX);
5877 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005879 flags = compute_code_flags(c);
5880 if (flags < 0)
5881 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005882
Mark Shannon6e8128f2020-07-30 10:03:00 +01005883 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5884 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005885 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005886 }
INADA Naokic2e16072018-11-26 21:23:22 +09005887 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005888 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005889 goto error;
5890 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005892 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005893 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005894 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005895 maxdepth = stackdepth(c);
5896 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005897 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005898 goto error;
5899 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005900 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005901 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005902 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005903 varnames, freevars, cellvars, c->c_filename,
5904 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005905 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005906 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005907 Py_XDECREF(names);
5908 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005909 Py_XDECREF(name);
5910 Py_XDECREF(freevars);
5911 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005912 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005913}
5914
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005915
5916/* For debugging purposes only */
5917#if 0
5918static void
5919dump_instr(const struct instr *i)
5920{
Mark Shannon582aaf12020-08-04 17:30:11 +01005921 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5922 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005923 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005925 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005926 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005927 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005928 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005929 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5930 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005931}
5932
5933static void
5934dump_basicblock(const basicblock *b)
5935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005936 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005937 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5938 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005939 if (b->b_instr) {
5940 int i;
5941 for (i = 0; i < b->b_iused; i++) {
5942 fprintf(stderr, " [%02d] ", i);
5943 dump_instr(b->b_instr + i);
5944 }
5945 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005946}
5947#endif
5948
Mark Shannon6e8128f2020-07-30 10:03:00 +01005949static int
5950optimize_cfg(struct assembler *a, PyObject *consts);
5951
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005952static PyCodeObject *
5953assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005955 basicblock *b, *entryblock;
5956 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005957 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005958 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005959 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005961 /* Make sure every block that falls off the end returns None.
5962 XXX NEXT_BLOCK() isn't quite right, because if the last
5963 block ends with a jump or return b_next shouldn't set.
5964 */
5965 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005966 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005967 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005968 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 ADDOP(c, RETURN_VALUE);
5970 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005972 nblocks = 0;
5973 entryblock = NULL;
5974 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5975 nblocks++;
5976 entryblock = b;
5977 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005979 /* Set firstlineno if it wasn't explicitly set. */
5980 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005981 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005982 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005983 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005984 c->u->u_firstlineno = 1;
5985 }
5986 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5987 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005988 a.a_entry = entryblock;
5989 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005990
Mark Shannon6e8128f2020-07-30 10:03:00 +01005991 consts = consts_dict_keys_inorder(c->u->u_consts);
5992 if (consts == NULL) {
5993 goto error;
5994 }
5995 if (optimize_cfg(&a, consts)) {
5996 goto error;
5997 }
5998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005999 /* Can't modify the bytecode after computing jump offsets. */
6000 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00006001
Mark Shannoncc75ab72020-11-12 19:49:33 +00006002 /* Emit code. */
6003 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006004 for (j = 0; j < b->b_iused; j++)
6005 if (!assemble_emit(&a, &b->b_instr[j]))
6006 goto error;
6007 }
Mark Shannon877df852020-11-12 09:43:29 +00006008 if (!assemble_line_range(&a)) {
6009 return 0;
6010 }
6011 /* Emit sentinel at end of line number table */
6012 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
6013 goto error;
6014 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00006015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006016 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
6017 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03006018 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006019 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006020
Mark Shannon6e8128f2020-07-30 10:03:00 +01006021 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006022 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006023 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00006024 assemble_free(&a);
6025 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00006026}
Georg Brandl8334fd92010-12-04 10:26:46 +00006027
6028#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07006029PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006030PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6031 PyArena *arena)
6032{
6033 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6034}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006035
6036
6037/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6038 with LOAD_CONST (c1, c2, ... cn).
6039 The consts table must still be in list form so that the
6040 new constant (c1, c2, ... cn) can be appended.
6041 Called with codestr pointing to the first LOAD_CONST.
6042*/
6043static int
6044fold_tuple_on_constants(struct instr *inst,
6045 int n, PyObject *consts)
6046{
6047 /* Pre-conditions */
6048 assert(PyList_CheckExact(consts));
6049 assert(inst[n].i_opcode == BUILD_TUPLE);
6050 assert(inst[n].i_oparg == n);
6051
6052 for (int i = 0; i < n; i++) {
6053 if (inst[i].i_opcode != LOAD_CONST) {
6054 return 0;
6055 }
6056 }
6057
6058 /* Buildup new tuple of constants */
6059 PyObject *newconst = PyTuple_New(n);
6060 if (newconst == NULL) {
6061 return -1;
6062 }
6063 for (int i = 0; i < n; i++) {
6064 int arg = inst[i].i_oparg;
6065 PyObject *constant = PyList_GET_ITEM(consts, arg);
6066 Py_INCREF(constant);
6067 PyTuple_SET_ITEM(newconst, i, constant);
6068 }
6069 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006070 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006071 Py_DECREF(newconst);
6072 PyErr_SetString(PyExc_OverflowError, "too many constants");
6073 return -1;
6074 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006075 if (PyList_Append(consts, newconst)) {
6076 Py_DECREF(newconst);
6077 return -1;
6078 }
6079 Py_DECREF(newconst);
6080 for (int i = 0; i < n; i++) {
6081 inst[i].i_opcode = NOP;
6082 }
6083 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006084 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006085 return 0;
6086}
6087
Mark Shannoncc75ab72020-11-12 19:49:33 +00006088/* Maximum size of basic block that should be copied in optimizer */
6089#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006090
6091/* Optimization */
6092static int
6093optimize_basic_block(basicblock *bb, PyObject *consts)
6094{
6095 assert(PyList_CheckExact(consts));
6096 struct instr nop;
6097 nop.i_opcode = NOP;
6098 struct instr *target;
6099 int lineno;
6100 for (int i = 0; i < bb->b_iused; i++) {
6101 struct instr *inst = &bb->b_instr[i];
6102 int oparg = inst->i_oparg;
6103 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006104 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006105 /* Skip over empty basic blocks. */
6106 while (inst->i_target->b_iused == 0) {
6107 inst->i_target = inst->i_target->b_next;
6108 }
6109 target = &inst->i_target->b_instr[0];
6110 }
6111 else {
6112 target = &nop;
6113 }
6114 switch (inst->i_opcode) {
6115 /* Skip over LOAD_CONST trueconst
6116 POP_JUMP_IF_FALSE xx. This improves
6117 "while 1" performance. */
6118 case LOAD_CONST:
6119 if (nextop != POP_JUMP_IF_FALSE) {
6120 break;
6121 }
6122 PyObject* cnt = PyList_GET_ITEM(consts, oparg);
6123 int is_true = PyObject_IsTrue(cnt);
6124 if (is_true == -1) {
6125 goto error;
6126 }
6127 if (is_true == 1) {
6128 inst->i_opcode = NOP;
6129 bb->b_instr[i+1].i_opcode = NOP;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006130 }
6131 break;
6132
6133 /* Try to fold tuples of constants.
6134 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6135 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6136 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6137 case BUILD_TUPLE:
6138 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6139 switch(oparg) {
6140 case 1:
6141 inst->i_opcode = NOP;
6142 bb->b_instr[i+1].i_opcode = NOP;
6143 break;
6144 case 2:
6145 inst->i_opcode = ROT_TWO;
6146 bb->b_instr[i+1].i_opcode = NOP;
6147 break;
6148 case 3:
6149 inst->i_opcode = ROT_THREE;
6150 bb->b_instr[i+1].i_opcode = ROT_TWO;
6151 }
6152 break;
6153 }
6154 if (i >= oparg) {
6155 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6156 goto error;
6157 }
6158 }
6159 break;
6160
6161 /* Simplify conditional jump to conditional jump where the
6162 result of the first test implies the success of a similar
6163 test or the failure of the opposite test.
6164 Arises in code like:
6165 "a and b or c"
6166 "(a and b) and c"
6167 "(a or b) or c"
6168 "(a or b) and c"
6169 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6170 --> x:JUMP_IF_FALSE_OR_POP z
6171 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6172 --> x:POP_JUMP_IF_FALSE y+1
6173 where y+1 is the instruction following the second test.
6174 */
6175 case JUMP_IF_FALSE_OR_POP:
6176 switch(target->i_opcode) {
6177 case POP_JUMP_IF_FALSE:
6178 *inst = *target;
6179 break;
6180 case JUMP_ABSOLUTE:
6181 case JUMP_FORWARD:
6182 case JUMP_IF_FALSE_OR_POP:
6183 inst->i_target = target->i_target;
6184 break;
6185 case JUMP_IF_TRUE_OR_POP:
6186 assert (inst->i_target->b_iused == 1);
6187 inst->i_opcode = POP_JUMP_IF_FALSE;
6188 inst->i_target = inst->i_target->b_next;
6189 break;
6190 }
6191 break;
6192
6193 case JUMP_IF_TRUE_OR_POP:
6194 switch(target->i_opcode) {
6195 case POP_JUMP_IF_TRUE:
6196 *inst = *target;
6197 break;
6198 case JUMP_ABSOLUTE:
6199 case JUMP_FORWARD:
6200 case JUMP_IF_TRUE_OR_POP:
6201 inst->i_target = target->i_target;
6202 break;
6203 case JUMP_IF_FALSE_OR_POP:
6204 assert (inst->i_target->b_iused == 1);
6205 inst->i_opcode = POP_JUMP_IF_TRUE;
6206 inst->i_target = inst->i_target->b_next;
6207 break;
6208 }
6209 break;
6210
6211 case POP_JUMP_IF_FALSE:
6212 switch(target->i_opcode) {
6213 case JUMP_ABSOLUTE:
6214 case JUMP_FORWARD:
6215 inst->i_target = target->i_target;
6216 break;
6217 }
6218 break;
6219
6220 case POP_JUMP_IF_TRUE:
6221 switch(target->i_opcode) {
6222 case JUMP_ABSOLUTE:
6223 case JUMP_FORWARD:
6224 inst->i_target = target->i_target;
6225 break;
6226 }
6227 break;
6228
6229 case JUMP_ABSOLUTE:
6230 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006231 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006232 switch(target->i_opcode) {
6233 case JUMP_FORWARD:
6234 inst->i_target = target->i_target;
6235 break;
6236 case JUMP_ABSOLUTE:
Mark Shannon6e8128f2020-07-30 10:03:00 +01006237 lineno = inst->i_lineno;
6238 *inst = *target;
6239 inst->i_lineno = lineno;
6240 break;
6241 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006242 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6243 basicblock *to_copy = inst->i_target;
6244 *inst = to_copy->b_instr[0];
6245 for (i = 1; i < to_copy->b_iused; i++) {
6246 int index = compiler_next_instr(bb);
6247 if (index < 0) {
6248 return -1;
6249 }
6250 bb->b_instr[index] = to_copy->b_instr[i];
6251 }
6252 bb->b_exit = 1;
6253 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006254 break;
6255 }
6256 }
6257 return 0;
6258error:
6259 return -1;
6260}
6261
6262
6263static void
6264clean_basic_block(basicblock *bb) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006265 /* Remove NOPs. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006266 int dest = 0;
Mark Shannon877df852020-11-12 09:43:29 +00006267 int prev_lineno = -1;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006268 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006269 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006270 if (bb->b_instr[src].i_opcode == NOP) {
6271 /* Eliminate no-op if it doesn't have a line number, or
6272 * if the next instruction has same line number or no line number, or
6273 * if the previous instruction had the same line number. */
6274 if (lineno < 0) {
6275 continue;
6276 }
6277 if (prev_lineno == lineno) {
6278 continue;
6279 }
6280 if (src < bb->b_iused - 1) {
6281 int next_lineno = bb->b_instr[src+1].i_lineno;
6282 if (next_lineno < 0 || next_lineno == lineno) {
6283 bb->b_instr[src+1].i_lineno = lineno;
6284 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006285 }
6286 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006287 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006288 if (dest != src) {
6289 bb->b_instr[dest] = bb->b_instr[src];
6290 }
6291 dest++;
6292 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006293 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006294 assert(dest <= bb->b_iused);
6295 bb->b_iused = dest;
6296}
6297
Mark Shannoncc75ab72020-11-12 19:49:33 +00006298static void
6299normalise_basic_block(basicblock *bb) {
6300 /* Remove any code following a return or re-raise,
6301 and mark those blocks as exit and/or nofallthrough. */
6302 for (int i = 0; i < bb->b_iused; i++) {
6303 switch(bb->b_instr[i].i_opcode) {
6304 case RETURN_VALUE:
6305 case RAISE_VARARGS:
6306 case RERAISE:
6307 bb->b_iused = i+1;
6308 bb->b_exit = 1;
6309 bb->b_nofallthrough = 1;
6310 return;
6311 case JUMP_ABSOLUTE:
6312 case JUMP_FORWARD:
6313 bb->b_iused = i+1;
6314 bb->b_nofallthrough = 1;
6315 return;
6316 }
6317 }
6318}
6319
6320
6321
Mark Shannon6e8128f2020-07-30 10:03:00 +01006322static int
6323mark_reachable(struct assembler *a) {
6324 basicblock **stack, **sp;
6325 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6326 if (stack == NULL) {
6327 return -1;
6328 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006329 a->a_entry->b_reachable = 1;
6330 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006331 while (sp > stack) {
6332 basicblock *b = *(--sp);
Mark Shannoncc75ab72020-11-12 19:49:33 +00006333 if (b->b_next && !b->b_nofallthrough && b->b_next->b_reachable == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006334 b->b_next->b_reachable = 1;
6335 *sp++ = b->b_next;
6336 }
6337 for (int i = 0; i < b->b_iused; i++) {
6338 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006339 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006340 target = b->b_instr[i].i_target;
6341 if (target->b_reachable == 0) {
6342 target->b_reachable = 1;
6343 *sp++ = target;
6344 }
6345 }
6346 }
6347 }
6348 PyObject_Free(stack);
6349 return 0;
6350}
6351
6352
6353/* Perform basic peephole optimizations on a control flow graph.
6354 The consts object should still be in list form to allow new constants
6355 to be appended.
6356
6357 All transformations keep the code size the same or smaller.
6358 For those that reduce size, the gaps are initially filled with
6359 NOPs. Later those NOPs are removed.
6360*/
6361
6362static int
6363optimize_cfg(struct assembler *a, PyObject *consts)
6364{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006365 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6366 normalise_basic_block(b);
6367 }
6368 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6369 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006370 return -1;
6371 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006372 clean_basic_block(b);
6373 assert(b->b_reachable == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006374 }
6375 if (mark_reachable(a)) {
6376 return -1;
6377 }
6378 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006379 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6380 if (b->b_reachable == 0) {
6381 b->b_iused = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006382 }
6383 }
6384 return 0;
6385}
6386
6387/* Retained for API compatibility.
6388 * Optimization is now done in optimize_cfg */
6389
6390PyObject *
6391PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6392 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6393{
6394 Py_INCREF(code);
6395 return code;
6396}
6397