blob: cf5c639feab7f4abc2073834b9d8db2133a4298c [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;
INADA Naokic2e16072018-11-26 21:23:22 +0900196 PyObject *c_const_cache; /* Python dict holding all constants,
197 including names tuple */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 struct compiler_unit *u; /* compiler state for current block */
199 PyObject *c_stack; /* Python list holding compiler_unit ptrs */
200 PyArena *c_arena; /* pointer to memory allocation arena */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201};
202
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100203static int compiler_enter_scope(struct compiler *, identifier, int, void *, int);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000204static void compiler_free(struct compiler *);
205static basicblock *compiler_new_block(struct compiler *);
Andy Lester76d58772020-03-10 21:18:12 -0500206static int compiler_next_instr(basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000207static int compiler_addop(struct compiler *, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +0100208static int compiler_addop_i(struct compiler *, int, Py_ssize_t);
Mark Shannon582aaf12020-08-04 17:30:11 +0100209static int compiler_addop_j(struct compiler *, int, basicblock *);
Mark Shannon127dde52021-01-04 18:06:55 +0000210static int compiler_addop_j_noline(struct compiler *, int, basicblock *);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000211static int compiler_error(struct compiler *, const char *);
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200212static int compiler_warn(struct compiler *, const char *, ...);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000213static int compiler_nameop(struct compiler *, identifier, expr_context_ty);
214
215static PyCodeObject *compiler_mod(struct compiler *, mod_ty);
216static int compiler_visit_stmt(struct compiler *, stmt_ty);
217static int compiler_visit_keyword(struct compiler *, keyword_ty);
218static int compiler_visit_expr(struct compiler *, expr_ty);
219static int compiler_augassign(struct compiler *, stmt_ty);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700220static int compiler_annassign(struct compiler *, stmt_ty);
Serhiy Storchaka13d52c22020-03-10 18:52:34 +0200221static int compiler_subscript(struct compiler *, expr_ty);
222static int compiler_slice(struct compiler *, expr_ty);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000223
Andy Lester76d58772020-03-10 21:18:12 -0500224static int inplace_binop(operator_ty);
Pablo Galindoa5634c42020-09-16 19:42:00 +0100225static int are_all_items_const(asdl_expr_seq *, Py_ssize_t, Py_ssize_t);
Mark Shannon8473cf82020-12-15 11:07:50 +0000226
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000227
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -0500228static int compiler_with(struct compiler *, stmt_ty, int);
Yury Selivanov75445082015-05-11 22:57:16 -0400229static int compiler_async_with(struct compiler *, stmt_ty, int);
230static int compiler_async_for(struct compiler *, stmt_ty);
Victor Stinner976bb402016-03-23 11:36:19 +0100231static int compiler_call_helper(struct compiler *c, int n,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100232 asdl_expr_seq *args,
233 asdl_keyword_seq *keywords);
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500234static int compiler_try_except(struct compiler *, stmt_ty);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400235static int compiler_set_qualname(struct compiler *);
Guido van Rossumc2e20742006-02-27 22:32:47 +0000236
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700237static int compiler_sync_comprehension_generator(
238 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100239 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200240 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700241 expr_ty elt, expr_ty val, int type);
242
243static int compiler_async_comprehension_generator(
244 struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +0100245 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +0200246 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -0700247 expr_ty elt, expr_ty val, int type);
248
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000249static PyCodeObject *assemble(struct compiler *, int addNone);
Mark Shannon332cd5e2018-01-30 00:41:04 +0000250static PyObject *__doc__, *__annotations__;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000251
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400252#define CAPSULE_NAME "compile.c compiler unit"
Benjamin Petersonb173f782009-05-05 22:31:58 +0000253
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000254PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000255_Py_Mangle(PyObject *privateobj, PyObject *ident)
Michael W. Hudson60934622004-08-12 17:56:29 +0000256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 /* Name mangling: __private becomes _classname__private.
258 This is independent from how the name is used. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200259 PyObject *result;
260 size_t nlen, plen, ipriv;
261 Py_UCS4 maxchar;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 if (privateobj == NULL || !PyUnicode_Check(privateobj) ||
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200263 PyUnicode_READ_CHAR(ident, 0) != '_' ||
264 PyUnicode_READ_CHAR(ident, 1) != '_') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 Py_INCREF(ident);
266 return ident;
267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200268 nlen = PyUnicode_GET_LENGTH(ident);
269 plen = PyUnicode_GET_LENGTH(privateobj);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* Don't mangle __id__ or names with dots.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 The only time a name with a dot can occur is when
273 we are compiling an import statement that has a
274 package name.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 TODO(jhylton): Decide whether we want to support
277 mangling of the module name, e.g. __M.X.
278 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200279 if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' &&
280 PyUnicode_READ_CHAR(ident, nlen-2) == '_') ||
281 PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Py_INCREF(ident);
283 return ident; /* Don't mangle __whatever__ */
284 }
285 /* Strip leading underscores from class name */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200286 ipriv = 0;
287 while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_')
288 ipriv++;
289 if (ipriv == plen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 Py_INCREF(ident);
291 return ident; /* Don't mangle if class is just underscores */
292 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200293 plen -= ipriv;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000294
Antoine Pitrou55bff892013-04-06 21:21:04 +0200295 if (plen + nlen >= PY_SSIZE_T_MAX - 1) {
296 PyErr_SetString(PyExc_OverflowError,
297 "private identifier too large to be mangled");
298 return NULL;
299 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200301 maxchar = PyUnicode_MAX_CHAR_VALUE(ident);
302 if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar)
303 maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj);
304
305 result = PyUnicode_New(1 + nlen + plen, maxchar);
306 if (!result)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200308 /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */
309 PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_');
Victor Stinner6c7a52a2011-09-28 21:39:17 +0200310 if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) {
311 Py_DECREF(result);
312 return NULL;
313 }
314 if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) {
315 Py_DECREF(result);
316 return NULL;
317 }
Victor Stinner8f825062012-04-27 13:55:39 +0200318 assert(_PyUnicode_CheckConsistency(result, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200319 return result;
Michael W. Hudson60934622004-08-12 17:56:29 +0000320}
321
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000322static int
323compiler_init(struct compiler *c)
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 memset(c, 0, sizeof(struct compiler));
Guido van Rossumbea18cc2002-06-14 20:41:17 +0000326
INADA Naokic2e16072018-11-26 21:23:22 +0900327 c->c_const_cache = PyDict_New();
328 if (!c->c_const_cache) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 return 0;
INADA Naokic2e16072018-11-26 21:23:22 +0900330 }
331
332 c->c_stack = PyList_New(0);
333 if (!c->c_stack) {
334 Py_CLEAR(c->c_const_cache);
335 return 0;
336 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000339}
340
341PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200342PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags,
343 int optimize, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 struct compiler c;
346 PyCodeObject *co = NULL;
Victor Stinner37d66d72019-06-13 02:16:41 +0200347 PyCompilerFlags local_flags = _PyCompilerFlags_INIT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 int merged;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 if (!__doc__) {
351 __doc__ = PyUnicode_InternFromString("__doc__");
352 if (!__doc__)
353 return NULL;
354 }
Mark Shannon332cd5e2018-01-30 00:41:04 +0000355 if (!__annotations__) {
356 __annotations__ = PyUnicode_InternFromString("__annotations__");
357 if (!__annotations__)
358 return NULL;
359 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (!compiler_init(&c))
361 return NULL;
Victor Stinner14e461d2013-08-26 22:28:21 +0200362 Py_INCREF(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 c.c_filename = filename;
364 c.c_arena = arena;
Victor Stinner14e461d2013-08-26 22:28:21 +0200365 c.c_future = PyFuture_FromASTObject(mod, filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (c.c_future == NULL)
367 goto finally;
368 if (!flags) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 flags = &local_flags;
370 }
371 merged = c.c_future->ff_features | flags->cf_flags;
372 c.c_future->ff_features = merged;
373 flags->cf_flags = merged;
374 c.c_flags = flags;
Victor Stinnerda7933e2020-04-13 03:04:28 +0200375 c.c_optimize = (optimize == -1) ? _Py_GetConfig()->optimization_level : optimize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 c.c_nestlevel = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000377
Pablo Galindod112c602020-03-18 23:02:09 +0000378 _PyASTOptimizeState state;
379 state.optimize = c.c_optimize;
380 state.ff_features = merged;
381
382 if (!_PyAST_Optimize(mod, arena, &state)) {
INADA Naoki7ea143a2017-12-14 16:47:20 +0900383 goto finally;
384 }
385
Victor Stinner14e461d2013-08-26 22:28:21 +0200386 c.c_st = PySymtable_BuildObject(mod, filename, c.c_future);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (c.c_st == NULL) {
388 if (!PyErr_Occurred())
389 PyErr_SetString(PyExc_SystemError, "no symtable");
390 goto finally;
391 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 co = compiler_mod(&c, mod);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000394
Thomas Wouters1175c432006-02-27 22:49:54 +0000395 finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 compiler_free(&c);
397 assert(co || PyErr_Occurred());
398 return co;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000399}
400
401PyCodeObject *
Victor Stinner14e461d2013-08-26 22:28:21 +0200402PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags,
403 int optimize, PyArena *arena)
404{
405 PyObject *filename;
406 PyCodeObject *co;
407 filename = PyUnicode_DecodeFSDefault(filename_str);
408 if (filename == NULL)
409 return NULL;
410 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
411 Py_DECREF(filename);
412 return co;
413
414}
415
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000416static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000417compiler_free(struct compiler *c)
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (c->c_st)
420 PySymtable_Free(c->c_st);
421 if (c->c_future)
422 PyObject_Free(c->c_future);
Victor Stinner14e461d2013-08-26 22:28:21 +0200423 Py_XDECREF(c->c_filename);
INADA Naokic2e16072018-11-26 21:23:22 +0900424 Py_DECREF(c->c_const_cache);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_DECREF(c->c_stack);
Guido van Rossum10dc2e81990-11-18 17:27:39 +0000426}
427
Guido van Rossum79f25d91997-04-29 20:08:16 +0000428static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000429list2dict(PyObject *list)
Guido van Rossum2dff9911992-09-03 20:50:59 +0000430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_ssize_t i, n;
432 PyObject *v, *k;
433 PyObject *dict = PyDict_New();
434 if (!dict) return NULL;
Guido van Rossumd076c731998-10-07 19:42:25 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 n = PyList_Size(list);
437 for (i = 0; i < n; i++) {
Victor Stinnerad9a0662013-11-19 22:23:20 +0100438 v = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (!v) {
440 Py_DECREF(dict);
441 return NULL;
442 }
443 k = PyList_GET_ITEM(list, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300444 if (PyDict_SetItem(dict, k, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 Py_DECREF(v);
446 Py_DECREF(dict);
447 return NULL;
448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 Py_DECREF(v);
450 }
451 return dict;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000452}
453
454/* Return new dict containing names from src that match scope(s).
455
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000456src is a symbol table dictionary. If the scope of a name matches
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457either scope_type or flag is set, insert it into the new dict. The
Jeremy Hyltone9357b22006-03-01 15:47:05 +0000458values are integers, starting at offset and increasing by one for
459each key.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460*/
461
462static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +0100463dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000464{
Benjamin Peterson51ab2832012-07-18 15:12:47 -0700465 Py_ssize_t i = offset, scope, num_keys, key_i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyObject *k, *v, *dest = PyDict_New();
Meador Inge2ca63152012-07-18 14:20:11 -0500467 PyObject *sorted_keys;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 assert(offset >= 0);
470 if (dest == NULL)
471 return NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000472
Meador Inge2ca63152012-07-18 14:20:11 -0500473 /* Sort the keys so that we have a deterministic order on the indexes
474 saved in the returned dictionary. These indexes are used as indexes
475 into the free and cell var storage. Therefore if they aren't
476 deterministic, then the generated bytecode is not deterministic.
477 */
478 sorted_keys = PyDict_Keys(src);
479 if (sorted_keys == NULL)
480 return NULL;
481 if (PyList_Sort(sorted_keys) != 0) {
482 Py_DECREF(sorted_keys);
483 return NULL;
484 }
Meador Ingef69e24e2012-07-18 16:41:03 -0500485 num_keys = PyList_GET_SIZE(sorted_keys);
Meador Inge2ca63152012-07-18 14:20:11 -0500486
487 for (key_i = 0; key_i < num_keys; key_i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* XXX this should probably be a macro in symtable.h */
489 long vi;
Meador Inge2ca63152012-07-18 14:20:11 -0500490 k = PyList_GET_ITEM(sorted_keys, key_i);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200491 v = PyDict_GetItemWithError(src, k);
492 assert(v && PyLong_Check(v));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 vi = PyLong_AS_LONG(v);
494 scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (scope == scope_type || vi & flag) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300497 PyObject *item = PyLong_FromSsize_t(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (item == NULL) {
Meador Inge2ca63152012-07-18 14:20:11 -0500499 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 Py_DECREF(dest);
501 return NULL;
502 }
503 i++;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300504 if (PyDict_SetItem(dest, k, item) < 0) {
Meador Inge2ca63152012-07-18 14:20:11 -0500505 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 Py_DECREF(item);
507 Py_DECREF(dest);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return NULL;
509 }
510 Py_DECREF(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 }
512 }
Meador Inge2ca63152012-07-18 14:20:11 -0500513 Py_DECREF(sorted_keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return dest;
Jeremy Hylton64949cb2001-01-25 20:06:59 +0000515}
516
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000517static void
518compiler_unit_check(struct compiler_unit *u)
519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 basicblock *block;
521 for (block = u->u_blocks; block != NULL; block = block->b_list) {
Benjamin Petersonca470632016-09-06 13:47:26 -0700522 assert((uintptr_t)block != 0xcbcbcbcbU);
523 assert((uintptr_t)block != 0xfbfbfbfbU);
524 assert((uintptr_t)block != 0xdbdbdbdbU);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (block->b_instr != NULL) {
526 assert(block->b_ialloc > 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +0100527 assert(block->b_iused >= 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 assert(block->b_ialloc >= block->b_iused);
529 }
530 else {
531 assert (block->b_iused == 0);
532 assert (block->b_ialloc == 0);
533 }
534 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000535}
536
537static void
538compiler_unit_free(struct compiler_unit *u)
539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 basicblock *b, *next;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 compiler_unit_check(u);
543 b = u->u_blocks;
544 while (b != NULL) {
545 if (b->b_instr)
546 PyObject_Free((void *)b->b_instr);
547 next = b->b_list;
548 PyObject_Free((void *)b);
549 b = next;
550 }
551 Py_CLEAR(u->u_ste);
552 Py_CLEAR(u->u_name);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400553 Py_CLEAR(u->u_qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 Py_CLEAR(u->u_consts);
555 Py_CLEAR(u->u_names);
556 Py_CLEAR(u->u_varnames);
557 Py_CLEAR(u->u_freevars);
558 Py_CLEAR(u->u_cellvars);
559 Py_CLEAR(u->u_private);
560 PyObject_Free(u);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561}
562
563static int
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100564compiler_enter_scope(struct compiler *c, identifier name,
565 int scope_type, void *key, int lineno)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 struct compiler_unit *u;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100568 basicblock *block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000569
Andy Lester7668a8b2020-03-24 23:26:44 -0500570 u = (struct compiler_unit *)PyObject_Calloc(1, sizeof(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 struct compiler_unit));
572 if (!u) {
573 PyErr_NoMemory();
574 return 0;
575 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100576 u->u_scope_type = scope_type;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 u->u_argcount = 0;
Pablo Galindo8c77b8c2019-04-29 13:36:57 +0100578 u->u_posonlyargcount = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 u->u_kwonlyargcount = 0;
580 u->u_ste = PySymtable_Lookup(c->c_st, key);
581 if (!u->u_ste) {
582 compiler_unit_free(u);
583 return 0;
584 }
585 Py_INCREF(name);
586 u->u_name = name;
587 u->u_varnames = list2dict(u->u_ste->ste_varnames);
588 u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
589 if (!u->u_varnames || !u->u_cellvars) {
590 compiler_unit_free(u);
591 return 0;
592 }
Benjamin Peterson312595c2013-05-15 15:26:42 -0500593 if (u->u_ste->ste_needs_class_closure) {
Martin Panter7462b6492015-11-02 03:37:02 +0000594 /* Cook up an implicit __class__ cell. */
Benjamin Peterson312595c2013-05-15 15:26:42 -0500595 _Py_IDENTIFIER(__class__);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +0300596 PyObject *name;
Benjamin Peterson312595c2013-05-15 15:26:42 -0500597 int res;
598 assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200599 assert(PyDict_GET_SIZE(u->u_cellvars) == 0);
Benjamin Peterson312595c2013-05-15 15:26:42 -0500600 name = _PyUnicode_FromId(&PyId___class__);
601 if (!name) {
602 compiler_unit_free(u);
603 return 0;
604 }
Victor Stinnerc9bc2902020-10-27 02:24:34 +0100605 res = PyDict_SetItem(u->u_cellvars, name, _PyLong_GetZero());
Benjamin Peterson312595c2013-05-15 15:26:42 -0500606 if (res < 0) {
607 compiler_unit_free(u);
608 return 0;
609 }
610 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +0200613 PyDict_GET_SIZE(u->u_cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (!u->u_freevars) {
615 compiler_unit_free(u);
616 return 0;
617 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 u->u_blocks = NULL;
620 u->u_nfblocks = 0;
621 u->u_firstlineno = lineno;
622 u->u_lineno = 0;
Benjamin Petersond4efd9e2010-09-20 23:02:10 +0000623 u->u_col_offset = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 u->u_consts = PyDict_New();
625 if (!u->u_consts) {
626 compiler_unit_free(u);
627 return 0;
628 }
629 u->u_names = PyDict_New();
630 if (!u->u_names) {
631 compiler_unit_free(u);
632 return 0;
633 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 u->u_private = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 /* Push the old compiler_unit on the stack. */
638 if (c->u) {
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400639 PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
641 Py_XDECREF(capsule);
642 compiler_unit_free(u);
643 return 0;
644 }
645 Py_DECREF(capsule);
646 u->u_private = c->u->u_private;
647 Py_XINCREF(u->u_private);
648 }
649 c->u = u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 c->c_nestlevel++;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100652
653 block = compiler_new_block(c);
654 if (block == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 return 0;
Victor Stinnerfc6f2ef2016-02-27 02:19:22 +0100656 c->u->u_curblock = block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000657
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400658 if (u->u_scope_type != COMPILER_SCOPE_MODULE) {
659 if (!compiler_set_qualname(c))
660 return 0;
661 }
662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000664}
665
Neil Schemenauerc396d9e2005-10-25 06:30:14 +0000666static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000667compiler_exit_scope(struct compiler *c)
668{
Victor Stinnerad9a0662013-11-19 22:23:20 +0100669 Py_ssize_t n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject *capsule;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 c->c_nestlevel--;
673 compiler_unit_free(c->u);
674 /* Restore c->u to the parent unit. */
675 n = PyList_GET_SIZE(c->c_stack) - 1;
676 if (n >= 0) {
677 capsule = PyList_GET_ITEM(c->c_stack, n);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400678 c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 assert(c->u);
680 /* we are deleting from a list so this really shouldn't fail */
681 if (PySequence_DelItem(c->c_stack, n) < 0)
682 Py_FatalError("compiler_exit_scope()");
683 compiler_unit_check(c->u);
684 }
685 else
686 c->u = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000687
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000688}
689
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400690static int
691compiler_set_qualname(struct compiler *c)
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100692{
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100693 _Py_static_string(dot, ".");
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400694 _Py_static_string(dot_locals, ".<locals>");
695 Py_ssize_t stack_size;
696 struct compiler_unit *u = c->u;
697 PyObject *name, *base, *dot_str, *dot_locals_str;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100698
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400699 base = NULL;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100700 stack_size = PyList_GET_SIZE(c->c_stack);
Benjamin Petersona8a38b82013-10-19 16:14:39 -0400701 assert(stack_size >= 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400702 if (stack_size > 1) {
703 int scope, force_global = 0;
704 struct compiler_unit *parent;
705 PyObject *mangled, *capsule;
706
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400707 capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1);
Benjamin Peterson9e77f722015-05-07 18:41:47 -0400708 parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400709 assert(parent);
710
Yury Selivanov75445082015-05-11 22:57:16 -0400711 if (u->u_scope_type == COMPILER_SCOPE_FUNCTION
712 || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
713 || u->u_scope_type == COMPILER_SCOPE_CLASS) {
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400714 assert(u->u_name);
715 mangled = _Py_Mangle(parent->u_private, u->u_name);
716 if (!mangled)
717 return 0;
718 scope = PyST_GetScope(parent->u_ste, mangled);
719 Py_DECREF(mangled);
720 assert(scope != GLOBAL_IMPLICIT);
721 if (scope == GLOBAL_EXPLICIT)
722 force_global = 1;
723 }
724
725 if (!force_global) {
726 if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION
Yury Selivanov75445082015-05-11 22:57:16 -0400727 || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400728 || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) {
729 dot_locals_str = _PyUnicode_FromId(&dot_locals);
730 if (dot_locals_str == NULL)
731 return 0;
732 base = PyUnicode_Concat(parent->u_qualname, dot_locals_str);
733 if (base == NULL)
734 return 0;
735 }
736 else {
737 Py_INCREF(parent->u_qualname);
738 base = parent->u_qualname;
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400739 }
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100740 }
741 }
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400742
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400743 if (base != NULL) {
744 dot_str = _PyUnicode_FromId(&dot);
745 if (dot_str == NULL) {
746 Py_DECREF(base);
747 return 0;
748 }
749 name = PyUnicode_Concat(base, dot_str);
750 Py_DECREF(base);
751 if (name == NULL)
752 return 0;
753 PyUnicode_Append(&name, u->u_name);
754 if (name == NULL)
755 return 0;
756 }
757 else {
758 Py_INCREF(u->u_name);
759 name = u->u_name;
760 }
761 u->u_qualname = name;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100762
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400763 return 1;
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100764}
765
Eric V. Smith235a6f02015-09-19 14:51:32 -0400766
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000767/* Allocate a new block and return a pointer to it.
768 Returns NULL on error.
769*/
770
771static basicblock *
772compiler_new_block(struct compiler *c)
773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 basicblock *b;
775 struct compiler_unit *u;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 u = c->u;
Andy Lester7668a8b2020-03-24 23:26:44 -0500778 b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (b == NULL) {
780 PyErr_NoMemory();
781 return NULL;
782 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* Extend the singly linked list of blocks with new block. */
784 b->b_list = u->u_blocks;
785 u->u_blocks = b;
786 return b;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787}
788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000789static basicblock *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000790compiler_next_block(struct compiler *c)
791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 basicblock *block = compiler_new_block(c);
793 if (block == NULL)
794 return NULL;
795 c->u->u_curblock->b_next = block;
796 c->u->u_curblock = block;
797 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000798}
799
800static basicblock *
801compiler_use_next_block(struct compiler *c, basicblock *block)
802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 assert(block != NULL);
804 c->u->u_curblock->b_next = block;
805 c->u->u_curblock = block;
806 return block;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000807}
808
Mark Shannon5977a792020-12-02 13:31:40 +0000809static basicblock *
810compiler_copy_block(struct compiler *c, basicblock *block)
811{
812 /* Cannot copy a block if it has a fallthrough, since
813 * a block can only have one fallthrough predecessor.
814 */
815 assert(block->b_nofallthrough);
816 basicblock *result = compiler_next_block(c);
817 if (result == NULL) {
818 return NULL;
819 }
820 for (int i = 0; i < block->b_iused; i++) {
821 int n = compiler_next_instr(result);
822 if (n < 0) {
823 return NULL;
824 }
825 result->b_instr[n] = block->b_instr[i];
826 }
827 result->b_exit = block->b_exit;
828 return result;
829}
830
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000831/* Returns the offset of the next instruction in the current block's
832 b_instr array. Resizes the b_instr as necessary.
833 Returns -1 on failure.
Thomas Wouters89f507f2006-12-13 04:49:30 +0000834*/
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000835
836static int
Andy Lester76d58772020-03-10 21:18:12 -0500837compiler_next_instr(basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 assert(b != NULL);
840 if (b->b_instr == NULL) {
Andy Lester7668a8b2020-03-24 23:26:44 -0500841 b->b_instr = (struct instr *)PyObject_Calloc(
842 DEFAULT_BLOCK_SIZE, sizeof(struct instr));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 if (b->b_instr == NULL) {
844 PyErr_NoMemory();
845 return -1;
846 }
847 b->b_ialloc = DEFAULT_BLOCK_SIZE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 }
849 else if (b->b_iused == b->b_ialloc) {
850 struct instr *tmp;
851 size_t oldsize, newsize;
852 oldsize = b->b_ialloc * sizeof(struct instr);
853 newsize = oldsize << 1;
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000854
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -0700855 if (oldsize > (SIZE_MAX >> 1)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyErr_NoMemory();
857 return -1;
858 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 if (newsize == 0) {
861 PyErr_NoMemory();
862 return -1;
863 }
864 b->b_ialloc <<= 1;
865 tmp = (struct instr *)PyObject_Realloc(
866 (void *)b->b_instr, newsize);
867 if (tmp == NULL) {
868 PyErr_NoMemory();
869 return -1;
870 }
871 b->b_instr = tmp;
872 memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
873 }
874 return b->b_iused++;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000875}
876
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200877/* Set the line number and column offset for the following instructions.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000878
Christian Heimes2202f872008-02-06 14:31:34 +0000879 The line number is reset in the following cases:
880 - when entering a new scope
881 - on each statement
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200882 - on each expression and sub-expression
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200883 - before the "except" and "finally" clauses
Thomas Wouters89f507f2006-12-13 04:49:30 +0000884*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000885
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +0200886#define SET_LOC(c, x) \
887 (c)->u->u_lineno = (x)->lineno; \
888 (c)->u->u_col_offset = (x)->col_offset;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000889
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200890/* Return the stack effect of opcode with argument oparg.
891
892 Some opcodes have different stack effect when jump to the target and
893 when not jump. The 'jump' parameter specifies the case:
894
895 * 0 -- when not jump
896 * 1 -- when jump
897 * -1 -- maximal
898 */
899/* XXX Make the stack effect of WITH_CLEANUP_START and
900 WITH_CLEANUP_FINISH deterministic. */
901static int
902stack_effect(int opcode, int oparg, int jump)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 switch (opcode) {
Serhiy Storchaka57faf342018-04-25 22:04:06 +0300905 case NOP:
906 case EXTENDED_ARG:
907 return 0;
908
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200909 /* Stack manipulation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 case POP_TOP:
911 return -1;
912 case ROT_TWO:
913 case ROT_THREE:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200914 case ROT_FOUR:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 return 0;
916 case DUP_TOP:
917 return 1;
Antoine Pitrou74a69fa2010-09-04 18:43:52 +0000918 case DUP_TOP_TWO:
919 return 2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000920
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200921 /* Unary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 case UNARY_POSITIVE:
923 case UNARY_NEGATIVE:
924 case UNARY_NOT:
925 case UNARY_INVERT:
926 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 case SET_ADD:
929 case LIST_APPEND:
930 return -1;
931 case MAP_ADD:
932 return -2;
Neal Norwitz10be2ea2006-03-03 20:29:11 +0000933
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200934 /* Binary operators */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 case BINARY_POWER:
936 case BINARY_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400937 case BINARY_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 case BINARY_MODULO:
939 case BINARY_ADD:
940 case BINARY_SUBTRACT:
941 case BINARY_SUBSCR:
942 case BINARY_FLOOR_DIVIDE:
943 case BINARY_TRUE_DIVIDE:
944 return -1;
945 case INPLACE_FLOOR_DIVIDE:
946 case INPLACE_TRUE_DIVIDE:
947 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 case INPLACE_ADD:
950 case INPLACE_SUBTRACT:
951 case INPLACE_MULTIPLY:
Benjamin Petersond51374e2014-04-09 23:55:56 -0400952 case INPLACE_MATRIX_MULTIPLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 case INPLACE_MODULO:
954 return -1;
955 case STORE_SUBSCR:
956 return -3;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 case DELETE_SUBSCR:
958 return -2;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 case BINARY_LSHIFT:
961 case BINARY_RSHIFT:
962 case BINARY_AND:
963 case BINARY_XOR:
964 case BINARY_OR:
965 return -1;
966 case INPLACE_POWER:
967 return -1;
968 case GET_ITER:
969 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 case PRINT_EXPR:
972 return -1;
973 case LOAD_BUILD_CLASS:
974 return 1;
975 case INPLACE_LSHIFT:
976 case INPLACE_RSHIFT:
977 case INPLACE_AND:
978 case INPLACE_XOR:
979 case INPLACE_OR:
980 return -1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +0200981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 case SETUP_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +0200983 /* 1 in the normal flow.
984 * Restore the stack position and push 6 values before jumping to
985 * the handler if an exception be raised. */
986 return jump ? 6 : 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 case RETURN_VALUE:
988 return -1;
989 case IMPORT_STAR:
990 return -1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -0700991 case SETUP_ANNOTATIONS:
992 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 case YIELD_VALUE:
994 return 0;
Benjamin Peterson2afe6ae2012-03-15 15:37:39 -0500995 case YIELD_FROM:
996 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 case POP_BLOCK:
998 return 0;
999 case POP_EXCEPT:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001000 return -3;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 case STORE_NAME:
1003 return -1;
1004 case DELETE_NAME:
1005 return 0;
1006 case UNPACK_SEQUENCE:
1007 return oparg-1;
1008 case UNPACK_EX:
1009 return (oparg&0xFF) + (oparg>>8);
1010 case FOR_ITER:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001011 /* -1 at end of iterator, 1 if continue iterating. */
1012 return jump > 0 ? -1 : 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 case STORE_ATTR:
1015 return -2;
1016 case DELETE_ATTR:
1017 return -1;
1018 case STORE_GLOBAL:
1019 return -1;
1020 case DELETE_GLOBAL:
1021 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 case LOAD_CONST:
1023 return 1;
1024 case LOAD_NAME:
1025 return 1;
1026 case BUILD_TUPLE:
1027 case BUILD_LIST:
1028 case BUILD_SET:
Serhiy Storchakaea525a22016-09-06 22:07:53 +03001029 case BUILD_STRING:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 return 1-oparg;
1031 case BUILD_MAP:
Benjamin Petersonb6855152015-09-10 21:02:39 -07001032 return 1 - 2*oparg;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03001033 case BUILD_CONST_KEY_MAP:
1034 return -oparg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 case LOAD_ATTR:
1036 return 0;
1037 case COMPARE_OP:
Mark Shannon9af0e472020-01-14 10:12:45 +00001038 case IS_OP:
1039 case CONTAINS_OP:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 return -1;
Mark Shannon9af0e472020-01-14 10:12:45 +00001041 case JUMP_IF_NOT_EXC_MATCH:
1042 return -2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 case IMPORT_NAME:
1044 return -1;
1045 case IMPORT_FROM:
1046 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001047
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001048 /* Jumps */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 case JUMP_FORWARD:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 case JUMP_ABSOLUTE:
1051 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001052
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001053 case JUMP_IF_TRUE_OR_POP:
1054 case JUMP_IF_FALSE_OR_POP:
1055 return jump ? 0 : -1;
1056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 case POP_JUMP_IF_FALSE:
1058 case POP_JUMP_IF_TRUE:
1059 return -1;
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 case LOAD_GLOBAL:
1062 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001064 /* Exception handling */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 case SETUP_FINALLY:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001066 /* 0 in the normal flow.
1067 * Restore the stack position and push 6 values before jumping to
1068 * the handler if an exception be raised. */
1069 return jump ? 6 : 0;
Mark Shannonfee55262019-11-21 09:11:43 +00001070 case RERAISE:
1071 return -3;
1072
1073 case WITH_EXCEPT_START:
1074 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 case LOAD_FAST:
1077 return 1;
1078 case STORE_FAST:
1079 return -1;
1080 case DELETE_FAST:
1081 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 case RAISE_VARARGS:
1084 return -oparg;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001085
1086 /* Functions and calls */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 case CALL_FUNCTION:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001088 return -oparg;
Yury Selivanovf2392132016-12-13 19:03:51 -05001089 case CALL_METHOD:
1090 return -oparg-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 case CALL_FUNCTION_KW:
Victor Stinnerf9b760f2016-09-09 10:17:08 -07001092 return -oparg-1;
1093 case CALL_FUNCTION_EX:
Matthieu Dartiailh3a9ac822017-02-21 14:25:22 +01001094 return -1 - ((oparg & 0x01) != 0);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001095 case MAKE_FUNCTION:
1096 return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) -
1097 ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 case BUILD_SLICE:
1099 if (oparg == 3)
1100 return -2;
1101 else
1102 return -1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001103
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001104 /* Closures */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 case LOAD_CLOSURE:
1106 return 1;
1107 case LOAD_DEREF:
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04001108 case LOAD_CLASSDEREF:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 return 1;
1110 case STORE_DEREF:
1111 return -1;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00001112 case DELETE_DEREF:
1113 return 0;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001114
1115 /* Iterators and generators */
Yury Selivanov75445082015-05-11 22:57:16 -04001116 case GET_AWAITABLE:
1117 return 0;
1118 case SETUP_ASYNC_WITH:
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001119 /* 0 in the normal flow.
1120 * Restore the stack position to the position before the result
1121 * of __aenter__ and push 6 values before jumping to the handler
1122 * if an exception be raised. */
1123 return jump ? -1 + 6 : 0;
Yury Selivanov75445082015-05-11 22:57:16 -04001124 case BEFORE_ASYNC_WITH:
1125 return 1;
1126 case GET_AITER:
1127 return 0;
1128 case GET_ANEXT:
1129 return 1;
Yury Selivanov5376ba92015-06-22 12:19:30 -04001130 case GET_YIELD_FROM_ITER:
1131 return 0;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001132 case END_ASYNC_FOR:
1133 return -7;
Eric V. Smitha78c7952015-11-03 12:45:05 -05001134 case FORMAT_VALUE:
1135 /* If there's a fmt_spec on the stack, we go from 2->1,
1136 else 1->1. */
1137 return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0;
Yury Selivanovf2392132016-12-13 19:03:51 -05001138 case LOAD_METHOD:
1139 return 1;
Zackery Spytzce6a0702019-08-25 03:44:09 -06001140 case LOAD_ASSERTION_ERROR:
1141 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001142 case LIST_TO_TUPLE:
1143 return 0;
1144 case LIST_EXTEND:
1145 case SET_UPDATE:
Mark Shannon8a4cd702020-01-27 09:57:45 +00001146 case DICT_MERGE:
1147 case DICT_UPDATE:
Mark Shannon13bc1392020-01-23 09:25:17 +00001148 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 default:
Larry Hastings3a907972013-11-23 14:49:22 -08001150 return PY_INVALID_STACK_EFFECT;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 }
Larry Hastings3a907972013-11-23 14:49:22 -08001152 return PY_INVALID_STACK_EFFECT; /* not reachable */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001153}
1154
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001155int
Serhiy Storchaka7bdf2822018-09-18 09:54:26 +03001156PyCompile_OpcodeStackEffectWithJump(int opcode, int oparg, int jump)
1157{
1158 return stack_effect(opcode, oparg, jump);
1159}
1160
1161int
Serhiy Storchakad4864c62018-01-09 21:54:52 +02001162PyCompile_OpcodeStackEffect(int opcode, int oparg)
1163{
1164 return stack_effect(opcode, oparg, -1);
1165}
1166
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001167/* Add an opcode with no argument.
1168 Returns 0 on failure, 1 on success.
1169*/
1170
1171static int
1172compiler_addop(struct compiler *c, int opcode)
1173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 basicblock *b;
1175 struct instr *i;
1176 int off;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001177 assert(!HAS_ARG(opcode));
Andy Lester76d58772020-03-10 21:18:12 -05001178 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (off < 0)
1180 return 0;
1181 b = c->u->u_curblock;
1182 i = &b->b_instr[off];
1183 i->i_opcode = opcode;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001184 i->i_oparg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 if (opcode == RETURN_VALUE)
1186 b->b_return = 1;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001187 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001189}
1190
Victor Stinnerf8e32212013-11-19 23:56:34 +01001191static Py_ssize_t
Andy Lester76d58772020-03-10 21:18:12 -05001192compiler_add_o(PyObject *dict, PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001193{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001194 PyObject *v;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 Py_ssize_t arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001196
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001197 v = PyDict_GetItemWithError(dict, o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (!v) {
Stefan Krahc0cbed12015-07-27 12:56:49 +02001199 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return -1;
Stefan Krahc0cbed12015-07-27 12:56:49 +02001201 }
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02001202 arg = PyDict_GET_SIZE(dict);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001203 v = PyLong_FromSsize_t(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (!v) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return -1;
1206 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001207 if (PyDict_SetItem(dict, o, v) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 Py_DECREF(v);
1209 return -1;
1210 }
1211 Py_DECREF(v);
1212 }
1213 else
1214 arg = PyLong_AsLong(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001215 return arg;
1216}
1217
INADA Naokic2e16072018-11-26 21:23:22 +09001218// Merge const *o* recursively and return constant key object.
1219static PyObject*
1220merge_consts_recursive(struct compiler *c, PyObject *o)
1221{
1222 // None and Ellipsis are singleton, and key is the singleton.
1223 // No need to merge object and key.
1224 if (o == Py_None || o == Py_Ellipsis) {
1225 Py_INCREF(o);
1226 return o;
1227 }
1228
1229 PyObject *key = _PyCode_ConstantKey(o);
1230 if (key == NULL) {
1231 return NULL;
1232 }
1233
1234 // t is borrowed reference
1235 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
1236 if (t != key) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001237 // o is registered in c_const_cache. Just use it.
Zackery Spytz9b4a1b12019-03-20 03:16:25 -06001238 Py_XINCREF(t);
INADA Naokic2e16072018-11-26 21:23:22 +09001239 Py_DECREF(key);
1240 return t;
1241 }
1242
INADA Naokif7e4d362018-11-29 00:58:46 +09001243 // We registered o in c_const_cache.
Simeon63b5fc52019-04-09 19:36:57 -04001244 // When o is a tuple or frozenset, we want to merge its
INADA Naokif7e4d362018-11-29 00:58:46 +09001245 // items too.
INADA Naokic2e16072018-11-26 21:23:22 +09001246 if (PyTuple_CheckExact(o)) {
INADA Naokif7e4d362018-11-29 00:58:46 +09001247 Py_ssize_t len = PyTuple_GET_SIZE(o);
1248 for (Py_ssize_t i = 0; i < len; i++) {
INADA Naokic2e16072018-11-26 21:23:22 +09001249 PyObject *item = PyTuple_GET_ITEM(o, i);
1250 PyObject *u = merge_consts_recursive(c, item);
1251 if (u == NULL) {
1252 Py_DECREF(key);
1253 return NULL;
1254 }
1255
1256 // See _PyCode_ConstantKey()
1257 PyObject *v; // borrowed
1258 if (PyTuple_CheckExact(u)) {
1259 v = PyTuple_GET_ITEM(u, 1);
1260 }
1261 else {
1262 v = u;
1263 }
1264 if (v != item) {
1265 Py_INCREF(v);
1266 PyTuple_SET_ITEM(o, i, v);
1267 Py_DECREF(item);
1268 }
1269
1270 Py_DECREF(u);
1271 }
1272 }
INADA Naokif7e4d362018-11-29 00:58:46 +09001273 else if (PyFrozenSet_CheckExact(o)) {
Simeon63b5fc52019-04-09 19:36:57 -04001274 // *key* is tuple. And its first item is frozenset of
INADA Naokif7e4d362018-11-29 00:58:46 +09001275 // constant keys.
1276 // See _PyCode_ConstantKey() for detail.
1277 assert(PyTuple_CheckExact(key));
1278 assert(PyTuple_GET_SIZE(key) == 2);
1279
1280 Py_ssize_t len = PySet_GET_SIZE(o);
1281 if (len == 0) { // empty frozenset should not be re-created.
1282 return key;
1283 }
1284 PyObject *tuple = PyTuple_New(len);
1285 if (tuple == NULL) {
1286 Py_DECREF(key);
1287 return NULL;
1288 }
1289 Py_ssize_t i = 0, pos = 0;
1290 PyObject *item;
1291 Py_hash_t hash;
1292 while (_PySet_NextEntry(o, &pos, &item, &hash)) {
1293 PyObject *k = merge_consts_recursive(c, item);
1294 if (k == NULL) {
1295 Py_DECREF(tuple);
1296 Py_DECREF(key);
1297 return NULL;
1298 }
1299 PyObject *u;
1300 if (PyTuple_CheckExact(k)) {
1301 u = PyTuple_GET_ITEM(k, 1);
1302 Py_INCREF(u);
1303 Py_DECREF(k);
1304 }
1305 else {
1306 u = k;
1307 }
1308 PyTuple_SET_ITEM(tuple, i, u); // Steals reference of u.
1309 i++;
1310 }
1311
1312 // Instead of rewriting o, we create new frozenset and embed in the
1313 // key tuple. Caller should get merged frozenset from the key tuple.
1314 PyObject *new = PyFrozenSet_New(tuple);
1315 Py_DECREF(tuple);
1316 if (new == NULL) {
1317 Py_DECREF(key);
1318 return NULL;
1319 }
1320 assert(PyTuple_GET_ITEM(key, 1) == o);
1321 Py_DECREF(o);
1322 PyTuple_SET_ITEM(key, 1, new);
1323 }
INADA Naokic2e16072018-11-26 21:23:22 +09001324
1325 return key;
1326}
1327
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001328static Py_ssize_t
1329compiler_add_const(struct compiler *c, PyObject *o)
1330{
INADA Naokic2e16072018-11-26 21:23:22 +09001331 PyObject *key = merge_consts_recursive(c, o);
1332 if (key == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001333 return -1;
INADA Naokic2e16072018-11-26 21:23:22 +09001334 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001335
Andy Lester76d58772020-03-10 21:18:12 -05001336 Py_ssize_t arg = compiler_add_o(c->u->u_consts, key);
INADA Naokic2e16072018-11-26 21:23:22 +09001337 Py_DECREF(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 return arg;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001339}
1340
1341static int
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001342compiler_addop_load_const(struct compiler *c, PyObject *o)
1343{
1344 Py_ssize_t arg = compiler_add_const(c, o);
1345 if (arg < 0)
1346 return 0;
1347 return compiler_addop_i(c, LOAD_CONST, arg);
1348}
1349
1350static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001353{
Andy Lester76d58772020-03-10 21:18:12 -05001354 Py_ssize_t arg = compiler_add_o(dict, o);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001355 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001356 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357 return compiler_addop_i(c, opcode, arg);
1358}
1359
1360static int
1361compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyObject *o)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001363{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001364 Py_ssize_t arg;
Pablo Galindo18c5f9d2019-07-15 10:15:01 +01001365
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001366 PyObject *mangled = _Py_Mangle(c->u->u_private, o);
1367 if (!mangled)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001368 return 0;
Andy Lester76d58772020-03-10 21:18:12 -05001369 arg = compiler_add_o(dict, mangled);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001370 Py_DECREF(mangled);
1371 if (arg < 0)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001372 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373 return compiler_addop_i(c, opcode, arg);
1374}
1375
1376/* Add an opcode with an integer argument.
1377 Returns 0 on failure, 1 on success.
1378*/
1379
1380static int
Victor Stinnerf8e32212013-11-19 23:56:34 +01001381compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 struct instr *i;
1384 int off;
Victor Stinnerad9a0662013-11-19 22:23:20 +01001385
Victor Stinner2ad474b2016-03-01 23:34:47 +01001386 /* oparg value is unsigned, but a signed C int is usually used to store
1387 it in the C code (like Python/ceval.c).
1388
1389 Limit to 32-bit signed C int (rather than INT_MAX) for portability.
1390
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001391 The argument of a concrete bytecode instruction is limited to 8-bit.
1392 EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */
1393 assert(HAS_ARG(opcode));
Victor Stinner2ad474b2016-03-01 23:34:47 +01001394 assert(0 <= oparg && oparg <= 2147483647);
Victor Stinnerad9a0662013-11-19 22:23:20 +01001395
Andy Lester76d58772020-03-10 21:18:12 -05001396 off = compiler_next_instr(c->u->u_curblock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 if (off < 0)
1398 return 0;
1399 i = &c->u->u_curblock->b_instr[off];
Victor Stinnerf8e32212013-11-19 23:56:34 +01001400 i->i_opcode = opcode;
1401 i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001402 i->i_lineno = c->u->u_lineno;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001404}
1405
Mark Shannon28b75c82020-12-23 11:43:10 +00001406static int add_jump_to_block(basicblock *b, int opcode, int lineno, basicblock *target)
1407{
1408 assert(HAS_ARG(opcode));
1409 assert(b != NULL);
1410 assert(target != NULL);
1411
1412 int off = compiler_next_instr(b);
1413 struct instr *i = &b->b_instr[off];
1414 if (off < 0) {
1415 return 0;
1416 }
1417 i->i_opcode = opcode;
1418 i->i_target = target;
1419 i->i_lineno = lineno;
1420 return 1;
1421}
1422
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001423static int
Mark Shannon582aaf12020-08-04 17:30:11 +01001424compiler_addop_j(struct compiler *c, int opcode, basicblock *b)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001425{
Mark Shannon28b75c82020-12-23 11:43:10 +00001426 return add_jump_to_block(c->u->u_curblock, opcode, c->u->u_lineno, b);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001427}
1428
Mark Shannon127dde52021-01-04 18:06:55 +00001429static int
1430compiler_addop_j_noline(struct compiler *c, int opcode, basicblock *b)
1431{
1432 return add_jump_to_block(c->u->u_curblock, opcode, -1, b);
1433}
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 Shannon127dde52021-01-04 18:06:55 +00001505/* Add a jump with no line number.
1506 * Used for artificial jumps that have no corresponding
1507 * token in the source code. */
1508#define ADDOP_JUMP_NOLINE(C, OP, O) { \
1509 if (!compiler_addop_j_noline((C), (OP), (O))) \
1510 return 0; \
1511}
1512
Mark Shannon9af0e472020-01-14 10:12:45 +00001513#define ADDOP_COMPARE(C, CMP) { \
1514 if (!compiler_addcompare((C), (cmpop_ty)(CMP))) \
1515 return 0; \
1516}
1517
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001518/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
1519 the ASDL name to synthesize the name of the C type and the visit function.
1520*/
1521
1522#define VISIT(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (!compiler_visit_ ## TYPE((C), (V))) \
1524 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001525}
1526
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001527#define VISIT_IN_SCOPE(C, TYPE, V) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (!compiler_visit_ ## TYPE((C), (V))) { \
1529 compiler_exit_scope(c); \
1530 return 0; \
1531 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001532}
1533
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001534#define VISIT_SLICE(C, V, CTX) {\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (!compiler_visit_slice((C), (V), (CTX))) \
1536 return 0; \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001537}
1538
1539#define VISIT_SEQ(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001541 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1543 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1544 if (!compiler_visit_ ## TYPE((C), elt)) \
1545 return 0; \
1546 } \
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547}
1548
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001549#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 int _i; \
Pablo Galindoa5634c42020-09-16 19:42:00 +01001551 asdl_ ## TYPE ## _seq *seq = (SEQ); /* avoid variable capture */ \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
1553 TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
1554 if (!compiler_visit_ ## TYPE((C), elt)) { \
1555 compiler_exit_scope(c); \
1556 return 0; \
1557 } \
1558 } \
Neal Norwitzb6fc9df2005-11-13 18:50:34 +00001559}
1560
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001561/* Search if variable annotations are present statically in a block. */
1562
1563static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001564find_ann(asdl_stmt_seq *stmts)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001565{
1566 int i, j, res = 0;
1567 stmt_ty st;
1568
1569 for (i = 0; i < asdl_seq_LEN(stmts); i++) {
1570 st = (stmt_ty)asdl_seq_GET(stmts, i);
1571 switch (st->kind) {
1572 case AnnAssign_kind:
1573 return 1;
1574 case For_kind:
1575 res = find_ann(st->v.For.body) ||
1576 find_ann(st->v.For.orelse);
1577 break;
1578 case AsyncFor_kind:
1579 res = find_ann(st->v.AsyncFor.body) ||
1580 find_ann(st->v.AsyncFor.orelse);
1581 break;
1582 case While_kind:
1583 res = find_ann(st->v.While.body) ||
1584 find_ann(st->v.While.orelse);
1585 break;
1586 case If_kind:
1587 res = find_ann(st->v.If.body) ||
1588 find_ann(st->v.If.orelse);
1589 break;
1590 case With_kind:
1591 res = find_ann(st->v.With.body);
1592 break;
1593 case AsyncWith_kind:
1594 res = find_ann(st->v.AsyncWith.body);
1595 break;
1596 case Try_kind:
1597 for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) {
1598 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
1599 st->v.Try.handlers, j);
1600 if (find_ann(handler->v.ExceptHandler.body)) {
1601 return 1;
1602 }
1603 }
1604 res = find_ann(st->v.Try.body) ||
1605 find_ann(st->v.Try.finalbody) ||
1606 find_ann(st->v.Try.orelse);
1607 break;
1608 default:
1609 res = 0;
1610 }
1611 if (res) {
1612 break;
1613 }
1614 }
1615 return res;
1616}
1617
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001618/*
1619 * Frame block handling functions
1620 */
1621
1622static int
1623compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b,
Mark Shannonfee55262019-11-21 09:11:43 +00001624 basicblock *exit, void *datum)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001625{
1626 struct fblockinfo *f;
1627 if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
Mark Shannon02d126a2020-09-25 14:04:19 +01001628 return compiler_error(c, "too many statically nested blocks");
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001629 }
1630 f = &c->u->u_fblock[c->u->u_nfblocks++];
1631 f->fb_type = t;
1632 f->fb_block = b;
1633 f->fb_exit = exit;
Mark Shannonfee55262019-11-21 09:11:43 +00001634 f->fb_datum = datum;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001635 return 1;
1636}
1637
1638static void
1639compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
1640{
1641 struct compiler_unit *u = c->u;
1642 assert(u->u_nfblocks > 0);
1643 u->u_nfblocks--;
1644 assert(u->u_fblock[u->u_nfblocks].fb_type == t);
1645 assert(u->u_fblock[u->u_nfblocks].fb_block == b);
1646}
1647
Mark Shannonfee55262019-11-21 09:11:43 +00001648static int
1649compiler_call_exit_with_nones(struct compiler *c) {
1650 ADDOP_O(c, LOAD_CONST, Py_None, consts);
1651 ADDOP(c, DUP_TOP);
1652 ADDOP(c, DUP_TOP);
1653 ADDOP_I(c, CALL_FUNCTION, 3);
1654 return 1;
1655}
1656
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001657/* Unwind a frame block. If preserve_tos is true, the TOS before
Mark Shannonfee55262019-11-21 09:11:43 +00001658 * popping the blocks will be restored afterwards, unless another
1659 * return, break or continue is found. In which case, the TOS will
1660 * be popped.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001661 */
1662static int
1663compiler_unwind_fblock(struct compiler *c, struct fblockinfo *info,
1664 int preserve_tos)
1665{
1666 switch (info->fb_type) {
1667 case WHILE_LOOP:
Mark Shannon02d126a2020-09-25 14:04:19 +01001668 case EXCEPTION_HANDLER:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001669 return 1;
1670
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001671 case FOR_LOOP:
1672 /* Pop the iterator */
1673 if (preserve_tos) {
1674 ADDOP(c, ROT_TWO);
1675 }
1676 ADDOP(c, POP_TOP);
1677 return 1;
1678
Mark Shannon02d126a2020-09-25 14:04:19 +01001679 case TRY_EXCEPT:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001680 ADDOP(c, POP_BLOCK);
1681 return 1;
1682
1683 case FINALLY_TRY:
Mark Shannon5274b682020-12-16 13:07:01 +00001684 /* This POP_BLOCK gets the line number of the unwinding statement */
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001685 ADDOP(c, POP_BLOCK);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001686 if (preserve_tos) {
Mark Shannonfee55262019-11-21 09:11:43 +00001687 if (!compiler_push_fblock(c, POP_VALUE, NULL, NULL, NULL)) {
1688 return 0;
1689 }
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001690 }
Mark Shannon5274b682020-12-16 13:07:01 +00001691 /* Emit the finally block */
Mark Shannonfee55262019-11-21 09:11:43 +00001692 VISIT_SEQ(c, stmt, info->fb_datum);
1693 if (preserve_tos) {
1694 compiler_pop_fblock(c, POP_VALUE, NULL);
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001695 }
Mark Shannon5274b682020-12-16 13:07:01 +00001696 /* The finally block should appear to execute after the
1697 * statement causing the unwinding, so make the unwinding
1698 * instruction artificial */
1699 c->u->u_lineno = -1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001700 return 1;
Mark Shannon13bc1392020-01-23 09:25:17 +00001701
Mark Shannonfee55262019-11-21 09:11:43 +00001702 case FINALLY_END:
1703 if (preserve_tos) {
1704 ADDOP(c, ROT_FOUR);
1705 }
1706 ADDOP(c, POP_TOP);
1707 ADDOP(c, POP_TOP);
1708 ADDOP(c, POP_TOP);
1709 if (preserve_tos) {
1710 ADDOP(c, ROT_FOUR);
1711 }
1712 ADDOP(c, POP_EXCEPT);
1713 return 1;
Serhiy Storchakaef61c522019-08-24 13:11:52 +03001714
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001715 case WITH:
1716 case ASYNC_WITH:
1717 ADDOP(c, POP_BLOCK);
1718 if (preserve_tos) {
1719 ADDOP(c, ROT_TWO);
1720 }
Mark Shannonfee55262019-11-21 09:11:43 +00001721 if(!compiler_call_exit_with_nones(c)) {
1722 return 0;
1723 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001724 if (info->fb_type == ASYNC_WITH) {
1725 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001726 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001727 ADDOP(c, YIELD_FROM);
1728 }
Mark Shannonfee55262019-11-21 09:11:43 +00001729 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001730 return 1;
1731
1732 case HANDLER_CLEANUP:
Mark Shannonfee55262019-11-21 09:11:43 +00001733 if (info->fb_datum) {
1734 ADDOP(c, POP_BLOCK);
1735 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001736 if (preserve_tos) {
1737 ADDOP(c, ROT_FOUR);
1738 }
Mark Shannonfee55262019-11-21 09:11:43 +00001739 ADDOP(c, POP_EXCEPT);
1740 if (info->fb_datum) {
1741 ADDOP_LOAD_CONST(c, Py_None);
1742 compiler_nameop(c, info->fb_datum, Store);
1743 compiler_nameop(c, info->fb_datum, Del);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001744 }
Mark Shannonfee55262019-11-21 09:11:43 +00001745 return 1;
1746
1747 case POP_VALUE:
1748 if (preserve_tos) {
1749 ADDOP(c, ROT_TWO);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001750 }
Mark Shannonfee55262019-11-21 09:11:43 +00001751 ADDOP(c, POP_TOP);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001752 return 1;
1753 }
1754 Py_UNREACHABLE();
1755}
1756
Mark Shannonfee55262019-11-21 09:11:43 +00001757/** Unwind block stack. If loop is not NULL, then stop when the first loop is encountered. */
1758static int
1759compiler_unwind_fblock_stack(struct compiler *c, int preserve_tos, struct fblockinfo **loop) {
1760 if (c->u->u_nfblocks == 0) {
1761 return 1;
1762 }
1763 struct fblockinfo *top = &c->u->u_fblock[c->u->u_nfblocks-1];
1764 if (loop != NULL && (top->fb_type == WHILE_LOOP || top->fb_type == FOR_LOOP)) {
1765 *loop = top;
1766 return 1;
1767 }
1768 struct fblockinfo copy = *top;
1769 c->u->u_nfblocks--;
1770 if (!compiler_unwind_fblock(c, &copy, preserve_tos)) {
1771 return 0;
1772 }
1773 if (!compiler_unwind_fblock_stack(c, preserve_tos, loop)) {
1774 return 0;
1775 }
1776 c->u->u_fblock[c->u->u_nfblocks] = copy;
1777 c->u->u_nfblocks++;
1778 return 1;
1779}
1780
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001781/* Compile a sequence of statements, checking for a docstring
1782 and for annotations. */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001783
1784static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001785compiler_body(struct compiler *c, asdl_stmt_seq *stmts)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786{
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001787 int i = 0;
1788 stmt_ty st;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001789 PyObject *docstring;
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001790
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001791 /* Set current line number to the line number of first statement.
1792 This way line number for SETUP_ANNOTATIONS will always
1793 coincide with the line number of first "real" statement in module.
Hansraj Das01171eb2019-10-09 07:54:02 +05301794 If body is empty, then lineno will be set later in assemble. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001795 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && asdl_seq_LEN(stmts)) {
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001796 st = (stmt_ty)asdl_seq_GET(stmts, 0);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02001797 SET_LOC(c, st);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001798 }
1799 /* Every annotated class and module should have __annotations__. */
1800 if (find_ann(stmts)) {
1801 ADDOP(c, SETUP_ANNOTATIONS);
1802 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001803 if (!asdl_seq_LEN(stmts))
1804 return 1;
INADA Naokicb41b272017-02-23 00:31:59 +09001805 /* if not -OO mode, set docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03001806 if (c->c_optimize < 2) {
1807 docstring = _PyAST_GetDocString(stmts);
1808 if (docstring) {
1809 i = 1;
1810 st = (stmt_ty)asdl_seq_GET(stmts, 0);
1811 assert(st->kind == Expr_kind);
1812 VISIT(c, expr, st->v.Expr.value);
1813 if (!compiler_nameop(c, __doc__, Store))
1814 return 0;
1815 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 }
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001817 for (; i < asdl_seq_LEN(stmts); i++)
1818 VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820}
1821
1822static PyCodeObject *
1823compiler_mod(struct compiler *c, mod_ty mod)
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001824{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 PyCodeObject *co;
1826 int addNone = 1;
1827 static PyObject *module;
1828 if (!module) {
1829 module = PyUnicode_InternFromString("<module>");
1830 if (!module)
1831 return NULL;
1832 }
1833 /* Use 0 for firstlineno initially, will fixup in assemble(). */
Mark Shannon877df852020-11-12 09:43:29 +00001834 if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 1))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 return NULL;
1836 switch (mod->kind) {
1837 case Module_kind:
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03001838 if (!compiler_body(c, mod->v.Module.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 compiler_exit_scope(c);
1840 return 0;
1841 }
1842 break;
1843 case Interactive_kind:
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001844 if (find_ann(mod->v.Interactive.body)) {
1845 ADDOP(c, SETUP_ANNOTATIONS);
1846 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 c->c_interactive = 1;
Pablo Galindoa5634c42020-09-16 19:42:00 +01001848 VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 break;
1850 case Expression_kind:
1851 VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
1852 addNone = 0;
1853 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 default:
1855 PyErr_Format(PyExc_SystemError,
1856 "module kind %d should not be possible",
1857 mod->kind);
1858 return 0;
1859 }
1860 co = assemble(c, addNone);
1861 compiler_exit_scope(c);
1862 return co;
Guido van Rossum10dc2e81990-11-18 17:27:39 +00001863}
1864
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865/* The test for LOCAL must come before the test for FREE in order to
1866 handle classes where name is both local and free. The local var is
1867 a method and the free var is a free var referenced within a method.
Jeremy Hyltone36f7782001-01-19 03:21:30 +00001868*/
1869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870static int
1871get_ref_type(struct compiler *c, PyObject *name)
1872{
Victor Stinner0b1bc562013-05-16 22:17:17 +02001873 int scope;
Benjamin Peterson312595c2013-05-15 15:26:42 -05001874 if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02001875 _PyUnicode_EqualToASCIIString(name, "__class__"))
Benjamin Peterson312595c2013-05-15 15:26:42 -05001876 return CELL;
Victor Stinner0b1bc562013-05-16 22:17:17 +02001877 scope = PyST_GetScope(c->u->u_ste, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (scope == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001879 _Py_FatalErrorFormat(__func__,
1880 "unknown scope for %.100s in %.100s(%s)\n"
1881 "symbols: %s\nlocals: %s\nglobals: %s",
1882 PyUnicode_AsUTF8(name),
1883 PyUnicode_AsUTF8(c->u->u_name),
1884 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)),
1885 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)),
1886 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)),
1887 PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 }
Tim Peters2a7f3842001-06-09 09:26:21 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 return scope;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001891}
1892
1893static int
1894compiler_lookup_arg(PyObject *dict, PyObject *name)
1895{
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001896 PyObject *v;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02001897 v = PyDict_GetItemWithError(dict, name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898 if (v == NULL)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00001899 return -1;
Christian Heimes217cfd12007-12-02 14:31:20 +00001900 return PyLong_AS_LONG(v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901}
1902
1903static int
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001904compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905{
Victor Stinnerad9a0662013-11-19 22:23:20 +01001906 Py_ssize_t i, free = PyCode_GetNumFree(co);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01001907 if (qualname == NULL)
1908 qualname = co->co_name;
1909
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001910 if (free) {
1911 for (i = 0; i < free; ++i) {
1912 /* Bypass com_addop_varname because it will generate
1913 LOAD_DEREF but LOAD_CLOSURE is needed.
1914 */
1915 PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
1916 int arg, reftype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001917
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001918 /* Special case: If a class contains a method with a
1919 free variable that has the same name as a method,
1920 the name will be considered free *and* local in the
1921 class. It should be handled by the closure, as
Min ho Kimc4cacc82019-07-31 08:16:13 +10001922 well as by the normal name lookup logic.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001923 */
1924 reftype = get_ref_type(c, name);
1925 if (reftype == CELL)
1926 arg = compiler_lookup_arg(c->u->u_cellvars, name);
1927 else /* (reftype == FREE) */
1928 arg = compiler_lookup_arg(c->u->u_freevars, name);
1929 if (arg == -1) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001930 _Py_FatalErrorFormat(__func__,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001931 "lookup %s in %s %d %d\n"
1932 "freevars of %s: %s\n",
1933 PyUnicode_AsUTF8(PyObject_Repr(name)),
1934 PyUnicode_AsUTF8(c->u->u_name),
1935 reftype, arg,
1936 PyUnicode_AsUTF8(co->co_name),
1937 PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars)));
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001938 }
1939 ADDOP_I(c, LOAD_CLOSURE, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001941 flags |= 0x08;
1942 ADDOP_I(c, BUILD_TUPLE, free);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03001944 ADDOP_LOAD_CONST(c, (PyObject*)co);
1945 ADDOP_LOAD_CONST(c, qualname);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001946 ADDOP_I(c, MAKE_FUNCTION, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001948}
1949
1950static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001951compiler_decorators(struct compiler *c, asdl_expr_seq* decos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 int i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 if (!decos)
1956 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 for (i = 0; i < asdl_seq_LEN(decos); i++) {
1959 VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
1960 }
1961 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001962}
1963
1964static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01001965compiler_visit_kwonlydefaults(struct compiler *c, asdl_arg_seq *kwonlyargs,
1966 asdl_expr_seq *kw_defaults)
Guido van Rossum4f72a782006-10-27 23:31:49 +00001967{
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001968 /* Push a dict of keyword-only default values.
1969
1970 Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed.
1971 */
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001972 int i;
1973 PyObject *keys = NULL;
1974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
1976 arg_ty arg = asdl_seq_GET(kwonlyargs, i);
1977 expr_ty default_ = asdl_seq_GET(kw_defaults, i);
1978 if (default_) {
Benjamin Peterson32c59b62012-04-17 19:53:21 -04001979 PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001980 if (!mangled) {
1981 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001983 if (keys == NULL) {
1984 keys = PyList_New(1);
1985 if (keys == NULL) {
1986 Py_DECREF(mangled);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03001987 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03001988 }
1989 PyList_SET_ITEM(keys, 0, mangled);
1990 }
1991 else {
1992 int res = PyList_Append(keys, mangled);
1993 Py_DECREF(mangled);
1994 if (res == -1) {
1995 goto error;
1996 }
1997 }
1998 if (!compiler_visit_expr(c, default_)) {
1999 goto error;
2000 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
2002 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002003 if (keys != NULL) {
2004 Py_ssize_t default_count = PyList_GET_SIZE(keys);
2005 PyObject *keys_tuple = PyList_AsTuple(keys);
2006 Py_DECREF(keys);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002007 ADDOP_LOAD_CONST_NEW(c, keys_tuple);
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002008 ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002009 assert(default_count > 0);
2010 return 1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002011 }
2012 else {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002013 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002014 }
2015
2016error:
2017 Py_XDECREF(keys);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002018 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002019}
2020
2021static int
Guido van Rossum95e4d582018-01-26 08:20:18 -08002022compiler_visit_annexpr(struct compiler *c, expr_ty annotation)
2023{
Serhiy Storchaka64fddc42018-05-17 06:17:48 +03002024 ADDOP_LOAD_CONST_NEW(c, _PyAST_ExprAsUnicode(annotation));
Guido van Rossum95e4d582018-01-26 08:20:18 -08002025 return 1;
2026}
2027
2028static int
Neal Norwitzc1505362006-12-28 06:47:50 +00002029compiler_visit_argannotation(struct compiler *c, identifier id,
Yurii Karabas73019792020-11-25 12:43:18 +02002030 expr_ty annotation, Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (annotation) {
Yurii Karabas73019792020-11-25 12:43:18 +02002033 PyObject *mangled = _Py_Mangle(c->u->u_private, id);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002034 if (!mangled)
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002035 return 0;
Yurii Karabas73019792020-11-25 12:43:18 +02002036
2037 ADDOP_LOAD_CONST(c, mangled);
Yury Selivanov34ce99f2014-02-18 12:49:41 -05002038 Py_DECREF(mangled);
Yurii Karabas73019792020-11-25 12:43:18 +02002039 VISIT(c, annexpr, annotation);
2040 *annotations_len += 2;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002042 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002043}
2044
2045static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002046compiler_visit_argannotations(struct compiler *c, asdl_arg_seq* args,
Yurii Karabas73019792020-11-25 12:43:18 +02002047 Py_ssize_t *annotations_len)
Neal Norwitzc1505362006-12-28 06:47:50 +00002048{
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002049 int i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 for (i = 0; i < asdl_seq_LEN(args); i++) {
2051 arg_ty arg = (arg_ty)asdl_seq_GET(args, i);
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002052 if (!compiler_visit_argannotation(
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 c,
2054 arg->arg,
2055 arg->annotation,
Yurii Karabas73019792020-11-25 12:43:18 +02002056 annotations_len))
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002057 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 }
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002059 return 1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002060}
2061
2062static int
2063compiler_visit_annotations(struct compiler *c, arguments_ty args,
2064 expr_ty returns)
2065{
Yurii Karabas73019792020-11-25 12:43:18 +02002066 /* Push arg annotation names and values.
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002067 The expressions are evaluated out-of-order wrt the source code.
Neal Norwitzc1505362006-12-28 06:47:50 +00002068
Yurii Karabas73019792020-11-25 12:43:18 +02002069 Return 0 on error, -1 if no annotations pushed, 1 if a annotations is pushed.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 */
2071 static identifier return_str;
Yurii Karabas73019792020-11-25 12:43:18 +02002072 Py_ssize_t annotations_len = 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002073
Yurii Karabas73019792020-11-25 12:43:18 +02002074 if (!compiler_visit_argannotations(c, args->args, &annotations_len))
2075 return 0;
2076 if (!compiler_visit_argannotations(c, args->posonlyargs, &annotations_len))
2077 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002078 if (args->vararg && args->vararg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002079 !compiler_visit_argannotation(c, args->vararg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002080 args->vararg->annotation, &annotations_len))
2081 return 0;
2082 if (!compiler_visit_argannotations(c, args->kwonlyargs, &annotations_len))
2083 return 0;
Benjamin Petersoncda75be2013-03-18 10:48:58 -07002084 if (args->kwarg && args->kwarg->annotation &&
Yury Selivanovf315c1c2015-07-23 09:10:44 +03002085 !compiler_visit_argannotation(c, args->kwarg->arg,
Yurii Karabas73019792020-11-25 12:43:18 +02002086 args->kwarg->annotation, &annotations_len))
2087 return 0;
Neal Norwitzc1505362006-12-28 06:47:50 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (!return_str) {
2090 return_str = PyUnicode_InternFromString("return");
2091 if (!return_str)
Yurii Karabas73019792020-11-25 12:43:18 +02002092 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 }
Yurii Karabas73019792020-11-25 12:43:18 +02002094 if (!compiler_visit_argannotation(c, return_str, returns, &annotations_len)) {
2095 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 }
2097
Yurii Karabas73019792020-11-25 12:43:18 +02002098 if (annotations_len) {
2099 ADDOP_I(c, BUILD_TUPLE, annotations_len);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002100 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 }
Neal Norwitzc1505362006-12-28 06:47:50 +00002102
Yurii Karabas73019792020-11-25 12:43:18 +02002103 return -1;
Neal Norwitzc1505362006-12-28 06:47:50 +00002104}
2105
2106static int
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002107compiler_visit_defaults(struct compiler *c, arguments_ty args)
2108{
2109 VISIT_SEQ(c, expr, args->defaults);
2110 ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults));
2111 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002112}
2113
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002114static Py_ssize_t
2115compiler_default_arguments(struct compiler *c, arguments_ty args)
2116{
2117 Py_ssize_t funcflags = 0;
2118 if (args->defaults && asdl_seq_LEN(args->defaults) > 0) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002119 if (!compiler_visit_defaults(c, args))
2120 return -1;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002121 funcflags |= 0x01;
2122 }
2123 if (args->kwonlyargs) {
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002124 int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002125 args->kw_defaults);
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002126 if (res == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002127 return -1;
2128 }
2129 else if (res > 0) {
2130 funcflags |= 0x02;
2131 }
2132 }
2133 return funcflags;
2134}
2135
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136static int
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002137forbidden_name(struct compiler *c, identifier name, expr_context_ty ctx)
2138{
2139
2140 if (ctx == Store && _PyUnicode_EqualToASCIIString(name, "__debug__")) {
2141 compiler_error(c, "cannot assign to __debug__");
2142 return 1;
2143 }
2144 return 0;
2145}
2146
2147static int
2148compiler_check_debug_one_arg(struct compiler *c, arg_ty arg)
2149{
2150 if (arg != NULL) {
2151 if (forbidden_name(c, arg->arg, Store))
2152 return 0;
2153 }
2154 return 1;
2155}
2156
2157static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01002158compiler_check_debug_args_seq(struct compiler *c, asdl_arg_seq *args)
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002159{
2160 if (args != NULL) {
Pablo Galindoee40e4b2020-04-23 03:43:08 +01002161 for (Py_ssize_t i = 0, n = asdl_seq_LEN(args); i < n; i++) {
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002162 if (!compiler_check_debug_one_arg(c, asdl_seq_GET(args, i)))
2163 return 0;
2164 }
2165 }
2166 return 1;
2167}
2168
2169static int
2170compiler_check_debug_args(struct compiler *c, arguments_ty args)
2171{
2172 if (!compiler_check_debug_args_seq(c, args->posonlyargs))
2173 return 0;
2174 if (!compiler_check_debug_args_seq(c, args->args))
2175 return 0;
2176 if (!compiler_check_debug_one_arg(c, args->vararg))
2177 return 0;
2178 if (!compiler_check_debug_args_seq(c, args->kwonlyargs))
2179 return 0;
2180 if (!compiler_check_debug_one_arg(c, args->kwarg))
2181 return 0;
2182 return 1;
2183}
2184
2185static int
Yury Selivanov75445082015-05-11 22:57:16 -04002186compiler_function(struct compiler *c, stmt_ty s, int is_async)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 PyCodeObject *co;
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002189 PyObject *qualname, *docstring = NULL;
Yury Selivanov75445082015-05-11 22:57:16 -04002190 arguments_ty args;
2191 expr_ty returns;
2192 identifier name;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002193 asdl_expr_seq* decos;
2194 asdl_stmt_seq *body;
INADA Naokicb41b272017-02-23 00:31:59 +09002195 Py_ssize_t i, funcflags;
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002196 int annotations;
Yury Selivanov75445082015-05-11 22:57:16 -04002197 int scope_type;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002198 int firstlineno;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002199
Yury Selivanov75445082015-05-11 22:57:16 -04002200 if (is_async) {
2201 assert(s->kind == AsyncFunctionDef_kind);
2202
2203 args = s->v.AsyncFunctionDef.args;
2204 returns = s->v.AsyncFunctionDef.returns;
2205 decos = s->v.AsyncFunctionDef.decorator_list;
2206 name = s->v.AsyncFunctionDef.name;
2207 body = s->v.AsyncFunctionDef.body;
2208
2209 scope_type = COMPILER_SCOPE_ASYNC_FUNCTION;
2210 } else {
2211 assert(s->kind == FunctionDef_kind);
2212
2213 args = s->v.FunctionDef.args;
2214 returns = s->v.FunctionDef.returns;
2215 decos = s->v.FunctionDef.decorator_list;
2216 name = s->v.FunctionDef.name;
2217 body = s->v.FunctionDef.body;
2218
2219 scope_type = COMPILER_SCOPE_FUNCTION;
2220 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002222 if (!compiler_check_debug_args(c, args))
2223 return 0;
2224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (!compiler_decorators(c, decos))
2226 return 0;
Guido van Rossum4f72a782006-10-27 23:31:49 +00002227
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002228 firstlineno = s->lineno;
2229 if (asdl_seq_LEN(decos)) {
2230 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2231 }
2232
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002233 funcflags = compiler_default_arguments(c, args);
2234 if (funcflags == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 return 0;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002236 }
2237
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002238 annotations = compiler_visit_annotations(c, args, returns);
2239 if (annotations == 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002240 return 0;
2241 }
Serhiy Storchaka607f8a52016-06-15 20:07:53 +03002242 else if (annotations > 0) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002243 funcflags |= 0x04;
2244 }
2245
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002246 if (!compiler_enter_scope(c, name, scope_type, (void *)s, firstlineno)) {
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002247 return 0;
2248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249
INADA Naokicb41b272017-02-23 00:31:59 +09002250 /* if not -OO mode, add docstring */
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002251 if (c->c_optimize < 2) {
2252 docstring = _PyAST_GetDocString(body);
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002253 }
Serhiy Storchaka143ce5c2018-05-30 10:56:16 +03002254 if (compiler_add_const(c, docstring ? docstring : Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 compiler_exit_scope(c);
2256 return 0;
2257 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002260 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
Mark Shannon877df852020-11-12 09:43:29 +00002262 for (i = docstring ? 1 : 0; i < asdl_seq_LEN(body); i++) {
Mark Shannonfd009e62020-11-13 12:53:53 +00002263 VISIT_IN_SCOPE(c, stmt, (stmt_ty)asdl_seq_GET(body, i));
Mark Shannon877df852020-11-12 09:43:29 +00002264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002266 qualname = c->u->u_qualname;
2267 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002269 if (co == NULL) {
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002270 Py_XDECREF(qualname);
2271 Py_XDECREF(co);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 return 0;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002273 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002275 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002276 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 Py_DECREF(co);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* decorators */
2280 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2281 ADDOP_I(c, CALL_FUNCTION, 1);
2282 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002283
Yury Selivanov75445082015-05-11 22:57:16 -04002284 return compiler_nameop(c, name, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
2287static int
2288compiler_class(struct compiler *c, stmt_ty s)
2289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 PyCodeObject *co;
2291 PyObject *str;
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002292 int i, firstlineno;
Pablo Galindoa5634c42020-09-16 19:42:00 +01002293 asdl_expr_seq *decos = s->v.ClassDef.decorator_list;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (!compiler_decorators(c, decos))
2296 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002297
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002298 firstlineno = s->lineno;
2299 if (asdl_seq_LEN(decos)) {
2300 firstlineno = ((expr_ty)asdl_seq_GET(decos, 0))->lineno;
2301 }
2302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 /* ultimately generate code for:
2304 <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>)
2305 where:
2306 <func> is a function/closure created from the class body;
2307 it has a single argument (__locals__) where the dict
2308 (or MutableSequence) representing the locals is passed
2309 <name> is the class name
2310 <bases> is the positional arguments and *varargs argument
2311 <keywords> is the keyword arguments and **kwds argument
2312 This borrows from compiler_call.
2313 */
Guido van Rossum52cc1d82007-03-18 15:41:51 +00002314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 /* 1. compile the class body into a code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002316 if (!compiler_enter_scope(c, s->v.ClassDef.name,
Serhiy Storchaka95b6acf2018-10-30 13:16:02 +02002317 COMPILER_SCOPE_CLASS, (void *)s, firstlineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 return 0;
2319 /* this block represents what we do in the new scope */
2320 {
2321 /* use the class name for name mangling */
2322 Py_INCREF(s->v.ClassDef.name);
Serhiy Storchaka48842712016-04-06 09:45:48 +03002323 Py_XSETREF(c->u->u_private, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 /* load (global) __name__ ... */
2325 str = PyUnicode_InternFromString("__name__");
2326 if (!str || !compiler_nameop(c, str, Load)) {
2327 Py_XDECREF(str);
2328 compiler_exit_scope(c);
2329 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002330 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 Py_DECREF(str);
2332 /* ... and store it as __module__ */
2333 str = PyUnicode_InternFromString("__module__");
2334 if (!str || !compiler_nameop(c, str, Store)) {
2335 Py_XDECREF(str);
2336 compiler_exit_scope(c);
2337 return 0;
2338 }
2339 Py_DECREF(str);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002340 assert(c->u->u_qualname);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002341 ADDOP_LOAD_CONST(c, c->u->u_qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002342 str = PyUnicode_InternFromString("__qualname__");
2343 if (!str || !compiler_nameop(c, str, Store)) {
2344 Py_XDECREF(str);
2345 compiler_exit_scope(c);
2346 return 0;
2347 }
2348 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* compile the body proper */
Serhiy Storchaka73cbe7a2018-05-29 12:04:55 +03002350 if (!compiler_body(c, s->v.ClassDef.body)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 compiler_exit_scope(c);
2352 return 0;
2353 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002354 /* Return __classcell__ if it is referenced, otherwise return None */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002355 if (c->u->u_ste->ste_needs_class_closure) {
Nick Coghlan19d24672016-12-05 16:47:55 +10002356 /* Store __classcell__ into class namespace & return it */
Benjamin Peterson312595c2013-05-15 15:26:42 -05002357 str = PyUnicode_InternFromString("__class__");
2358 if (str == NULL) {
2359 compiler_exit_scope(c);
2360 return 0;
2361 }
2362 i = compiler_lookup_arg(c->u->u_cellvars, str);
2363 Py_DECREF(str);
Victor Stinner98e818b2013-11-05 18:07:34 +01002364 if (i < 0) {
2365 compiler_exit_scope(c);
2366 return 0;
2367 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002368 assert(i == 0);
Nick Coghlan944368e2016-09-11 14:45:49 +10002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 ADDOP_I(c, LOAD_CLOSURE, i);
Nick Coghlan19d24672016-12-05 16:47:55 +10002371 ADDOP(c, DUP_TOP);
Nick Coghlan944368e2016-09-11 14:45:49 +10002372 str = PyUnicode_InternFromString("__classcell__");
2373 if (!str || !compiler_nameop(c, str, Store)) {
2374 Py_XDECREF(str);
2375 compiler_exit_scope(c);
2376 return 0;
2377 }
2378 Py_DECREF(str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 }
Benjamin Peterson312595c2013-05-15 15:26:42 -05002380 else {
Nick Coghlan19d24672016-12-05 16:47:55 +10002381 /* No methods referenced __class__, so just return None */
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02002382 assert(PyDict_GET_SIZE(c->u->u_cellvars) == 0);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002383 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson312595c2013-05-15 15:26:42 -05002384 }
Nick Coghlan19d24672016-12-05 16:47:55 +10002385 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 /* create the code object */
2387 co = assemble(c, 1);
2388 }
2389 /* leave the new scope */
2390 compiler_exit_scope(c);
2391 if (co == NULL)
2392 return 0;
Guido van Rossumd59da4b2007-05-22 18:11:13 +00002393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* 2. load the 'build_class' function */
2395 ADDOP(c, LOAD_BUILD_CLASS);
2396
2397 /* 3. load a function (or closure) made from the code object */
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002398 compiler_make_closure(c, co, 0, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 Py_DECREF(co);
2400
2401 /* 4. load class name */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002402 ADDOP_LOAD_CONST(c, s->v.ClassDef.name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403
2404 /* 5. generate the rest of the code for the call */
Pablo Galindoa5634c42020-09-16 19:42:00 +01002405 if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return 0;
2407
2408 /* 6. apply decorators */
2409 for (i = 0; i < asdl_seq_LEN(decos); i++) {
2410 ADDOP_I(c, CALL_FUNCTION, 1);
2411 }
2412
2413 /* 7. store into <name> */
2414 if (!compiler_nameop(c, s->v.ClassDef.name, Store))
2415 return 0;
2416 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417}
2418
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02002419/* Return 0 if the expression is a constant value except named singletons.
2420 Return 1 otherwise. */
2421static int
2422check_is_arg(expr_ty e)
2423{
2424 if (e->kind != Constant_kind) {
2425 return 1;
2426 }
2427 PyObject *value = e->v.Constant.value;
2428 return (value == Py_None
2429 || value == Py_False
2430 || value == Py_True
2431 || value == Py_Ellipsis);
2432}
2433
2434/* Check operands of identity chacks ("is" and "is not").
2435 Emit a warning if any operand is a constant except named singletons.
2436 Return 0 on error.
2437 */
2438static int
2439check_compare(struct compiler *c, expr_ty e)
2440{
2441 Py_ssize_t i, n;
2442 int left = check_is_arg(e->v.Compare.left);
2443 n = asdl_seq_LEN(e->v.Compare.ops);
2444 for (i = 0; i < n; i++) {
2445 cmpop_ty op = (cmpop_ty)asdl_seq_GET(e->v.Compare.ops, i);
2446 int right = check_is_arg((expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2447 if (op == Is || op == IsNot) {
2448 if (!right || !left) {
2449 const char *msg = (op == Is)
2450 ? "\"is\" with a literal. Did you mean \"==\"?"
2451 : "\"is not\" with a literal. Did you mean \"!=\"?";
2452 return compiler_warn(c, msg);
2453 }
2454 }
2455 left = right;
2456 }
2457 return 1;
2458}
2459
Mark Shannon9af0e472020-01-14 10:12:45 +00002460static int compiler_addcompare(struct compiler *c, cmpop_ty op)
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002461{
Mark Shannon9af0e472020-01-14 10:12:45 +00002462 int cmp;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002463 switch (op) {
2464 case Eq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002465 cmp = Py_EQ;
2466 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002467 case NotEq:
Mark Shannon9af0e472020-01-14 10:12:45 +00002468 cmp = Py_NE;
2469 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002470 case Lt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002471 cmp = Py_LT;
2472 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002473 case LtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002474 cmp = Py_LE;
2475 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002476 case Gt:
Mark Shannon9af0e472020-01-14 10:12:45 +00002477 cmp = Py_GT;
2478 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002479 case GtE:
Mark Shannon9af0e472020-01-14 10:12:45 +00002480 cmp = Py_GE;
2481 break;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002482 case Is:
Mark Shannon9af0e472020-01-14 10:12:45 +00002483 ADDOP_I(c, IS_OP, 0);
2484 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002485 case IsNot:
Mark Shannon9af0e472020-01-14 10:12:45 +00002486 ADDOP_I(c, IS_OP, 1);
2487 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002488 case In:
Mark Shannon9af0e472020-01-14 10:12:45 +00002489 ADDOP_I(c, CONTAINS_OP, 0);
2490 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002491 case NotIn:
Mark Shannon9af0e472020-01-14 10:12:45 +00002492 ADDOP_I(c, CONTAINS_OP, 1);
2493 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002494 default:
Mark Shannon9af0e472020-01-14 10:12:45 +00002495 Py_UNREACHABLE();
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002496 }
Mark Shannon9af0e472020-01-14 10:12:45 +00002497 ADDOP_I(c, COMPARE_OP, cmp);
2498 return 1;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002499}
2500
Mark Shannon9af0e472020-01-14 10:12:45 +00002501
2502
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002503static int
2504compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
2505{
2506 switch (e->kind) {
2507 case UnaryOp_kind:
2508 if (e->v.UnaryOp.op == Not)
2509 return compiler_jump_if(c, e->v.UnaryOp.operand, next, !cond);
2510 /* fallback to general implementation */
2511 break;
2512 case BoolOp_kind: {
Pablo Galindoa5634c42020-09-16 19:42:00 +01002513 asdl_expr_seq *s = e->v.BoolOp.values;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002514 Py_ssize_t i, n = asdl_seq_LEN(s) - 1;
2515 assert(n >= 0);
2516 int cond2 = e->v.BoolOp.op == Or;
2517 basicblock *next2 = next;
2518 if (!cond2 != !cond) {
2519 next2 = compiler_new_block(c);
2520 if (next2 == NULL)
2521 return 0;
2522 }
2523 for (i = 0; i < n; ++i) {
2524 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, i), next2, cond2))
2525 return 0;
2526 }
2527 if (!compiler_jump_if(c, (expr_ty)asdl_seq_GET(s, n), next, cond))
2528 return 0;
2529 if (next2 != next)
2530 compiler_use_next_block(c, next2);
2531 return 1;
2532 }
2533 case IfExp_kind: {
2534 basicblock *end, *next2;
2535 end = compiler_new_block(c);
2536 if (end == NULL)
2537 return 0;
2538 next2 = compiler_new_block(c);
2539 if (next2 == NULL)
2540 return 0;
2541 if (!compiler_jump_if(c, e->v.IfExp.test, next2, 0))
2542 return 0;
2543 if (!compiler_jump_if(c, e->v.IfExp.body, next, cond))
2544 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002545 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002546 compiler_use_next_block(c, next2);
2547 if (!compiler_jump_if(c, e->v.IfExp.orelse, next, cond))
2548 return 0;
2549 compiler_use_next_block(c, end);
2550 return 1;
2551 }
2552 case Compare_kind: {
2553 Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
2554 if (n > 0) {
Serhiy Storchaka45835252019-02-16 08:29:46 +02002555 if (!check_compare(c, e)) {
2556 return 0;
2557 }
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002558 basicblock *cleanup = compiler_new_block(c);
2559 if (cleanup == NULL)
2560 return 0;
2561 VISIT(c, expr, e->v.Compare.left);
2562 for (i = 0; i < n; i++) {
2563 VISIT(c, expr,
2564 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
2565 ADDOP(c, DUP_TOP);
2566 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00002567 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01002568 ADDOP_JUMP(c, POP_JUMP_IF_FALSE, cleanup);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002569 NEXT_BLOCK(c);
2570 }
2571 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00002572 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Mark Shannon582aaf12020-08-04 17:30:11 +01002573 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002574 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002575 basicblock *end = compiler_new_block(c);
2576 if (end == NULL)
2577 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00002578 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002579 compiler_use_next_block(c, cleanup);
2580 ADDOP(c, POP_TOP);
2581 if (!cond) {
Mark Shannon127dde52021-01-04 18:06:55 +00002582 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, next);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002583 }
2584 compiler_use_next_block(c, end);
2585 return 1;
2586 }
2587 /* fallback to general implementation */
2588 break;
2589 }
2590 default:
2591 /* fallback to general implementation */
2592 break;
2593 }
2594
2595 /* general implementation */
2596 VISIT(c, expr, e);
Mark Shannon582aaf12020-08-04 17:30:11 +01002597 ADDOP_JUMP(c, cond ? POP_JUMP_IF_TRUE : POP_JUMP_IF_FALSE, next);
Mark Shannon266b4622020-11-17 19:30:14 +00002598 NEXT_BLOCK(c);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002599 return 1;
2600}
2601
2602static int
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002603compiler_ifexp(struct compiler *c, expr_ty e)
2604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 basicblock *end, *next;
2606
2607 assert(e->kind == IfExp_kind);
2608 end = compiler_new_block(c);
2609 if (end == NULL)
2610 return 0;
2611 next = compiler_new_block(c);
2612 if (next == NULL)
2613 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002614 if (!compiler_jump_if(c, e->v.IfExp.test, next, 0))
2615 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 VISIT(c, expr, e->v.IfExp.body);
Mark Shannon127dde52021-01-04 18:06:55 +00002617 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 compiler_use_next_block(c, next);
2619 VISIT(c, expr, e->v.IfExp.orelse);
2620 compiler_use_next_block(c, end);
2621 return 1;
Thomas Woutersdca3b9c2006-02-27 00:24:13 +00002622}
2623
2624static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625compiler_lambda(struct compiler *c, expr_ty e)
2626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 PyCodeObject *co;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002628 PyObject *qualname;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 static identifier name;
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002630 Py_ssize_t funcflags;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 arguments_ty args = e->v.Lambda.args;
2632 assert(e->kind == Lambda_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633
Pablo Galindoc5fc1562020-04-22 23:29:27 +01002634 if (!compiler_check_debug_args(c, args))
2635 return 0;
2636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 if (!name) {
2638 name = PyUnicode_InternFromString("<lambda>");
2639 if (!name)
2640 return 0;
2641 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002642
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002643 funcflags = compiler_default_arguments(c, args);
2644 if (funcflags == -1) {
2645 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 }
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002647
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002648 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002649 (void *)e, e->lineno))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 return 0;
Neal Norwitz4737b232005-11-19 23:58:29 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 /* Make None the first constant, so the lambda can't have a
2653 docstring. */
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002654 if (compiler_add_const(c, Py_None) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 c->u->u_argcount = asdl_seq_LEN(args->args);
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01002658 c->u->u_posonlyargcount = asdl_seq_LEN(args->posonlyargs);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs);
2660 VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
2661 if (c->u->u_ste->ste_generator) {
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002662 co = assemble(c, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 }
2664 else {
2665 ADDOP_IN_SCOPE(c, RETURN_VALUE);
Serhiy Storchakac775ad62015-03-11 18:20:35 +02002666 co = assemble(c, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002668 qualname = c->u->u_qualname;
2669 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 compiler_exit_scope(c);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04002671 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002673
Serhiy Storchaka64204de2016-06-12 17:36:24 +03002674 compiler_make_closure(c, co, funcflags, qualname);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01002675 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 Py_DECREF(co);
2677
2678 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002679}
2680
2681static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002682compiler_if(struct compiler *c, stmt_ty s)
2683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002684 basicblock *end, *next;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 assert(s->kind == If_kind);
2686 end = compiler_new_block(c);
Mark Shannon8473cf82020-12-15 11:07:50 +00002687 if (end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 return 0;
Mark Shannon8473cf82020-12-15 11:07:50 +00002689 }
2690 if (asdl_seq_LEN(s->v.If.orelse)) {
2691 next = compiler_new_block(c);
2692 if (next == NULL) {
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03002693 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002694 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002695 }
2696 else {
2697 next = end;
2698 }
2699 if (!compiler_jump_if(c, s->v.If.test, next, 0)) {
2700 return 0;
2701 }
2702 VISIT_SEQ(c, stmt, s->v.If.body);
2703 if (asdl_seq_LEN(s->v.If.orelse)) {
Mark Shannon127dde52021-01-04 18:06:55 +00002704 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Mark Shannon8473cf82020-12-15 11:07:50 +00002705 compiler_use_next_block(c, next);
2706 VISIT_SEQ(c, stmt, s->v.If.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 }
2708 compiler_use_next_block(c, end);
2709 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002710}
2711
2712static int
2713compiler_for(struct compiler *c, stmt_ty s)
2714{
Mark Shannon5977a792020-12-02 13:31:40 +00002715 basicblock *start, *body, *cleanup, *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 start = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002718 body = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 cleanup = compiler_new_block(c);
2720 end = compiler_new_block(c);
Mark Shannon5977a792020-12-02 13:31:40 +00002721 if (start == NULL || body == NULL || end == NULL || cleanup == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002722 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002723 }
2724 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002726 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 VISIT(c, expr, s->v.For.iter);
2728 ADDOP(c, GET_ITER);
2729 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01002730 ADDOP_JUMP(c, FOR_ITER, cleanup);
Mark Shannon5977a792020-12-02 13:31:40 +00002731 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 VISIT(c, expr, s->v.For.target);
2733 VISIT_SEQ(c, stmt, s->v.For.body);
Mark Shannonf5e97b72020-12-14 11:28:39 +00002734 /* Mark jump as artificial */
2735 c->u->u_lineno = -1;
Mark Shannon582aaf12020-08-04 17:30:11 +01002736 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 compiler_use_next_block(c, cleanup);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002738
2739 compiler_pop_fblock(c, FOR_LOOP, start);
2740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 VISIT_SEQ(c, stmt, s->v.For.orelse);
2742 compiler_use_next_block(c, end);
2743 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002744}
2745
Yury Selivanov75445082015-05-11 22:57:16 -04002746
2747static int
2748compiler_async_for(struct compiler *c, stmt_ty s)
2749{
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002750 basicblock *start, *except, *end;
Pablo Galindo90235812020-03-15 04:29:22 +00002751 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07002752 c->u->u_ste->ste_coroutine = 1;
2753 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION) {
Zsolt Dollensteine2396502018-04-27 08:58:56 -07002754 return compiler_error(c, "'async for' outside async function");
2755 }
2756
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002757 start = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002758 except = compiler_new_block(c);
2759 end = compiler_new_block(c);
Yury Selivanov75445082015-05-11 22:57:16 -04002760
Mark Shannonfee55262019-11-21 09:11:43 +00002761 if (start == NULL || except == NULL || end == NULL) {
Yury Selivanov75445082015-05-11 22:57:16 -04002762 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002763 }
Yury Selivanov75445082015-05-11 22:57:16 -04002764 VISIT(c, expr, s->v.AsyncFor.iter);
2765 ADDOP(c, GET_AITER);
Yury Selivanov75445082015-05-11 22:57:16 -04002766
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002767 compiler_use_next_block(c, start);
Mark Shannonfee55262019-11-21 09:11:43 +00002768 if (!compiler_push_fblock(c, FOR_LOOP, start, end, NULL)) {
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002769 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00002770 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002771 /* SETUP_FINALLY to guard the __anext__ call */
Mark Shannon582aaf12020-08-04 17:30:11 +01002772 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov75445082015-05-11 22:57:16 -04002773 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002774 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04002775 ADDOP(c, YIELD_FROM);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002776 ADDOP(c, POP_BLOCK); /* for SETUP_FINALLY */
Yury Selivanov75445082015-05-11 22:57:16 -04002777
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002778 /* Success block for __anext__ */
2779 VISIT(c, expr, s->v.AsyncFor.target);
2780 VISIT_SEQ(c, stmt, s->v.AsyncFor.body);
Mark Shannon582aaf12020-08-04 17:30:11 +01002781 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002782
2783 compiler_pop_fblock(c, FOR_LOOP, start);
Yury Selivanov75445082015-05-11 22:57:16 -04002784
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002785 /* Except block for __anext__ */
Yury Selivanov75445082015-05-11 22:57:16 -04002786 compiler_use_next_block(c, except);
Mark Shannon877df852020-11-12 09:43:29 +00002787
2788 c->u->u_lineno = -1;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02002789 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov75445082015-05-11 22:57:16 -04002790
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002791 /* `else` block */
Yury Selivanov75445082015-05-11 22:57:16 -04002792 VISIT_SEQ(c, stmt, s->v.For.orelse);
2793
2794 compiler_use_next_block(c, end);
2795
2796 return 1;
2797}
2798
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002799static int
2800compiler_while(struct compiler *c, stmt_ty s)
2801{
Mark Shannon266b4622020-11-17 19:30:14 +00002802 basicblock *loop, *body, *end, *anchor = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002803 loop = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002804 body = compiler_new_block(c);
2805 anchor = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 end = compiler_new_block(c);
Mark Shannon266b4622020-11-17 19:30:14 +00002807 if (loop == NULL || body == NULL || anchor == NULL || end == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 compiler_use_next_block(c, loop);
Mark Shannon266b4622020-11-17 19:30:14 +00002811 if (!compiler_push_fblock(c, WHILE_LOOP, loop, end, NULL)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 }
Mark Shannon8473cf82020-12-15 11:07:50 +00002814 if (!compiler_jump_if(c, s->v.While.test, anchor, 0)) {
2815 return 0;
Mark Shannon266b4622020-11-17 19:30:14 +00002816 }
2817
2818 compiler_use_next_block(c, body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 VISIT_SEQ(c, stmt, s->v.While.body);
Mark Shannon8473cf82020-12-15 11:07:50 +00002820 SET_LOC(c, s);
2821 if (!compiler_jump_if(c, s->v.While.test, body, 1)) {
2822 return 0;
2823 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002824
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002825 compiler_pop_fblock(c, WHILE_LOOP, loop);
2826
Mark Shannon266b4622020-11-17 19:30:14 +00002827 compiler_use_next_block(c, anchor);
2828 if (s->v.While.orelse) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 VISIT_SEQ(c, stmt, s->v.While.orelse);
Mark Shannon266b4622020-11-17 19:30:14 +00002830 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 compiler_use_next_block(c, end);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834}
2835
2836static int
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002837compiler_return(struct compiler *c, stmt_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002838{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002839 int preserve_tos = ((s->v.Return.value != NULL) &&
Serhiy Storchaka3f228112018-09-27 17:42:37 +03002840 (s->v.Return.value->kind != Constant_kind));
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002841 if (c->u->u_ste->ste_type != FunctionBlock)
2842 return compiler_error(c, "'return' outside function");
2843 if (s->v.Return.value != NULL &&
2844 c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator)
2845 {
2846 return compiler_error(
2847 c, "'return' with value in async generator");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002849 if (preserve_tos) {
2850 VISIT(c, expr, s->v.Return.value);
Mark Shannon5274b682020-12-16 13:07:01 +00002851 } else {
2852 /* Emit instruction with line number for expression */
2853 if (s->v.Return.value != NULL) {
2854 SET_LOC(c, s->v.Return.value);
2855 ADDOP(c, NOP);
2856 }
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002857 }
Mark Shannonfee55262019-11-21 09:11:43 +00002858 if (!compiler_unwind_fblock_stack(c, preserve_tos, NULL))
2859 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002860 if (s->v.Return.value == NULL) {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03002861 ADDOP_LOAD_CONST(c, Py_None);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002862 }
2863 else if (!preserve_tos) {
Mark Shannon5274b682020-12-16 13:07:01 +00002864 ADDOP_LOAD_CONST(c, s->v.Return.value->v.Constant.value);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002865 }
2866 ADDOP(c, RETURN_VALUE);
Mark Shannon266b4622020-11-17 19:30:14 +00002867 NEXT_BLOCK(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002870}
2871
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002872static int
2873compiler_break(struct compiler *c)
2874{
Mark Shannonfee55262019-11-21 09:11:43 +00002875 struct fblockinfo *loop = NULL;
2876 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2877 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002878 }
Mark Shannonfee55262019-11-21 09:11:43 +00002879 if (loop == NULL) {
2880 return compiler_error(c, "'break' outside loop");
2881 }
2882 if (!compiler_unwind_fblock(c, loop, 0)) {
2883 return 0;
2884 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002885 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_exit);
Mark Shannon266b4622020-11-17 19:30:14 +00002886 NEXT_BLOCK(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002887 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002888}
2889
2890static int
2891compiler_continue(struct compiler *c)
2892{
Mark Shannonfee55262019-11-21 09:11:43 +00002893 struct fblockinfo *loop = NULL;
2894 if (!compiler_unwind_fblock_stack(c, 0, &loop)) {
2895 return 0;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002896 }
Mark Shannonfee55262019-11-21 09:11:43 +00002897 if (loop == NULL) {
2898 return compiler_error(c, "'continue' not properly in loop");
2899 }
Mark Shannon582aaf12020-08-04 17:30:11 +01002900 ADDOP_JUMP(c, JUMP_ABSOLUTE, loop->fb_block);
Mark Shannon266b4622020-11-17 19:30:14 +00002901 NEXT_BLOCK(c)
Mark Shannonfee55262019-11-21 09:11:43 +00002902 return 1;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002903}
2904
2905
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002906/* Code generated for "try: <body> finally: <finalbody>" is as follows:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907
2908 SETUP_FINALLY L
2909 <code for body>
2910 POP_BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00002911 <code for finalbody>
2912 JUMP E
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002913 L:
2914 <code for finalbody>
Mark Shannonfee55262019-11-21 09:11:43 +00002915 E:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002916
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002917 The special instructions use the block stack. Each block
2918 stack entry contains the instruction that created it (here
2919 SETUP_FINALLY), the level of the value stack at the time the
2920 block stack entry was created, and a label (here L).
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002921
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002922 SETUP_FINALLY:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 Pushes the current value stack level and the label
2924 onto the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002925 POP_BLOCK:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002926 Pops en entry from the block stack.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002928 The block stack is unwound when an exception is raised:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002929 when a SETUP_FINALLY entry is found, the raised and the caught
2930 exceptions are pushed onto the value stack (and the exception
2931 condition is cleared), and the interpreter jumps to the label
2932 gotten from the block stack.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002933*/
2934
2935static int
2936compiler_try_finally(struct compiler *c, stmt_ty s)
2937{
Mark Shannonfee55262019-11-21 09:11:43 +00002938 basicblock *body, *end, *exit;
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 body = compiler_new_block(c);
2941 end = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00002942 exit = compiler_new_block(c);
2943 if (body == NULL || end == NULL || exit == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002945
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002946 /* `try` block */
Mark Shannon582aaf12020-08-04 17:30:11 +01002947 ADDOP_JUMP(c, SETUP_FINALLY, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 compiler_use_next_block(c, body);
Mark Shannonfee55262019-11-21 09:11:43 +00002949 if (!compiler_push_fblock(c, FINALLY_TRY, body, end, s->v.Try.finalbody))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05002951 if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) {
2952 if (!compiler_try_except(c, s))
2953 return 0;
2954 }
2955 else {
2956 VISIT_SEQ(c, stmt, s->v.Try.body);
2957 }
Mark Shannon56aa20f2020-12-14 10:19:10 +00002958 /* Mark code as artificial */
2959 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 ADDOP(c, POP_BLOCK);
Mark Shannonfee55262019-11-21 09:11:43 +00002961 compiler_pop_fblock(c, FINALLY_TRY, body);
2962 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
Mark Shannon127dde52021-01-04 18:06:55 +00002963 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00002964 /* `finally` block */
2965 compiler_use_next_block(c, end);
2966 if (!compiler_push_fblock(c, FINALLY_END, end, NULL, NULL))
2967 return 0;
2968 VISIT_SEQ(c, stmt, s->v.Try.finalbody);
2969 compiler_pop_fblock(c, FINALLY_END, end);
Mark Shannonbf353f32020-12-17 13:55:28 +00002970 ADDOP_I(c, RERAISE, 0);
Mark Shannonfee55262019-11-21 09:11:43 +00002971 compiler_use_next_block(c, exit);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002973}
2974
2975/*
Jeffrey Yasskin9de7ec72009-02-25 02:25:04 +00002976 Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...":
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002977 (The contents of the value stack is shown in [], with the top
2978 at the right; 'tb' is trace-back info, 'val' the exception's
2979 associated value, and 'exc' the exception.)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980
2981 Value stack Label Instruction Argument
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02002982 [] SETUP_FINALLY L1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002983 [] <code for S>
2984 [] POP_BLOCK
2985 [] JUMP_FORWARD L0
2986
2987 [tb, val, exc] L1: DUP )
2988 [tb, val, exc, exc] <evaluate E1> )
Mark Shannon9af0e472020-01-14 10:12:45 +00002989 [tb, val, exc, exc, E1] JUMP_IF_NOT_EXC_MATCH L2 ) only if E1
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002990 [tb, val, exc] POP
2991 [tb, val] <assign to V1> (or POP if no V1)
2992 [tb] POP
2993 [] <code for S1>
2994 JUMP_FORWARD L0
2995
2996 [tb, val, exc] L2: DUP
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002997 .............................etc.......................
2998
Mark Shannonfee55262019-11-21 09:11:43 +00002999 [tb, val, exc] Ln+1: RERAISE # re-raise exception
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003000
3001 [] L0: <next statement>
3002
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003003 Of course, parts are not generated if Vi or Ei is not present.
3004*/
3005static int
3006compiler_try_except(struct compiler *c, stmt_ty s)
3007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003008 basicblock *body, *orelse, *except, *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003009 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003011 body = compiler_new_block(c);
3012 except = compiler_new_block(c);
3013 orelse = compiler_new_block(c);
3014 end = compiler_new_block(c);
3015 if (body == NULL || except == NULL || orelse == NULL || end == NULL)
3016 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01003017 ADDOP_JUMP(c, SETUP_FINALLY, except);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003018 compiler_use_next_block(c, body);
Mark Shannon02d126a2020-09-25 14:04:19 +01003019 if (!compiler_push_fblock(c, TRY_EXCEPT, body, NULL, NULL))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003020 return 0;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003021 VISIT_SEQ(c, stmt, s->v.Try.body);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 ADDOP(c, POP_BLOCK);
Mark Shannon02d126a2020-09-25 14:04:19 +01003023 compiler_pop_fblock(c, TRY_EXCEPT, body);
Mark Shannon582aaf12020-08-04 17:30:11 +01003024 ADDOP_JUMP(c, JUMP_FORWARD, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003025 n = asdl_seq_LEN(s->v.Try.handlers);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 compiler_use_next_block(c, except);
Mark Shannon02d126a2020-09-25 14:04:19 +01003027 /* Runtime will push a block here, so we need to account for that */
3028 if (!compiler_push_fblock(c, EXCEPTION_HANDLER, NULL, NULL, NULL))
3029 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003030 for (i = 0; i < n; i++) {
3031 excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003032 s->v.Try.handlers, i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003033 if (!handler->v.ExceptHandler.type && i < n-1)
3034 return compiler_error(c, "default 'except:' must be last");
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003035 SET_LOC(c, handler);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003036 except = compiler_new_block(c);
3037 if (except == NULL)
3038 return 0;
3039 if (handler->v.ExceptHandler.type) {
3040 ADDOP(c, DUP_TOP);
3041 VISIT(c, expr, handler->v.ExceptHandler.type);
Mark Shannon582aaf12020-08-04 17:30:11 +01003042 ADDOP_JUMP(c, JUMP_IF_NOT_EXC_MATCH, except);
Mark Shannon266b4622020-11-17 19:30:14 +00003043 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003044 }
3045 ADDOP(c, POP_TOP);
3046 if (handler->v.ExceptHandler.name) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003047 basicblock *cleanup_end, *cleanup_body;
Guido van Rossumb940e112007-01-10 16:19:56 +00003048
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003049 cleanup_end = compiler_new_block(c);
3050 cleanup_body = compiler_new_block(c);
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003051 if (cleanup_end == NULL || cleanup_body == NULL) {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003052 return 0;
Zackery Spytz53ebf4b2018-10-11 23:54:03 -06003053 }
Guido van Rossumb940e112007-01-10 16:19:56 +00003054
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003055 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3056 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003057
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003058 /*
3059 try:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003060 # body
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003061 except type as name:
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003062 try:
3063 # body
3064 finally:
Chris Angelicoad098b62019-05-21 23:34:19 +10003065 name = None # in case body contains "del name"
Ezio Melotti1b6424f2013-04-19 07:10:09 +03003066 del name
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003067 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003068
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003069 /* second try: */
Mark Shannon582aaf12020-08-04 17:30:11 +01003070 ADDOP_JUMP(c, SETUP_FINALLY, cleanup_end);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003071 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003072 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, handler->v.ExceptHandler.name))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003073 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003075 /* second # body */
3076 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003077 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003078 ADDOP(c, POP_BLOCK);
3079 ADDOP(c, POP_EXCEPT);
Mark Shannon877df852020-11-12 09:43:29 +00003080 /* name = None; del name; # Mark as artificial */
3081 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003082 ADDOP_LOAD_CONST(c, Py_None);
3083 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
3084 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Mark Shannon582aaf12020-08-04 17:30:11 +01003085 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003086
Mark Shannonfee55262019-11-21 09:11:43 +00003087 /* except: */
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003088 compiler_use_next_block(c, cleanup_end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003089
Mark Shannon877df852020-11-12 09:43:29 +00003090 /* name = None; del name; # Mark as artificial */
3091 c->u->u_lineno = -1;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003092 ADDOP_LOAD_CONST(c, Py_None);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003093 compiler_nameop(c, handler->v.ExceptHandler.name, Store);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003094 compiler_nameop(c, handler->v.ExceptHandler.name, Del);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095
Mark Shannonbf353f32020-12-17 13:55:28 +00003096 ADDOP_I(c, RERAISE, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003097 }
3098 else {
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003099 basicblock *cleanup_body;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003101 cleanup_body = compiler_new_block(c);
Benjamin Peterson0a5dad92011-05-27 14:17:04 -05003102 if (!cleanup_body)
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003103 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104
Guido van Rossumb940e112007-01-10 16:19:56 +00003105 ADDOP(c, POP_TOP);
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003106 ADDOP(c, POP_TOP);
3107 compiler_use_next_block(c, cleanup_body);
Mark Shannonfee55262019-11-21 09:11:43 +00003108 if (!compiler_push_fblock(c, HANDLER_CLEANUP, cleanup_body, NULL, NULL))
Benjamin Peterson74897ba2011-05-27 14:10:24 -05003109 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003111 compiler_pop_fblock(c, HANDLER_CLEANUP, cleanup_body);
Mark Shannon127dde52021-01-04 18:06:55 +00003112 /* name = None; del name; # Mark as artificial */
3113 c->u->u_lineno = -1;
Mark Shannonfee55262019-11-21 09:11:43 +00003114 ADDOP(c, POP_EXCEPT);
Mark Shannon582aaf12020-08-04 17:30:11 +01003115 ADDOP_JUMP(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003117 compiler_use_next_block(c, except);
3118 }
Mark Shannon02d126a2020-09-25 14:04:19 +01003119 compiler_pop_fblock(c, EXCEPTION_HANDLER, NULL);
Mark Shannonf2dbfd72020-12-21 13:53:50 +00003120 /* Mark as artificial */
3121 c->u->u_lineno = -1;
Mark Shannonbf353f32020-12-17 13:55:28 +00003122 ADDOP_I(c, RERAISE, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 compiler_use_next_block(c, orelse);
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003124 VISIT_SEQ(c, stmt, s->v.Try.orelse);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 compiler_use_next_block(c, end);
3126 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003127}
3128
3129static int
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003130compiler_try(struct compiler *c, stmt_ty s) {
3131 if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody))
3132 return compiler_try_finally(c, s);
3133 else
3134 return compiler_try_except(c, s);
3135}
3136
3137
3138static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003139compiler_import_as(struct compiler *c, identifier name, identifier asname)
3140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 /* The IMPORT_NAME opcode was already generated. This function
3142 merely needs to bind the result to a name.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 If there is a dot in name, we need to split it and emit a
Serhiy Storchakaf93234b2017-05-09 22:31:05 +03003145 IMPORT_FROM for each name.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003147 Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3148 Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003149 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003150 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003151 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 /* Consume the base module name to get the first attribute */
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003153 while (1) {
3154 Py_ssize_t pos = dot + 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003155 PyObject *attr;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003156 dot = PyUnicode_FindChar(name, '.', pos, len, 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003157 if (dot == -2)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003158 return 0;
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003159 attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : len);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 if (!attr)
Serhiy Storchaka694de3b2016-06-15 20:06:07 +03003161 return 0;
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003162 ADDOP_N(c, IMPORT_FROM, attr, names);
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003163 if (dot == -1) {
3164 break;
3165 }
3166 ADDOP(c, ROT_TWO);
3167 ADDOP(c, POP_TOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 }
Serhiy Storchaka265fcc52017-08-29 15:47:44 +03003169 if (!compiler_nameop(c, asname, Store)) {
3170 return 0;
3171 }
3172 ADDOP(c, POP_TOP);
3173 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003174 }
3175 return compiler_nameop(c, asname, Store);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003176}
3177
3178static int
3179compiler_import(struct compiler *c, stmt_ty s)
3180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003181 /* The Import node stores a module name like a.b.c as a single
3182 string. This is convenient for all cases except
3183 import a.b.c as d
3184 where we need to parse that string to extract the individual
3185 module names.
3186 XXX Perhaps change the representation to make this case simpler?
3187 */
Victor Stinnerad9a0662013-11-19 22:23:20 +01003188 Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names);
Thomas Woutersf7f438b2006-02-28 16:09:29 +00003189
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003190 PyObject *zero = _PyLong_GetZero(); // borrowed reference
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 for (i = 0; i < n; i++) {
3192 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
3193 int r;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003194
Victor Stinnerc9bc2902020-10-27 02:24:34 +01003195 ADDOP_LOAD_CONST(c, zero);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003196 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003199 if (alias->asname) {
3200 r = compiler_import_as(c, alias->name, alias->asname);
3201 if (!r)
3202 return r;
3203 }
3204 else {
3205 identifier tmp = alias->name;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003206 Py_ssize_t dot = PyUnicode_FindChar(
3207 alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1);
Victor Stinner6b64a682013-07-11 22:50:45 +02003208 if (dot != -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003209 tmp = PyUnicode_Substring(alias->name, 0, dot);
Victor Stinner6b64a682013-07-11 22:50:45 +02003210 if (tmp == NULL)
3211 return 0;
3212 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003213 r = compiler_nameop(c, tmp, Store);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003214 if (dot != -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003215 Py_DECREF(tmp);
3216 }
3217 if (!r)
3218 return r;
3219 }
3220 }
3221 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003222}
3223
3224static int
3225compiler_from_import(struct compiler *c, stmt_ty s)
3226{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003227 Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003228 PyObject *names;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003229 static PyObject *empty_string;
Benjamin Peterson78565b22009-06-28 19:19:51 +00003230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003231 if (!empty_string) {
3232 empty_string = PyUnicode_FromString("");
3233 if (!empty_string)
3234 return 0;
3235 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003236
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003237 ADDOP_LOAD_CONST_NEW(c, PyLong_FromLong(s->v.ImportFrom.level));
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02003238
3239 names = PyTuple_New(n);
3240 if (!names)
3241 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003243 /* build up the names */
3244 for (i = 0; i < n; i++) {
3245 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3246 Py_INCREF(alias->name);
3247 PyTuple_SET_ITEM(names, i, alias->name);
3248 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003251 _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 Py_DECREF(names);
3253 return compiler_error(c, "from __future__ imports must occur "
3254 "at the beginning of the file");
3255 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003256 ADDOP_LOAD_CONST_NEW(c, names);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 if (s->v.ImportFrom.module) {
3259 ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
3260 }
3261 else {
3262 ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
3263 }
3264 for (i = 0; i < n; i++) {
3265 alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
3266 identifier store_name;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003268 if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 assert(n == 1);
3270 ADDOP(c, IMPORT_STAR);
3271 return 1;
3272 }
3273
3274 ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
3275 store_name = alias->name;
3276 if (alias->asname)
3277 store_name = alias->asname;
3278
3279 if (!compiler_nameop(c, store_name, Store)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 return 0;
3281 }
3282 }
3283 /* remove imported module */
3284 ADDOP(c, POP_TOP);
3285 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003286}
3287
3288static int
3289compiler_assert(struct compiler *c, stmt_ty s)
3290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 basicblock *end;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003292
Georg Brandl8334fd92010-12-04 10:26:46 +00003293 if (c->c_optimize)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003295 if (s->v.Assert.test->kind == Tuple_kind &&
Serhiy Storchakad31e7732018-10-21 10:09:39 +03003296 asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0)
3297 {
3298 if (!compiler_warn(c, "assertion is always true, "
3299 "perhaps remove parentheses?"))
3300 {
Victor Stinner14e461d2013-08-26 22:28:21 +02003301 return 0;
3302 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003303 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 end = compiler_new_block(c);
3305 if (end == NULL)
3306 return 0;
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03003307 if (!compiler_jump_if(c, s->v.Assert.test, end, 1))
3308 return 0;
Zackery Spytzce6a0702019-08-25 03:44:09 -06003309 ADDOP(c, LOAD_ASSERTION_ERROR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 if (s->v.Assert.msg) {
3311 VISIT(c, expr, s->v.Assert.msg);
3312 ADDOP_I(c, CALL_FUNCTION, 1);
3313 }
3314 ADDOP_I(c, RAISE_VARARGS, 1);
3315 compiler_use_next_block(c, end);
3316 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003317}
3318
3319static int
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003320compiler_visit_stmt_expr(struct compiler *c, expr_ty value)
3321{
3322 if (c->c_interactive && c->c_nestlevel <= 1) {
3323 VISIT(c, expr, value);
3324 ADDOP(c, PRINT_EXPR);
3325 return 1;
3326 }
3327
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003328 if (value->kind == Constant_kind) {
Victor Stinner15a30952016-02-08 22:45:06 +01003329 /* ignore constant statement */
Mark Shannon877df852020-11-12 09:43:29 +00003330 ADDOP(c, NOP);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003331 return 1;
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003332 }
3333
3334 VISIT(c, expr, value);
3335 ADDOP(c, POP_TOP);
3336 return 1;
3337}
3338
3339static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003340compiler_visit_stmt(struct compiler *c, stmt_ty s)
3341{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003342 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 /* Always assign a lineno to the next instruction for a stmt. */
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02003345 SET_LOC(c, s);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003347 switch (s->kind) {
3348 case FunctionDef_kind:
Yury Selivanov75445082015-05-11 22:57:16 -04003349 return compiler_function(c, s, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003350 case ClassDef_kind:
3351 return compiler_class(c, s);
3352 case Return_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003353 return compiler_return(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003354 case Delete_kind:
3355 VISIT_SEQ(c, expr, s->v.Delete.targets)
3356 break;
3357 case Assign_kind:
3358 n = asdl_seq_LEN(s->v.Assign.targets);
3359 VISIT(c, expr, s->v.Assign.value);
3360 for (i = 0; i < n; i++) {
3361 if (i < n - 1)
3362 ADDOP(c, DUP_TOP);
3363 VISIT(c, expr,
3364 (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
3365 }
3366 break;
3367 case AugAssign_kind:
3368 return compiler_augassign(c, s);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07003369 case AnnAssign_kind:
3370 return compiler_annassign(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 case For_kind:
3372 return compiler_for(c, s);
3373 case While_kind:
3374 return compiler_while(c, s);
3375 case If_kind:
3376 return compiler_if(c, s);
3377 case Raise_kind:
3378 n = 0;
3379 if (s->v.Raise.exc) {
3380 VISIT(c, expr, s->v.Raise.exc);
3381 n++;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003382 if (s->v.Raise.cause) {
3383 VISIT(c, expr, s->v.Raise.cause);
3384 n++;
3385 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003386 }
Victor Stinnerad9a0662013-11-19 22:23:20 +01003387 ADDOP_I(c, RAISE_VARARGS, (int)n);
Mark Shannon266b4622020-11-17 19:30:14 +00003388 NEXT_BLOCK(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003389 break;
Benjamin Peterson43af12b2011-05-29 11:43:10 -05003390 case Try_kind:
3391 return compiler_try(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003392 case Assert_kind:
3393 return compiler_assert(c, s);
3394 case Import_kind:
3395 return compiler_import(c, s);
3396 case ImportFrom_kind:
3397 return compiler_from_import(c, s);
3398 case Global_kind:
3399 case Nonlocal_kind:
3400 break;
3401 case Expr_kind:
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01003402 return compiler_visit_stmt_expr(c, s->v.Expr.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003403 case Pass_kind:
Mark Shannon877df852020-11-12 09:43:29 +00003404 ADDOP(c, NOP);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003405 break;
3406 case Break_kind:
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02003407 return compiler_break(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003408 case Continue_kind:
3409 return compiler_continue(c);
3410 case With_kind:
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05003411 return compiler_with(c, s, 0);
Yury Selivanov75445082015-05-11 22:57:16 -04003412 case AsyncFunctionDef_kind:
3413 return compiler_function(c, s, 1);
3414 case AsyncWith_kind:
3415 return compiler_async_with(c, s, 0);
3416 case AsyncFor_kind:
3417 return compiler_async_for(c, s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003418 }
Yury Selivanov75445082015-05-11 22:57:16 -04003419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003420 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003421}
3422
3423static int
3424unaryop(unaryop_ty op)
3425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003426 switch (op) {
3427 case Invert:
3428 return UNARY_INVERT;
3429 case Not:
3430 return UNARY_NOT;
3431 case UAdd:
3432 return UNARY_POSITIVE;
3433 case USub:
3434 return UNARY_NEGATIVE;
3435 default:
3436 PyErr_Format(PyExc_SystemError,
3437 "unary op %d should not be possible", op);
3438 return 0;
3439 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003440}
3441
3442static int
Andy Lester76d58772020-03-10 21:18:12 -05003443binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003445 switch (op) {
3446 case Add:
3447 return BINARY_ADD;
3448 case Sub:
3449 return BINARY_SUBTRACT;
3450 case Mult:
3451 return BINARY_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003452 case MatMult:
3453 return BINARY_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003454 case Div:
3455 return BINARY_TRUE_DIVIDE;
3456 case Mod:
3457 return BINARY_MODULO;
3458 case Pow:
3459 return BINARY_POWER;
3460 case LShift:
3461 return BINARY_LSHIFT;
3462 case RShift:
3463 return BINARY_RSHIFT;
3464 case BitOr:
3465 return BINARY_OR;
3466 case BitXor:
3467 return BINARY_XOR;
3468 case BitAnd:
3469 return BINARY_AND;
3470 case FloorDiv:
3471 return BINARY_FLOOR_DIVIDE;
3472 default:
3473 PyErr_Format(PyExc_SystemError,
3474 "binary op %d should not be possible", op);
3475 return 0;
3476 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003477}
3478
3479static int
Andy Lester76d58772020-03-10 21:18:12 -05003480inplace_binop(operator_ty op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003482 switch (op) {
3483 case Add:
3484 return INPLACE_ADD;
3485 case Sub:
3486 return INPLACE_SUBTRACT;
3487 case Mult:
3488 return INPLACE_MULTIPLY;
Benjamin Petersond51374e2014-04-09 23:55:56 -04003489 case MatMult:
3490 return INPLACE_MATRIX_MULTIPLY;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003491 case Div:
3492 return INPLACE_TRUE_DIVIDE;
3493 case Mod:
3494 return INPLACE_MODULO;
3495 case Pow:
3496 return INPLACE_POWER;
3497 case LShift:
3498 return INPLACE_LSHIFT;
3499 case RShift:
3500 return INPLACE_RSHIFT;
3501 case BitOr:
3502 return INPLACE_OR;
3503 case BitXor:
3504 return INPLACE_XOR;
3505 case BitAnd:
3506 return INPLACE_AND;
3507 case FloorDiv:
3508 return INPLACE_FLOOR_DIVIDE;
3509 default:
3510 PyErr_Format(PyExc_SystemError,
3511 "inplace binary op %d should not be possible", op);
3512 return 0;
3513 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003514}
3515
3516static int
3517compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
3518{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003519 int op, scope;
3520 Py_ssize_t arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003521 enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003523 PyObject *dict = c->u->u_names;
3524 PyObject *mangled;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003525
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +02003526 assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
3527 !_PyUnicode_EqualToASCIIString(name, "True") &&
3528 !_PyUnicode_EqualToASCIIString(name, "False"));
Benjamin Peterson70b224d2012-12-06 17:49:58 -05003529
Pablo Galindoc5fc1562020-04-22 23:29:27 +01003530 if (forbidden_name(c, name, ctx))
3531 return 0;
3532
Serhiy Storchakabd6ec4d2017-12-18 14:29:12 +02003533 mangled = _Py_Mangle(c->u->u_private, name);
3534 if (!mangled)
3535 return 0;
3536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003537 op = 0;
3538 optype = OP_NAME;
3539 scope = PyST_GetScope(c->u->u_ste, mangled);
3540 switch (scope) {
3541 case FREE:
3542 dict = c->u->u_freevars;
3543 optype = OP_DEREF;
3544 break;
3545 case CELL:
3546 dict = c->u->u_cellvars;
3547 optype = OP_DEREF;
3548 break;
3549 case LOCAL:
3550 if (c->u->u_ste->ste_type == FunctionBlock)
3551 optype = OP_FAST;
3552 break;
3553 case GLOBAL_IMPLICIT:
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04003554 if (c->u->u_ste->ste_type == FunctionBlock)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003555 optype = OP_GLOBAL;
3556 break;
3557 case GLOBAL_EXPLICIT:
3558 optype = OP_GLOBAL;
3559 break;
3560 default:
3561 /* scope can be 0 */
3562 break;
3563 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003565 /* XXX Leave assert here, but handle __doc__ and the like better */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003566 assert(scope || PyUnicode_READ_CHAR(name, 0) == '_');
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003568 switch (optype) {
3569 case OP_DEREF:
3570 switch (ctx) {
Benjamin Peterson3b0431d2013-04-30 09:41:40 -04003571 case Load:
3572 op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF;
3573 break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003574 case Store: op = STORE_DEREF; break;
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +00003575 case Del: op = DELETE_DEREF; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003576 }
3577 break;
3578 case OP_FAST:
3579 switch (ctx) {
3580 case Load: op = LOAD_FAST; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003581 case Store: op = STORE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003582 case Del: op = DELETE_FAST; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003583 }
Serhiy Storchakaaa8e51f2018-04-01 00:29:37 +03003584 ADDOP_N(c, op, mangled, varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003585 return 1;
3586 case OP_GLOBAL:
3587 switch (ctx) {
3588 case Load: op = LOAD_GLOBAL; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003589 case Store: op = STORE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003590 case Del: op = DELETE_GLOBAL; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003591 }
3592 break;
3593 case OP_NAME:
3594 switch (ctx) {
Benjamin Peterson20f9c3c2010-07-20 22:39:34 +00003595 case Load: op = LOAD_NAME; break;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02003596 case Store: op = STORE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003597 case Del: op = DELETE_NAME; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003598 }
3599 break;
3600 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003602 assert(op);
Andy Lester76d58772020-03-10 21:18:12 -05003603 arg = compiler_add_o(dict, mangled);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003604 Py_DECREF(mangled);
3605 if (arg < 0)
3606 return 0;
3607 return compiler_addop_i(c, op, arg);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003608}
3609
3610static int
3611compiler_boolop(struct compiler *c, expr_ty e)
3612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003613 basicblock *end;
Victor Stinnerad9a0662013-11-19 22:23:20 +01003614 int jumpi;
3615 Py_ssize_t i, n;
Pablo Galindoa5634c42020-09-16 19:42:00 +01003616 asdl_expr_seq *s;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003618 assert(e->kind == BoolOp_kind);
3619 if (e->v.BoolOp.op == And)
3620 jumpi = JUMP_IF_FALSE_OR_POP;
3621 else
3622 jumpi = JUMP_IF_TRUE_OR_POP;
3623 end = compiler_new_block(c);
3624 if (end == NULL)
3625 return 0;
3626 s = e->v.BoolOp.values;
3627 n = asdl_seq_LEN(s) - 1;
3628 assert(n >= 0);
3629 for (i = 0; i < n; ++i) {
3630 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003631 ADDOP_JUMP(c, jumpi, end);
Mark Shannon6e8128f2020-07-30 10:03:00 +01003632 basicblock *next = compiler_new_block(c);
3633 if (next == NULL) {
3634 return 0;
3635 }
3636 compiler_use_next_block(c, next);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003637 }
3638 VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
3639 compiler_use_next_block(c, end);
3640 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003641}
3642
3643static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003644starunpack_helper(struct compiler *c, asdl_expr_seq *elts, int pushed,
Mark Shannon13bc1392020-01-23 09:25:17 +00003645 int build, int add, int extend, int tuple)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003646{
3647 Py_ssize_t n = asdl_seq_LEN(elts);
Mark Shannon13bc1392020-01-23 09:25:17 +00003648 Py_ssize_t i, seen_star = 0;
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003649 if (n > 2 && are_all_items_const(elts, 0, n)) {
3650 PyObject *folded = PyTuple_New(n);
3651 if (folded == NULL) {
3652 return 0;
3653 }
3654 PyObject *val;
3655 for (i = 0; i < n; i++) {
3656 val = ((expr_ty)asdl_seq_GET(elts, i))->v.Constant.value;
3657 Py_INCREF(val);
3658 PyTuple_SET_ITEM(folded, i, val);
3659 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003660 if (tuple) {
3661 ADDOP_LOAD_CONST_NEW(c, folded);
3662 } else {
3663 if (add == SET_ADD) {
3664 Py_SETREF(folded, PyFrozenSet_New(folded));
3665 if (folded == NULL) {
3666 return 0;
3667 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003668 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003669 ADDOP_I(c, build, pushed);
3670 ADDOP_LOAD_CONST_NEW(c, folded);
3671 ADDOP_I(c, extend, 1);
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003672 }
Brandt Bucher6dd9b642019-11-25 22:16:53 -08003673 return 1;
3674 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003675
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003676 for (i = 0; i < n; i++) {
3677 expr_ty elt = asdl_seq_GET(elts, i);
3678 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003679 seen_star = 1;
3680 }
3681 }
3682 if (seen_star) {
3683 seen_star = 0;
3684 for (i = 0; i < n; i++) {
3685 expr_ty elt = asdl_seq_GET(elts, i);
3686 if (elt->kind == Starred_kind) {
3687 if (seen_star == 0) {
3688 ADDOP_I(c, build, i+pushed);
3689 seen_star = 1;
3690 }
3691 VISIT(c, expr, elt->v.Starred.value);
3692 ADDOP_I(c, extend, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003693 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003694 else {
3695 VISIT(c, expr, elt);
3696 if (seen_star) {
3697 ADDOP_I(c, add, 1);
3698 }
3699 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003700 }
Mark Shannon13bc1392020-01-23 09:25:17 +00003701 assert(seen_star);
3702 if (tuple) {
3703 ADDOP(c, LIST_TO_TUPLE);
3704 }
3705 }
3706 else {
3707 for (i = 0; i < n; i++) {
3708 expr_ty elt = asdl_seq_GET(elts, i);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003709 VISIT(c, expr, elt);
Mark Shannon13bc1392020-01-23 09:25:17 +00003710 }
3711 if (tuple) {
3712 ADDOP_I(c, BUILD_TUPLE, n+pushed);
3713 } else {
3714 ADDOP_I(c, build, n+pushed);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003715 }
3716 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003717 return 1;
3718}
3719
3720static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003721assignment_helper(struct compiler *c, asdl_expr_seq *elts)
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003722{
3723 Py_ssize_t n = asdl_seq_LEN(elts);
3724 Py_ssize_t i;
3725 int seen_star = 0;
3726 for (i = 0; i < n; i++) {
3727 expr_ty elt = asdl_seq_GET(elts, i);
3728 if (elt->kind == Starred_kind && !seen_star) {
3729 if ((i >= (1 << 8)) ||
3730 (n-i-1 >= (INT_MAX >> 8)))
3731 return compiler_error(c,
3732 "too many expressions in "
3733 "star-unpacking assignment");
3734 ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8)));
3735 seen_star = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003736 }
3737 else if (elt->kind == Starred_kind) {
3738 return compiler_error(c,
Furkan Öndercb6534e2020-03-26 04:54:31 +03003739 "multiple starred expressions in assignment");
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003740 }
3741 }
3742 if (!seen_star) {
3743 ADDOP_I(c, UNPACK_SEQUENCE, n);
3744 }
Brandt Bucherd5aa2e92020-03-07 19:44:18 -08003745 for (i = 0; i < n; i++) {
3746 expr_ty elt = asdl_seq_GET(elts, i);
3747 VISIT(c, expr, elt->kind != Starred_kind ? elt : elt->v.Starred.value);
3748 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003749 return 1;
3750}
3751
3752static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003753compiler_list(struct compiler *c, expr_ty e)
3754{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003755 asdl_expr_seq *elts = e->v.List.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003756 if (e->v.List.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003757 return assignment_helper(c, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003758 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003759 else if (e->v.List.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003760 return starunpack_helper(c, elts, 0, BUILD_LIST,
3761 LIST_APPEND, LIST_EXTEND, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003762 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003763 else
3764 VISIT_SEQ(c, expr, elts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003765 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003766}
3767
3768static int
3769compiler_tuple(struct compiler *c, expr_ty e)
3770{
Pablo Galindoa5634c42020-09-16 19:42:00 +01003771 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchakad8b3a982019-03-05 20:42:06 +02003772 if (e->v.Tuple.ctx == Store) {
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003773 return assignment_helper(c, elts);
3774 }
3775 else if (e->v.Tuple.ctx == Load) {
Mark Shannon13bc1392020-01-23 09:25:17 +00003776 return starunpack_helper(c, elts, 0, BUILD_LIST,
3777 LIST_APPEND, LIST_EXTEND, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003778 }
3779 else
3780 VISIT_SEQ(c, expr, elts);
3781 return 1;
3782}
3783
3784static int
3785compiler_set(struct compiler *c, expr_ty e)
3786{
Mark Shannon13bc1392020-01-23 09:25:17 +00003787 return starunpack_helper(c, e->v.Set.elts, 0, BUILD_SET,
3788 SET_ADD, SET_UPDATE, 0);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003789}
3790
3791static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01003792are_all_items_const(asdl_expr_seq *seq, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003793{
3794 Py_ssize_t i;
3795 for (i = begin; i < end; i++) {
3796 expr_ty key = (expr_ty)asdl_seq_GET(seq, i);
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003797 if (key == NULL || key->kind != Constant_kind)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003798 return 0;
3799 }
3800 return 1;
3801}
3802
3803static int
3804compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end)
3805{
3806 Py_ssize_t i, n = end - begin;
3807 PyObject *keys, *key;
3808 if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) {
3809 for (i = begin; i < end; i++) {
3810 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3811 }
3812 keys = PyTuple_New(n);
3813 if (keys == NULL) {
3814 return 0;
3815 }
3816 for (i = begin; i < end; i++) {
Serhiy Storchaka3f228112018-09-27 17:42:37 +03003817 key = ((expr_ty)asdl_seq_GET(e->v.Dict.keys, i))->v.Constant.value;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003818 Py_INCREF(key);
3819 PyTuple_SET_ITEM(keys, i - begin, key);
3820 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03003821 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003822 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
3823 }
3824 else {
3825 for (i = begin; i < end; i++) {
3826 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
3827 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
3828 }
3829 ADDOP_I(c, BUILD_MAP, n);
3830 }
3831 return 1;
3832}
3833
3834static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003835compiler_dict(struct compiler *c, expr_ty e)
3836{
Victor Stinner976bb402016-03-23 11:36:19 +01003837 Py_ssize_t i, n, elements;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003838 int have_dict;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003839 int is_unpacking = 0;
3840 n = asdl_seq_LEN(e->v.Dict.values);
Mark Shannon8a4cd702020-01-27 09:57:45 +00003841 have_dict = 0;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003842 elements = 0;
3843 for (i = 0; i < n; i++) {
3844 is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003845 if (is_unpacking) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003846 if (elements) {
3847 if (!compiler_subdict(c, e, i - elements, i)) {
3848 return 0;
3849 }
3850 if (have_dict) {
3851 ADDOP_I(c, DICT_UPDATE, 1);
3852 }
3853 have_dict = 1;
3854 elements = 0;
3855 }
3856 if (have_dict == 0) {
3857 ADDOP_I(c, BUILD_MAP, 0);
3858 have_dict = 1;
3859 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003860 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
Mark Shannon8a4cd702020-01-27 09:57:45 +00003861 ADDOP_I(c, DICT_UPDATE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003862 }
3863 else {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003864 if (elements == 0xFFFF) {
Pablo Galindoc51db0e2020-08-13 09:48:41 +01003865 if (!compiler_subdict(c, e, i - elements, i + 1)) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00003866 return 0;
3867 }
3868 if (have_dict) {
3869 ADDOP_I(c, DICT_UPDATE, 1);
3870 }
3871 have_dict = 1;
3872 elements = 0;
3873 }
3874 else {
3875 elements++;
3876 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003877 }
3878 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003879 if (elements) {
3880 if (!compiler_subdict(c, e, n - elements, n)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03003881 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00003882 }
3883 if (have_dict) {
3884 ADDOP_I(c, DICT_UPDATE, 1);
3885 }
3886 have_dict = 1;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04003887 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00003888 if (!have_dict) {
3889 ADDOP_I(c, BUILD_MAP, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003890 }
3891 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003892}
3893
3894static int
3895compiler_compare(struct compiler *c, expr_ty e)
3896{
Victor Stinnerad9a0662013-11-19 22:23:20 +01003897 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003898
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02003899 if (!check_compare(c, e)) {
3900 return 0;
3901 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003902 VISIT(c, expr, e->v.Compare.left);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003903 assert(asdl_seq_LEN(e->v.Compare.ops) > 0);
3904 n = asdl_seq_LEN(e->v.Compare.ops) - 1;
3905 if (n == 0) {
3906 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
Mark Shannon9af0e472020-01-14 10:12:45 +00003907 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, 0));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003908 }
3909 else {
3910 basicblock *cleanup = compiler_new_block(c);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003911 if (cleanup == NULL)
3912 return 0;
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003913 for (i = 0; i < n; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003914 VISIT(c, expr,
3915 (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003916 ADDOP(c, DUP_TOP);
3917 ADDOP(c, ROT_THREE);
Mark Shannon9af0e472020-01-14 10:12:45 +00003918 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, i));
Mark Shannon582aaf12020-08-04 17:30:11 +01003919 ADDOP_JUMP(c, JUMP_IF_FALSE_OR_POP, cleanup);
Serhiy Storchaka02b9ef22017-12-30 09:47:42 +02003920 NEXT_BLOCK(c);
3921 }
3922 VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n));
Mark Shannon9af0e472020-01-14 10:12:45 +00003923 ADDOP_COMPARE(c, asdl_seq_GET(e->v.Compare.ops, n));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003924 basicblock *end = compiler_new_block(c);
3925 if (end == NULL)
3926 return 0;
Mark Shannon127dde52021-01-04 18:06:55 +00003927 ADDOP_JUMP_NOLINE(c, JUMP_FORWARD, end);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003928 compiler_use_next_block(c, cleanup);
3929 ADDOP(c, ROT_TWO);
3930 ADDOP(c, POP_TOP);
3931 compiler_use_next_block(c, end);
3932 }
3933 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003934}
3935
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003936static PyTypeObject *
3937infer_type(expr_ty e)
3938{
3939 switch (e->kind) {
3940 case Tuple_kind:
3941 return &PyTuple_Type;
3942 case List_kind:
3943 case ListComp_kind:
3944 return &PyList_Type;
3945 case Dict_kind:
3946 case DictComp_kind:
3947 return &PyDict_Type;
3948 case Set_kind:
3949 case SetComp_kind:
3950 return &PySet_Type;
3951 case GeneratorExp_kind:
3952 return &PyGen_Type;
3953 case Lambda_kind:
3954 return &PyFunction_Type;
3955 case JoinedStr_kind:
3956 case FormattedValue_kind:
3957 return &PyUnicode_Type;
3958 case Constant_kind:
Victor Stinnera102ed72020-02-07 02:24:48 +01003959 return Py_TYPE(e->v.Constant.value);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02003960 default:
3961 return NULL;
3962 }
3963}
3964
3965static int
3966check_caller(struct compiler *c, expr_ty e)
3967{
3968 switch (e->kind) {
3969 case Constant_kind:
3970 case Tuple_kind:
3971 case List_kind:
3972 case ListComp_kind:
3973 case Dict_kind:
3974 case DictComp_kind:
3975 case Set_kind:
3976 case SetComp_kind:
3977 case GeneratorExp_kind:
3978 case JoinedStr_kind:
3979 case FormattedValue_kind:
3980 return compiler_warn(c, "'%.200s' object is not callable; "
3981 "perhaps you missed a comma?",
3982 infer_type(e)->tp_name);
3983 default:
3984 return 1;
3985 }
3986}
3987
3988static int
3989check_subscripter(struct compiler *c, expr_ty e)
3990{
3991 PyObject *v;
3992
3993 switch (e->kind) {
3994 case Constant_kind:
3995 v = e->v.Constant.value;
3996 if (!(v == Py_None || v == Py_Ellipsis ||
3997 PyLong_Check(v) || PyFloat_Check(v) || PyComplex_Check(v) ||
3998 PyAnySet_Check(v)))
3999 {
4000 return 1;
4001 }
4002 /* fall through */
4003 case Set_kind:
4004 case SetComp_kind:
4005 case GeneratorExp_kind:
4006 case Lambda_kind:
4007 return compiler_warn(c, "'%.200s' object is not subscriptable; "
4008 "perhaps you missed a comma?",
4009 infer_type(e)->tp_name);
4010 default:
4011 return 1;
4012 }
4013}
4014
4015static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004016check_index(struct compiler *c, expr_ty e, expr_ty s)
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004017{
4018 PyObject *v;
4019
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02004020 PyTypeObject *index_type = infer_type(s);
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004021 if (index_type == NULL
4022 || PyType_FastSubclass(index_type, Py_TPFLAGS_LONG_SUBCLASS)
4023 || index_type == &PySlice_Type) {
4024 return 1;
4025 }
4026
4027 switch (e->kind) {
4028 case Constant_kind:
4029 v = e->v.Constant.value;
4030 if (!(PyUnicode_Check(v) || PyBytes_Check(v) || PyTuple_Check(v))) {
4031 return 1;
4032 }
4033 /* fall through */
4034 case Tuple_kind:
4035 case List_kind:
4036 case ListComp_kind:
4037 case JoinedStr_kind:
4038 case FormattedValue_kind:
4039 return compiler_warn(c, "%.200s indices must be integers or slices, "
4040 "not %.200s; "
4041 "perhaps you missed a comma?",
4042 infer_type(e)->tp_name,
4043 index_type->tp_name);
4044 default:
4045 return 1;
4046 }
4047}
4048
Zackery Spytz97f5de02019-03-22 01:30:32 -06004049// Return 1 if the method call was optimized, -1 if not, and 0 on error.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004050static int
Yury Selivanovf2392132016-12-13 19:03:51 -05004051maybe_optimize_method_call(struct compiler *c, expr_ty e)
4052{
4053 Py_ssize_t argsl, i;
4054 expr_ty meth = e->v.Call.func;
Pablo Galindoa5634c42020-09-16 19:42:00 +01004055 asdl_expr_seq *args = e->v.Call.args;
Yury Selivanovf2392132016-12-13 19:03:51 -05004056
4057 /* Check that the call node is an attribute access, and that
4058 the call doesn't have keyword parameters. */
4059 if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load ||
4060 asdl_seq_LEN(e->v.Call.keywords))
4061 return -1;
4062
4063 /* Check that there are no *varargs types of arguments. */
4064 argsl = asdl_seq_LEN(args);
4065 for (i = 0; i < argsl; i++) {
4066 expr_ty elt = asdl_seq_GET(args, i);
4067 if (elt->kind == Starred_kind) {
4068 return -1;
4069 }
4070 }
4071
4072 /* Alright, we can optimize the code. */
4073 VISIT(c, expr, meth->v.Attribute.value);
4074 ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names);
4075 VISIT_SEQ(c, expr, e->v.Call.args);
4076 ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args));
4077 return 1;
4078}
4079
4080static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004081validate_keywords(struct compiler *c, asdl_keyword_seq *keywords)
Zackery Spytz08050e92020-04-06 00:47:47 -06004082{
4083 Py_ssize_t nkeywords = asdl_seq_LEN(keywords);
4084 for (Py_ssize_t i = 0; i < nkeywords; i++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004085 keyword_ty key = ((keyword_ty)asdl_seq_GET(keywords, i));
4086 if (key->arg == NULL) {
4087 continue;
4088 }
Pablo Galindoc5fc1562020-04-22 23:29:27 +01004089 if (forbidden_name(c, key->arg, Store)) {
4090 return -1;
4091 }
Zackery Spytz08050e92020-04-06 00:47:47 -06004092 for (Py_ssize_t j = i + 1; j < nkeywords; j++) {
Pablo Galindo254ec782020-04-03 20:37:13 +01004093 keyword_ty other = ((keyword_ty)asdl_seq_GET(keywords, j));
4094 if (other->arg && !PyUnicode_Compare(key->arg, other->arg)) {
4095 PyObject *msg = PyUnicode_FromFormat("keyword argument repeated: %U", key->arg);
4096 if (msg == NULL) {
4097 return -1;
4098 }
4099 c->u->u_col_offset = other->col_offset;
4100 compiler_error(c, PyUnicode_AsUTF8(msg));
4101 Py_DECREF(msg);
4102 return -1;
4103 }
4104 }
4105 }
4106 return 0;
4107}
4108
4109static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004110compiler_call(struct compiler *c, expr_ty e)
4111{
Zackery Spytz97f5de02019-03-22 01:30:32 -06004112 int ret = maybe_optimize_method_call(c, e);
4113 if (ret >= 0) {
4114 return ret;
4115 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02004116 if (!check_caller(c, e->v.Call.func)) {
4117 return 0;
4118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004119 VISIT(c, expr, e->v.Call.func);
4120 return compiler_call_helper(c, 0,
4121 e->v.Call.args,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004122 e->v.Call.keywords);
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004123}
4124
Eric V. Smith235a6f02015-09-19 14:51:32 -04004125static int
4126compiler_joined_str(struct compiler *c, expr_ty e)
4127{
Eric V. Smith235a6f02015-09-19 14:51:32 -04004128 VISIT_SEQ(c, expr, e->v.JoinedStr.values);
Serhiy Storchaka4cc30ae2016-12-11 19:37:19 +02004129 if (asdl_seq_LEN(e->v.JoinedStr.values) != 1)
4130 ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values));
Eric V. Smith235a6f02015-09-19 14:51:32 -04004131 return 1;
4132}
4133
Eric V. Smitha78c7952015-11-03 12:45:05 -05004134/* Used to implement f-strings. Format a single value. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004135static int
4136compiler_formatted_value(struct compiler *c, expr_ty e)
4137{
Eric V. Smitha78c7952015-11-03 12:45:05 -05004138 /* Our oparg encodes 2 pieces of information: the conversion
4139 character, and whether or not a format_spec was provided.
Eric V. Smith235a6f02015-09-19 14:51:32 -04004140
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004141 Convert the conversion char to 3 bits:
4142 : 000 0x0 FVC_NONE The default if nothing specified.
Eric V. Smitha78c7952015-11-03 12:45:05 -05004143 !s : 001 0x1 FVC_STR
4144 !r : 010 0x2 FVC_REPR
4145 !a : 011 0x3 FVC_ASCII
Eric V. Smith235a6f02015-09-19 14:51:32 -04004146
Eric V. Smitha78c7952015-11-03 12:45:05 -05004147 next bit is whether or not we have a format spec:
4148 yes : 100 0x4
4149 no : 000 0x0
4150 */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004151
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004152 int conversion = e->v.FormattedValue.conversion;
Eric V. Smitha78c7952015-11-03 12:45:05 -05004153 int oparg;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004154
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004155 /* The expression to be formatted. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004156 VISIT(c, expr, e->v.FormattedValue.value);
4157
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004158 switch (conversion) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004159 case 's': oparg = FVC_STR; break;
4160 case 'r': oparg = FVC_REPR; break;
4161 case 'a': oparg = FVC_ASCII; break;
4162 case -1: oparg = FVC_NONE; break;
4163 default:
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004164 PyErr_Format(PyExc_SystemError,
4165 "Unrecognized conversion character %d", conversion);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004166 return 0;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004167 }
Eric V. Smith235a6f02015-09-19 14:51:32 -04004168 if (e->v.FormattedValue.format_spec) {
Eric V. Smitha78c7952015-11-03 12:45:05 -05004169 /* Evaluate the format spec, and update our opcode arg. */
Eric V. Smith235a6f02015-09-19 14:51:32 -04004170 VISIT(c, expr, e->v.FormattedValue.format_spec);
Eric V. Smitha78c7952015-11-03 12:45:05 -05004171 oparg |= FVS_HAVE_SPEC;
Eric V. Smith235a6f02015-09-19 14:51:32 -04004172 }
4173
Eric V. Smitha78c7952015-11-03 12:45:05 -05004174 /* And push our opcode and oparg */
4175 ADDOP_I(c, FORMAT_VALUE, oparg);
Eric V. Smith9a4135e2019-05-08 16:28:48 -04004176
Eric V. Smith235a6f02015-09-19 14:51:32 -04004177 return 1;
4178}
4179
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004180static int
Pablo Galindoa5634c42020-09-16 19:42:00 +01004181compiler_subkwargs(struct compiler *c, asdl_keyword_seq *keywords, Py_ssize_t begin, Py_ssize_t end)
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004182{
4183 Py_ssize_t i, n = end - begin;
4184 keyword_ty kw;
4185 PyObject *keys, *key;
4186 assert(n > 0);
4187 if (n > 1) {
4188 for (i = begin; i < end; i++) {
4189 kw = asdl_seq_GET(keywords, i);
4190 VISIT(c, expr, kw->value);
4191 }
4192 keys = PyTuple_New(n);
4193 if (keys == NULL) {
4194 return 0;
4195 }
4196 for (i = begin; i < end; i++) {
4197 key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg;
4198 Py_INCREF(key);
4199 PyTuple_SET_ITEM(keys, i - begin, key);
4200 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004201 ADDOP_LOAD_CONST_NEW(c, keys);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004202 ADDOP_I(c, BUILD_CONST_KEY_MAP, n);
4203 }
4204 else {
4205 /* a for loop only executes once */
4206 for (i = begin; i < end; i++) {
4207 kw = asdl_seq_GET(keywords, i);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004208 ADDOP_LOAD_CONST(c, kw->arg);
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004209 VISIT(c, expr, kw->value);
4210 }
4211 ADDOP_I(c, BUILD_MAP, n);
4212 }
4213 return 1;
4214}
4215
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004216/* shared code between compiler_call and compiler_class */
4217static int
4218compiler_call_helper(struct compiler *c,
Victor Stinner976bb402016-03-23 11:36:19 +01004219 int n, /* Args already pushed */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004220 asdl_expr_seq *args,
4221 asdl_keyword_seq *keywords)
Guido van Rossum52cc1d82007-03-18 15:41:51 +00004222{
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004223 Py_ssize_t i, nseen, nelts, nkwelts;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004224
Pablo Galindo254ec782020-04-03 20:37:13 +01004225 if (validate_keywords(c, keywords) == -1) {
4226 return 0;
4227 }
4228
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004229 nelts = asdl_seq_LEN(args);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004230 nkwelts = asdl_seq_LEN(keywords);
4231
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004232 for (i = 0; i < nelts; i++) {
4233 expr_ty elt = asdl_seq_GET(args, i);
4234 if (elt->kind == Starred_kind) {
Mark Shannon13bc1392020-01-23 09:25:17 +00004235 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004236 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004237 }
4238 for (i = 0; i < nkwelts; i++) {
4239 keyword_ty kw = asdl_seq_GET(keywords, i);
4240 if (kw->arg == NULL) {
4241 goto ex_call;
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004242 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004243 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004244
Mark Shannon13bc1392020-01-23 09:25:17 +00004245 /* No * or ** args, so can use faster calling sequence */
4246 for (i = 0; i < nelts; i++) {
4247 expr_ty elt = asdl_seq_GET(args, i);
4248 assert(elt->kind != Starred_kind);
4249 VISIT(c, expr, elt);
4250 }
4251 if (nkwelts) {
4252 PyObject *names;
4253 VISIT_SEQ(c, keyword, keywords);
4254 names = PyTuple_New(nkwelts);
4255 if (names == NULL) {
4256 return 0;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004257 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004258 for (i = 0; i < nkwelts; i++) {
4259 keyword_ty kw = asdl_seq_GET(keywords, i);
4260 Py_INCREF(kw->arg);
4261 PyTuple_SET_ITEM(names, i, kw->arg);
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004262 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004263 ADDOP_LOAD_CONST_NEW(c, names);
4264 ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts);
4265 return 1;
4266 }
4267 else {
4268 ADDOP_I(c, CALL_FUNCTION, n + nelts);
4269 return 1;
4270 }
4271
4272ex_call:
4273
4274 /* Do positional arguments. */
4275 if (n ==0 && nelts == 1 && ((expr_ty)asdl_seq_GET(args, 0))->kind == Starred_kind) {
4276 VISIT(c, expr, ((expr_ty)asdl_seq_GET(args, 0))->v.Starred.value);
4277 }
4278 else if (starunpack_helper(c, args, n, BUILD_LIST,
4279 LIST_APPEND, LIST_EXTEND, 1) == 0) {
4280 return 0;
4281 }
4282 /* Then keyword arguments */
4283 if (nkwelts) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004284 /* Has a new dict been pushed */
4285 int have_dict = 0;
Mark Shannon13bc1392020-01-23 09:25:17 +00004286
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004287 nseen = 0; /* the number of keyword arguments on the stack following */
4288 for (i = 0; i < nkwelts; i++) {
4289 keyword_ty kw = asdl_seq_GET(keywords, i);
4290 if (kw->arg == NULL) {
4291 /* A keyword argument unpacking. */
4292 if (nseen) {
Mark Shannon8a4cd702020-01-27 09:57:45 +00004293 if (!compiler_subkwargs(c, keywords, i - nseen, i)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004294 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004295 }
Mark Shannondb64f122020-06-01 10:42:42 +01004296 if (have_dict) {
4297 ADDOP_I(c, DICT_MERGE, 1);
4298 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004299 have_dict = 1;
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004300 nseen = 0;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004301 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004302 if (!have_dict) {
4303 ADDOP_I(c, BUILD_MAP, 0);
4304 have_dict = 1;
4305 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004306 VISIT(c, expr, kw->value);
Mark Shannon8a4cd702020-01-27 09:57:45 +00004307 ADDOP_I(c, DICT_MERGE, 1);
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004308 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004309 else {
4310 nseen++;
4311 }
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004312 }
Victor Stinnerf9b760f2016-09-09 10:17:08 -07004313 if (nseen) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004314 /* Pack up any trailing keyword arguments. */
Mark Shannon8a4cd702020-01-27 09:57:45 +00004315 if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) {
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004316 return 0;
Mark Shannon8a4cd702020-01-27 09:57:45 +00004317 }
4318 if (have_dict) {
4319 ADDOP_I(c, DICT_MERGE, 1);
4320 }
4321 have_dict = 1;
Serhiy Storchaka6a7506a2016-06-12 00:39:41 +03004322 }
Mark Shannon8a4cd702020-01-27 09:57:45 +00004323 assert(have_dict);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004324 }
Mark Shannon13bc1392020-01-23 09:25:17 +00004325 ADDOP_I(c, CALL_FUNCTION_EX, nkwelts > 0);
4326 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004327}
4328
Nick Coghlan650f0d02007-04-15 12:05:43 +00004329
4330/* List and set comprehensions and generator expressions work by creating a
4331 nested function to perform the actual iteration. This means that the
4332 iteration variables don't leak into the current scope.
4333 The defined function is called immediately following its definition, with the
4334 result of that call being the result of the expression.
4335 The LC/SC version returns the populated container, while the GE version is
4336 flagged in symtable.c as a generator, so it returns the generator object
4337 when the function is called.
Nick Coghlan650f0d02007-04-15 12:05:43 +00004338
4339 Possible cleanups:
4340 - iterate over the generator sequence instead of using recursion
4341*/
4342
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004343
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004344static int
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004345compiler_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004346 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004347 int depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004348 expr_ty elt, expr_ty val, int type)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004349{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004350 comprehension_ty gen;
4351 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4352 if (gen->is_async) {
4353 return compiler_async_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004354 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004355 } else {
4356 return compiler_sync_comprehension_generator(
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004357 c, generators, gen_index, depth, elt, val, type);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004358 }
4359}
4360
4361static int
4362compiler_sync_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004363 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004364 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004365 expr_ty elt, expr_ty val, int type)
4366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004367 /* generate code for the iterator, then each of the ifs,
4368 and then write to the element */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004370 comprehension_ty gen;
4371 basicblock *start, *anchor, *skip, *if_cleanup;
Victor Stinnerad9a0662013-11-19 22:23:20 +01004372 Py_ssize_t i, n;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004374 start = compiler_new_block(c);
4375 skip = compiler_new_block(c);
4376 if_cleanup = compiler_new_block(c);
4377 anchor = compiler_new_block(c);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004379 if (start == NULL || skip == NULL || if_cleanup == NULL ||
4380 anchor == NULL)
4381 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004383 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004385 if (gen_index == 0) {
4386 /* Receive outermost iter as an implicit argument */
4387 c->u->u_argcount = 1;
4388 ADDOP_I(c, LOAD_FAST, 0);
4389 }
4390 else {
4391 /* Sub-iter - calculate on the fly */
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004392 /* Fast path for the temporary variable assignment idiom:
4393 for y in [f(x)]
4394 */
Pablo Galindoa5634c42020-09-16 19:42:00 +01004395 asdl_expr_seq *elts;
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004396 switch (gen->iter->kind) {
4397 case List_kind:
4398 elts = gen->iter->v.List.elts;
4399 break;
4400 case Tuple_kind:
4401 elts = gen->iter->v.Tuple.elts;
4402 break;
4403 default:
4404 elts = NULL;
4405 }
4406 if (asdl_seq_LEN(elts) == 1) {
4407 expr_ty elt = asdl_seq_GET(elts, 0);
4408 if (elt->kind != Starred_kind) {
4409 VISIT(c, expr, elt);
4410 start = NULL;
4411 }
4412 }
4413 if (start) {
4414 VISIT(c, expr, gen->iter);
4415 ADDOP(c, GET_ITER);
4416 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004417 }
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004418 if (start) {
4419 depth++;
4420 compiler_use_next_block(c, start);
Mark Shannon582aaf12020-08-04 17:30:11 +01004421 ADDOP_JUMP(c, FOR_ITER, anchor);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004422 NEXT_BLOCK(c);
4423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004424 VISIT(c, expr, gen->target);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004426 /* XXX this needs to be cleaned up...a lot! */
4427 n = asdl_seq_LEN(gen->ifs);
4428 for (i = 0; i < n; i++) {
4429 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004430 if (!compiler_jump_if(c, e, if_cleanup, 0))
4431 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004432 NEXT_BLOCK(c);
4433 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004435 if (++gen_index < asdl_seq_LEN(generators))
4436 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004437 generators, gen_index, depth,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004438 elt, val, type))
4439 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004441 /* only append after the last for generator */
4442 if (gen_index >= asdl_seq_LEN(generators)) {
4443 /* comprehension specific code */
4444 switch (type) {
4445 case COMP_GENEXP:
4446 VISIT(c, expr, elt);
4447 ADDOP(c, YIELD_VALUE);
4448 ADDOP(c, POP_TOP);
4449 break;
4450 case COMP_LISTCOMP:
4451 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004452 ADDOP_I(c, LIST_APPEND, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004453 break;
4454 case COMP_SETCOMP:
4455 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004456 ADDOP_I(c, SET_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004457 break;
4458 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004459 /* With '{k: v}', k is evaluated before v, so we do
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004460 the same. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004461 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004462 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004463 ADDOP_I(c, MAP_ADD, depth + 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004464 break;
4465 default:
4466 return 0;
4467 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004469 compiler_use_next_block(c, skip);
4470 }
4471 compiler_use_next_block(c, if_cleanup);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004472 if (start) {
Mark Shannon582aaf12020-08-04 17:30:11 +01004473 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004474 compiler_use_next_block(c, anchor);
4475 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004476
4477 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004478}
4479
4480static int
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004481compiler_async_comprehension_generator(struct compiler *c,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004482 asdl_comprehension_seq *generators, int gen_index,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004483 int depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004484 expr_ty elt, expr_ty val, int type)
4485{
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004486 comprehension_ty gen;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004487 basicblock *start, *if_cleanup, *except;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004488 Py_ssize_t i, n;
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004489 start = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004490 except = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004491 if_cleanup = compiler_new_block(c);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004492
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004493 if (start == NULL || if_cleanup == NULL || except == NULL) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004494 return 0;
4495 }
4496
4497 gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
4498
4499 if (gen_index == 0) {
4500 /* Receive outermost iter as an implicit argument */
4501 c->u->u_argcount = 1;
4502 ADDOP_I(c, LOAD_FAST, 0);
4503 }
4504 else {
4505 /* Sub-iter - calculate on the fly */
4506 VISIT(c, expr, gen->iter);
4507 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004508 }
4509
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004510 compiler_use_next_block(c, start);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004511
Mark Shannon582aaf12020-08-04 17:30:11 +01004512 ADDOP_JUMP(c, SETUP_FINALLY, except);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004513 ADDOP(c, GET_ANEXT);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004514 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004515 ADDOP(c, YIELD_FROM);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004516 ADDOP(c, POP_BLOCK);
Serhiy Storchaka24d32012018-03-10 18:22:34 +02004517 VISIT(c, expr, gen->target);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004518
4519 n = asdl_seq_LEN(gen->ifs);
4520 for (i = 0; i < n; i++) {
4521 expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
Serhiy Storchaka36ff4512017-06-11 14:50:22 +03004522 if (!compiler_jump_if(c, e, if_cleanup, 0))
4523 return 0;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004524 NEXT_BLOCK(c);
4525 }
4526
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004527 depth++;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004528 if (++gen_index < asdl_seq_LEN(generators))
4529 if (!compiler_comprehension_generator(c,
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004530 generators, gen_index, depth,
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004531 elt, val, type))
4532 return 0;
4533
4534 /* only append after the last for generator */
4535 if (gen_index >= asdl_seq_LEN(generators)) {
4536 /* comprehension specific code */
4537 switch (type) {
4538 case COMP_GENEXP:
4539 VISIT(c, expr, elt);
4540 ADDOP(c, YIELD_VALUE);
4541 ADDOP(c, POP_TOP);
4542 break;
4543 case COMP_LISTCOMP:
4544 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004545 ADDOP_I(c, LIST_APPEND, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004546 break;
4547 case COMP_SETCOMP:
4548 VISIT(c, expr, elt);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004549 ADDOP_I(c, SET_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004550 break;
4551 case COMP_DICTCOMP:
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004552 /* With '{k: v}', k is evaluated before v, so we do
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004553 the same. */
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004554 VISIT(c, expr, elt);
Jörn Heisslerc8a35412019-06-22 16:40:55 +02004555 VISIT(c, expr, val);
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004556 ADDOP_I(c, MAP_ADD, depth + 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004557 break;
4558 default:
4559 return 0;
4560 }
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004561 }
4562 compiler_use_next_block(c, if_cleanup);
Mark Shannon582aaf12020-08-04 17:30:11 +01004563 ADDOP_JUMP(c, JUMP_ABSOLUTE, start);
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02004564
4565 compiler_use_next_block(c, except);
4566 ADDOP(c, END_ASYNC_FOR);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004567
4568 return 1;
4569}
4570
4571static int
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004572compiler_comprehension(struct compiler *c, expr_ty e, int type,
Pablo Galindoa5634c42020-09-16 19:42:00 +01004573 identifier name, asdl_comprehension_seq *generators, expr_ty elt,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004574 expr_ty val)
Nick Coghlan650f0d02007-04-15 12:05:43 +00004575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004576 PyCodeObject *co = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004577 comprehension_ty outermost;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004578 PyObject *qualname = NULL;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004579 int is_async_generator = 0;
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004580 int top_level_await = IS_TOP_LEVEL_AWAIT(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004581
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004582
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004583 int is_async_function = c->u->u_ste->ste_coroutine;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004584
Batuhan TaÅŸkaya9052f7a2020-03-19 14:35:44 +03004585 outermost = (comprehension_ty) asdl_seq_GET(generators, 0);
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004586 if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION,
4587 (void *)e, e->lineno))
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004588 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004589 goto error;
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004590 }
4591
4592 is_async_generator = c->u->u_ste->ste_coroutine;
4593
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004594 if (is_async_generator && !is_async_function && type != COMP_GENEXP && !top_level_await) {
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004595 compiler_error(c, "asynchronous comprehension outside of "
4596 "an asynchronous function");
4597 goto error_in_scope;
4598 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004600 if (type != COMP_GENEXP) {
4601 int op;
4602 switch (type) {
4603 case COMP_LISTCOMP:
4604 op = BUILD_LIST;
4605 break;
4606 case COMP_SETCOMP:
4607 op = BUILD_SET;
4608 break;
4609 case COMP_DICTCOMP:
4610 op = BUILD_MAP;
4611 break;
4612 default:
4613 PyErr_Format(PyExc_SystemError,
4614 "unknown comprehension type %d", type);
4615 goto error_in_scope;
4616 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004618 ADDOP_I(c, op, 0);
4619 }
Nick Coghlan650f0d02007-04-15 12:05:43 +00004620
Serhiy Storchaka8c579b12020-02-12 12:18:59 +02004621 if (!compiler_comprehension_generator(c, generators, 0, 0, elt,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004622 val, type))
4623 goto error_in_scope;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004625 if (type != COMP_GENEXP) {
4626 ADDOP(c, RETURN_VALUE);
4627 }
4628
4629 co = assemble(c, 1);
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004630 qualname = c->u->u_qualname;
4631 Py_INCREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004632 compiler_exit_scope(c);
Matthias Bussonnierbd461742020-07-06 14:26:52 -07004633 if (top_level_await && is_async_generator){
4634 c->u->u_ste->ste_coroutine = 1;
4635 }
Benjamin Peterson6b4f7802013-10-20 17:50:28 -04004636 if (co == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004637 goto error;
4638
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004639 if (!compiler_make_closure(c, co, 0, qualname))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004640 goto error;
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004641 Py_DECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004642 Py_DECREF(co);
4643
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004644 VISIT(c, expr, outermost->iter);
4645
4646 if (outermost->is_async) {
4647 ADDOP(c, GET_AITER);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004648 } else {
4649 ADDOP(c, GET_ITER);
4650 }
4651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004652 ADDOP_I(c, CALL_FUNCTION, 1);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004653
4654 if (is_async_generator && type != COMP_GENEXP) {
4655 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004656 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov52c4e7c2016-09-09 10:36:01 -07004657 ADDOP(c, YIELD_FROM);
4658 }
4659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004660 return 1;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004661error_in_scope:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004662 compiler_exit_scope(c);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004663error:
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004664 Py_XDECREF(qualname);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004665 Py_XDECREF(co);
4666 return 0;
Nick Coghlan650f0d02007-04-15 12:05:43 +00004667}
4668
4669static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004670compiler_genexp(struct compiler *c, expr_ty e)
4671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004672 static identifier name;
4673 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004674 name = PyUnicode_InternFromString("<genexpr>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004675 if (!name)
4676 return 0;
4677 }
4678 assert(e->kind == GeneratorExp_kind);
4679 return compiler_comprehension(c, e, COMP_GENEXP, name,
4680 e->v.GeneratorExp.generators,
4681 e->v.GeneratorExp.elt, NULL);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004682}
4683
4684static int
Nick Coghlan650f0d02007-04-15 12:05:43 +00004685compiler_listcomp(struct compiler *c, expr_ty e)
4686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004687 static identifier name;
4688 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004689 name = PyUnicode_InternFromString("<listcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004690 if (!name)
4691 return 0;
4692 }
4693 assert(e->kind == ListComp_kind);
4694 return compiler_comprehension(c, e, COMP_LISTCOMP, name,
4695 e->v.ListComp.generators,
4696 e->v.ListComp.elt, NULL);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004697}
4698
4699static int
4700compiler_setcomp(struct compiler *c, expr_ty e)
4701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004702 static identifier name;
4703 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004704 name = PyUnicode_InternFromString("<setcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004705 if (!name)
4706 return 0;
4707 }
4708 assert(e->kind == SetComp_kind);
4709 return compiler_comprehension(c, e, COMP_SETCOMP, name,
4710 e->v.SetComp.generators,
4711 e->v.SetComp.elt, NULL);
Guido van Rossum992d4a32007-07-11 13:09:30 +00004712}
4713
4714
4715static int
4716compiler_dictcomp(struct compiler *c, expr_ty e)
4717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004718 static identifier name;
4719 if (!name) {
Zackery Spytzf3036392018-04-15 16:12:29 -06004720 name = PyUnicode_InternFromString("<dictcomp>");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004721 if (!name)
4722 return 0;
4723 }
4724 assert(e->kind == DictComp_kind);
4725 return compiler_comprehension(c, e, COMP_DICTCOMP, name,
4726 e->v.DictComp.generators,
4727 e->v.DictComp.key, e->v.DictComp.value);
Nick Coghlan650f0d02007-04-15 12:05:43 +00004728}
4729
4730
4731static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004732compiler_visit_keyword(struct compiler *c, keyword_ty k)
4733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004734 VISIT(c, expr, k->value);
4735 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004736}
4737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004738/* Test whether expression is constant. For constants, report
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004739 whether they are true or false.
4740
4741 Return values: 1 for true, 0 for false, -1 for non-constant.
4742 */
4743
4744static int
Mark Shannonfee55262019-11-21 09:11:43 +00004745compiler_with_except_finish(struct compiler *c) {
4746 basicblock *exit;
4747 exit = compiler_new_block(c);
4748 if (exit == NULL)
4749 return 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01004750 ADDOP_JUMP(c, POP_JUMP_IF_TRUE, exit);
Mark Shannon266b4622020-11-17 19:30:14 +00004751 NEXT_BLOCK(c);
Mark Shannonbf353f32020-12-17 13:55:28 +00004752 ADDOP_I(c, RERAISE, 1);
Mark Shannonfee55262019-11-21 09:11:43 +00004753 compiler_use_next_block(c, exit);
4754 ADDOP(c, POP_TOP);
4755 ADDOP(c, POP_TOP);
4756 ADDOP(c, POP_TOP);
4757 ADDOP(c, POP_EXCEPT);
4758 ADDOP(c, POP_TOP);
4759 return 1;
4760}
Yury Selivanov75445082015-05-11 22:57:16 -04004761
4762/*
4763 Implements the async with statement.
4764
4765 The semantics outlined in that PEP are as follows:
4766
4767 async with EXPR as VAR:
4768 BLOCK
4769
4770 It is implemented roughly as:
4771
4772 context = EXPR
4773 exit = context.__aexit__ # not calling it
4774 value = await context.__aenter__()
4775 try:
4776 VAR = value # if VAR present in the syntax
4777 BLOCK
4778 finally:
4779 if an exception was raised:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004780 exc = copy of (exception, instance, traceback)
Yury Selivanov75445082015-05-11 22:57:16 -04004781 else:
Serhiy Storchakaec466a12015-06-11 00:09:32 +03004782 exc = (None, None, None)
Yury Selivanov75445082015-05-11 22:57:16 -04004783 if not (await exit(*exc)):
4784 raise
4785 */
4786static int
4787compiler_async_with(struct compiler *c, stmt_ty s, int pos)
4788{
Mark Shannonfee55262019-11-21 09:11:43 +00004789 basicblock *block, *final, *exit;
Yury Selivanov75445082015-05-11 22:57:16 -04004790 withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos);
4791
4792 assert(s->kind == AsyncWith_kind);
Pablo Galindo90235812020-03-15 04:29:22 +00004793 if (IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07004794 c->u->u_ste->ste_coroutine = 1;
4795 } else if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION){
Zsolt Dollensteine2396502018-04-27 08:58:56 -07004796 return compiler_error(c, "'async with' outside async function");
4797 }
Yury Selivanov75445082015-05-11 22:57:16 -04004798
4799 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004800 final = compiler_new_block(c);
4801 exit = compiler_new_block(c);
4802 if (!block || !final || !exit)
Yury Selivanov75445082015-05-11 22:57:16 -04004803 return 0;
4804
4805 /* Evaluate EXPR */
4806 VISIT(c, expr, item->context_expr);
4807
4808 ADDOP(c, BEFORE_ASYNC_WITH);
4809 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004810 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004811 ADDOP(c, YIELD_FROM);
4812
Mark Shannon582aaf12020-08-04 17:30:11 +01004813 ADDOP_JUMP(c, SETUP_ASYNC_WITH, final);
Yury Selivanov75445082015-05-11 22:57:16 -04004814
4815 /* SETUP_ASYNC_WITH pushes a finally block. */
4816 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004817 if (!compiler_push_fblock(c, ASYNC_WITH, block, final, NULL)) {
Yury Selivanov75445082015-05-11 22:57:16 -04004818 return 0;
4819 }
4820
4821 if (item->optional_vars) {
4822 VISIT(c, expr, item->optional_vars);
4823 }
4824 else {
4825 /* Discard result from context.__aenter__() */
4826 ADDOP(c, POP_TOP);
4827 }
4828
4829 pos++;
4830 if (pos == asdl_seq_LEN(s->v.AsyncWith.items))
4831 /* BLOCK code */
4832 VISIT_SEQ(c, stmt, s->v.AsyncWith.body)
4833 else if (!compiler_async_with(c, s, pos))
4834 return 0;
4835
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004836 compiler_pop_fblock(c, ASYNC_WITH, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004837 ADDOP(c, POP_BLOCK);
4838 /* End of body; start the cleanup */
Yury Selivanov75445082015-05-11 22:57:16 -04004839
Mark Shannonfee55262019-11-21 09:11:43 +00004840 /* For successful outcome:
4841 * call __exit__(None, None, None)
4842 */
4843 if(!compiler_call_exit_with_nones(c))
Yury Selivanov75445082015-05-11 22:57:16 -04004844 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004845 ADDOP(c, GET_AWAITABLE);
4846 ADDOP_O(c, LOAD_CONST, Py_None, consts);
4847 ADDOP(c, YIELD_FROM);
Yury Selivanov75445082015-05-11 22:57:16 -04004848
Mark Shannonfee55262019-11-21 09:11:43 +00004849 ADDOP(c, POP_TOP);
Yury Selivanov75445082015-05-11 22:57:16 -04004850
Mark Shannon582aaf12020-08-04 17:30:11 +01004851 ADDOP_JUMP(c, JUMP_ABSOLUTE, exit);
Mark Shannonfee55262019-11-21 09:11:43 +00004852
4853 /* For exceptional outcome: */
4854 compiler_use_next_block(c, final);
4855
4856 ADDOP(c, WITH_EXCEPT_START);
Yury Selivanov75445082015-05-11 22:57:16 -04004857 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004858 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04004859 ADDOP(c, YIELD_FROM);
Mark Shannonfee55262019-11-21 09:11:43 +00004860 compiler_with_except_finish(c);
Yury Selivanov75445082015-05-11 22:57:16 -04004861
Mark Shannonfee55262019-11-21 09:11:43 +00004862compiler_use_next_block(c, exit);
Yury Selivanov75445082015-05-11 22:57:16 -04004863 return 1;
4864}
4865
4866
Guido van Rossumc2e20742006-02-27 22:32:47 +00004867/*
4868 Implements the with statement from PEP 343.
Guido van Rossumc2e20742006-02-27 22:32:47 +00004869 with EXPR as VAR:
4870 BLOCK
Mark Shannonfee55262019-11-21 09:11:43 +00004871 is implemented as:
4872 <code for EXPR>
4873 SETUP_WITH E
4874 <code to store to VAR> or POP_TOP
4875 <code for BLOCK>
4876 LOAD_CONST (None, None, None)
4877 CALL_FUNCTION_EX 0
4878 JUMP_FORWARD EXIT
4879 E: WITH_EXCEPT_START (calls EXPR.__exit__)
4880 POP_JUMP_IF_TRUE T:
4881 RERAISE
4882 T: POP_TOP * 3 (remove exception from stack)
4883 POP_EXCEPT
4884 POP_TOP
4885 EXIT:
Guido van Rossumc2e20742006-02-27 22:32:47 +00004886 */
Mark Shannonfee55262019-11-21 09:11:43 +00004887
Guido van Rossumc2e20742006-02-27 22:32:47 +00004888static int
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004889compiler_with(struct compiler *c, stmt_ty s, int pos)
Guido van Rossumc2e20742006-02-27 22:32:47 +00004890{
Mark Shannonfee55262019-11-21 09:11:43 +00004891 basicblock *block, *final, *exit;
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004892 withitem_ty item = asdl_seq_GET(s->v.With.items, pos);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004893
4894 assert(s->kind == With_kind);
4895
Guido van Rossumc2e20742006-02-27 22:32:47 +00004896 block = compiler_new_block(c);
Mark Shannonfee55262019-11-21 09:11:43 +00004897 final = compiler_new_block(c);
4898 exit = compiler_new_block(c);
4899 if (!block || !final || !exit)
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004900 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004901
Thomas Wouters477c8d52006-05-27 19:21:47 +00004902 /* Evaluate EXPR */
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004903 VISIT(c, expr, item->context_expr);
Mark Shannonfee55262019-11-21 09:11:43 +00004904 /* Will push bound __exit__ */
Mark Shannon582aaf12020-08-04 17:30:11 +01004905 ADDOP_JUMP(c, SETUP_WITH, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004906
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004907 /* SETUP_WITH pushes a finally block. */
Guido van Rossumc2e20742006-02-27 22:32:47 +00004908 compiler_use_next_block(c, block);
Mark Shannonfee55262019-11-21 09:11:43 +00004909 if (!compiler_push_fblock(c, WITH, block, final, NULL)) {
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004910 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004911 }
4912
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004913 if (item->optional_vars) {
4914 VISIT(c, expr, item->optional_vars);
Benjamin Peterson876b2f22009-06-28 03:18:59 +00004915 }
4916 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004917 /* Discard result from context.__enter__() */
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004918 ADDOP(c, POP_TOP);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004919 }
4920
Benjamin Petersonbf1bbc12011-05-27 13:58:08 -05004921 pos++;
4922 if (pos == asdl_seq_LEN(s->v.With.items))
4923 /* BLOCK code */
4924 VISIT_SEQ(c, stmt, s->v.With.body)
4925 else if (!compiler_with(c, s, pos))
4926 return 0;
Guido van Rossumc2e20742006-02-27 22:32:47 +00004927
Guido van Rossumc2e20742006-02-27 22:32:47 +00004928 ADDOP(c, POP_BLOCK);
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02004929 compiler_pop_fblock(c, WITH, block);
Mark Shannon13bc1392020-01-23 09:25:17 +00004930
Mark Shannonfee55262019-11-21 09:11:43 +00004931 /* End of body; start the cleanup. */
Mark Shannon13bc1392020-01-23 09:25:17 +00004932
Mark Shannonfee55262019-11-21 09:11:43 +00004933 /* For successful outcome:
4934 * call __exit__(None, None, None)
4935 */
4936 if (!compiler_call_exit_with_nones(c))
Antoine Pitrou9aee2c82010-06-22 21:49:39 +00004937 return 0;
Mark Shannonfee55262019-11-21 09:11:43 +00004938 ADDOP(c, POP_TOP);
Mark Shannon582aaf12020-08-04 17:30:11 +01004939 ADDOP_JUMP(c, JUMP_FORWARD, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004940
Mark Shannonfee55262019-11-21 09:11:43 +00004941 /* For exceptional outcome: */
4942 compiler_use_next_block(c, final);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004943
Mark Shannonfee55262019-11-21 09:11:43 +00004944 ADDOP(c, WITH_EXCEPT_START);
4945 compiler_with_except_finish(c);
4946
4947 compiler_use_next_block(c, exit);
Guido van Rossumc2e20742006-02-27 22:32:47 +00004948 return 1;
4949}
4950
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004951static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03004952compiler_visit_expr1(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00004953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004954 switch (e->kind) {
Emily Morehouse8f59ee02019-01-24 16:49:56 -07004955 case NamedExpr_kind:
4956 VISIT(c, expr, e->v.NamedExpr.value);
4957 ADDOP(c, DUP_TOP);
4958 VISIT(c, expr, e->v.NamedExpr.target);
4959 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004960 case BoolOp_kind:
4961 return compiler_boolop(c, e);
4962 case BinOp_kind:
4963 VISIT(c, expr, e->v.BinOp.left);
4964 VISIT(c, expr, e->v.BinOp.right);
Andy Lester76d58772020-03-10 21:18:12 -05004965 ADDOP(c, binop(e->v.BinOp.op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004966 break;
4967 case UnaryOp_kind:
4968 VISIT(c, expr, e->v.UnaryOp.operand);
4969 ADDOP(c, unaryop(e->v.UnaryOp.op));
4970 break;
4971 case Lambda_kind:
4972 return compiler_lambda(c, e);
4973 case IfExp_kind:
4974 return compiler_ifexp(c, e);
4975 case Dict_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004976 return compiler_dict(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004977 case Set_kind:
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04004978 return compiler_set(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004979 case GeneratorExp_kind:
4980 return compiler_genexp(c, e);
4981 case ListComp_kind:
4982 return compiler_listcomp(c, e);
4983 case SetComp_kind:
4984 return compiler_setcomp(c, e);
4985 case DictComp_kind:
4986 return compiler_dictcomp(c, e);
4987 case Yield_kind:
4988 if (c->u->u_ste->ste_type != FunctionBlock)
4989 return compiler_error(c, "'yield' outside function");
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004990 if (e->v.Yield.value) {
4991 VISIT(c, expr, e->v.Yield.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004992 }
4993 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03004994 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004995 }
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004996 ADDOP(c, YIELD_VALUE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00004997 break;
Mark Dickinsonded35ae2012-11-25 14:36:26 +00004998 case YieldFrom_kind:
4999 if (c->u->u_ste->ste_type != FunctionBlock)
5000 return compiler_error(c, "'yield' outside function");
Yury Selivanov75445082015-05-11 22:57:16 -04005001
5002 if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION)
5003 return compiler_error(c, "'yield from' inside async function");
5004
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005005 VISIT(c, expr, e->v.YieldFrom.value);
Yury Selivanov5376ba92015-06-22 12:19:30 -04005006 ADDOP(c, GET_YIELD_FROM_ITER);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005007 ADDOP_LOAD_CONST(c, Py_None);
Mark Dickinsonded35ae2012-11-25 14:36:26 +00005008 ADDOP(c, YIELD_FROM);
5009 break;
Yury Selivanov75445082015-05-11 22:57:16 -04005010 case Await_kind:
Pablo Galindo90235812020-03-15 04:29:22 +00005011 if (!IS_TOP_LEVEL_AWAIT(c)){
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005012 if (c->u->u_ste->ste_type != FunctionBlock){
5013 return compiler_error(c, "'await' outside function");
5014 }
Yury Selivanov75445082015-05-11 22:57:16 -04005015
Victor Stinner331a6a52019-05-27 16:39:22 +02005016 if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005017 c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION){
5018 return compiler_error(c, "'await' outside async function");
5019 }
5020 }
Yury Selivanov75445082015-05-11 22:57:16 -04005021
5022 VISIT(c, expr, e->v.Await.value);
5023 ADDOP(c, GET_AWAITABLE);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005024 ADDOP_LOAD_CONST(c, Py_None);
Yury Selivanov75445082015-05-11 22:57:16 -04005025 ADDOP(c, YIELD_FROM);
5026 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005027 case Compare_kind:
5028 return compiler_compare(c, e);
5029 case Call_kind:
5030 return compiler_call(c, e);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005031 case Constant_kind:
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005032 ADDOP_LOAD_CONST(c, e->v.Constant.value);
Victor Stinnerf2c1aa12016-01-26 00:40:57 +01005033 break;
Eric V. Smith235a6f02015-09-19 14:51:32 -04005034 case JoinedStr_kind:
5035 return compiler_joined_str(c, e);
5036 case FormattedValue_kind:
5037 return compiler_formatted_value(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005038 /* The following exprs can be assignment targets. */
5039 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005040 VISIT(c, expr, e->v.Attribute.value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005041 switch (e->v.Attribute.ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005042 case Load:
5043 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
5044 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005045 case Store:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005046 if (forbidden_name(c, e->v.Attribute.attr, e->v.Attribute.ctx))
5047 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005048 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5049 break;
5050 case Del:
5051 ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
5052 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005053 }
5054 break;
5055 case Subscript_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005056 return compiler_subscript(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005057 case Starred_kind:
5058 switch (e->v.Starred.ctx) {
5059 case Store:
5060 /* In all legitimate cases, the Starred node was already replaced
5061 * by compiler_list/compiler_tuple. XXX: is that okay? */
5062 return compiler_error(c,
5063 "starred assignment target must be in a list or tuple");
5064 default:
5065 return compiler_error(c,
Benjamin Peterson025e9eb2015-05-05 20:16:41 -04005066 "can't use starred expression here");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005067 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005068 break;
5069 case Slice_kind:
5070 return compiler_slice(c, e);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005071 case Name_kind:
5072 return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
5073 /* child nodes of List and Tuple will have expr_context set */
5074 case List_kind:
5075 return compiler_list(c, e);
5076 case Tuple_kind:
5077 return compiler_tuple(c, e);
5078 }
5079 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005080}
5081
5082static int
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005083compiler_visit_expr(struct compiler *c, expr_ty e)
5084{
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005085 int old_lineno = c->u->u_lineno;
5086 int old_col_offset = c->u->u_col_offset;
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005087 SET_LOC(c, e);
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005088 int res = compiler_visit_expr1(c, e);
Serhiy Storchaka61cb3d02020-03-17 18:07:30 +02005089 c->u->u_lineno = old_lineno;
Serhiy Storchakada8d72c2018-09-17 15:17:29 +03005090 c->u->u_col_offset = old_col_offset;
5091 return res;
5092}
5093
5094static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005095compiler_augassign(struct compiler *c, stmt_ty s)
5096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005097 assert(s->kind == AugAssign_kind);
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005098 expr_ty e = s->v.AugAssign.target;
5099
5100 int old_lineno = c->u->u_lineno;
5101 int old_col_offset = c->u->u_col_offset;
5102 SET_LOC(c, e);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005104 switch (e->kind) {
5105 case Attribute_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005106 VISIT(c, expr, e->v.Attribute.value);
5107 ADDOP(c, DUP_TOP);
5108 ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005109 break;
5110 case Subscript_kind:
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005111 VISIT(c, expr, e->v.Subscript.value);
5112 VISIT(c, expr, e->v.Subscript.slice);
5113 ADDOP(c, DUP_TOP_TWO);
5114 ADDOP(c, BINARY_SUBSCR);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005115 break;
5116 case Name_kind:
5117 if (!compiler_nameop(c, e->v.Name.id, Load))
5118 return 0;
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005119 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005120 default:
5121 PyErr_Format(PyExc_SystemError,
5122 "invalid node type (%d) for augmented assignment",
5123 e->kind);
5124 return 0;
5125 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005126
5127 c->u->u_lineno = old_lineno;
5128 c->u->u_col_offset = old_col_offset;
5129
5130 VISIT(c, expr, s->v.AugAssign.value);
5131 ADDOP(c, inplace_binop(s->v.AugAssign.op));
5132
5133 SET_LOC(c, e);
5134
5135 switch (e->kind) {
5136 case Attribute_kind:
5137 ADDOP(c, ROT_TWO);
5138 ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
5139 break;
5140 case Subscript_kind:
5141 ADDOP(c, ROT_THREE);
5142 ADDOP(c, STORE_SUBSCR);
5143 break;
5144 case Name_kind:
5145 return compiler_nameop(c, e->v.Name.id, Store);
5146 default:
5147 Py_UNREACHABLE();
5148 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005149 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005150}
5151
5152static int
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005153check_ann_expr(struct compiler *c, expr_ty e)
5154{
5155 VISIT(c, expr, e);
5156 ADDOP(c, POP_TOP);
5157 return 1;
5158}
5159
5160static int
5161check_annotation(struct compiler *c, stmt_ty s)
5162{
5163 /* Annotations are only evaluated in a module or class. */
5164 if (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5165 c->u->u_scope_type == COMPILER_SCOPE_CLASS) {
5166 return check_ann_expr(c, s->v.AnnAssign.annotation);
5167 }
5168 return 1;
5169}
5170
5171static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005172check_ann_subscr(struct compiler *c, expr_ty e)
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005173{
5174 /* We check that everything in a subscript is defined at runtime. */
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005175 switch (e->kind) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005176 case Slice_kind:
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005177 if (e->v.Slice.lower && !check_ann_expr(c, e->v.Slice.lower)) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005178 return 0;
5179 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005180 if (e->v.Slice.upper && !check_ann_expr(c, e->v.Slice.upper)) {
5181 return 0;
5182 }
5183 if (e->v.Slice.step && !check_ann_expr(c, e->v.Slice.step)) {
5184 return 0;
5185 }
5186 return 1;
5187 case Tuple_kind: {
5188 /* extended slice */
Pablo Galindoa5634c42020-09-16 19:42:00 +01005189 asdl_expr_seq *elts = e->v.Tuple.elts;
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005190 Py_ssize_t i, n = asdl_seq_LEN(elts);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005191 for (i = 0; i < n; i++) {
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005192 if (!check_ann_subscr(c, asdl_seq_GET(elts, i))) {
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005193 return 0;
5194 }
5195 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005196 return 1;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005197 }
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005198 default:
5199 return check_ann_expr(c, e);
5200 }
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005201}
5202
5203static int
5204compiler_annassign(struct compiler *c, stmt_ty s)
5205{
5206 expr_ty targ = s->v.AnnAssign.target;
Guido van Rossum015d8742016-09-11 09:45:24 -07005207 PyObject* mangled;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005208
5209 assert(s->kind == AnnAssign_kind);
5210
5211 /* We perform the actual assignment first. */
5212 if (s->v.AnnAssign.value) {
5213 VISIT(c, expr, s->v.AnnAssign.value);
5214 VISIT(c, expr, targ);
5215 }
5216 switch (targ->kind) {
5217 case Name_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005218 if (forbidden_name(c, targ->v.Name.id, Store))
5219 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005220 /* If we have a simple name in a module or class, store annotation. */
5221 if (s->v.AnnAssign.simple &&
5222 (c->u->u_scope_type == COMPILER_SCOPE_MODULE ||
5223 c->u->u_scope_type == COMPILER_SCOPE_CLASS)) {
Batuhan Taskaya044a1042020-10-06 23:03:02 +03005224 VISIT(c, annexpr, s->v.AnnAssign.annotation);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005225 ADDOP_NAME(c, LOAD_NAME, __annotations__, names);
Serhiy Storchakaa95d9862018-03-24 22:42:35 +02005226 mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005227 ADDOP_LOAD_CONST_NEW(c, mangled);
Mark Shannon332cd5e2018-01-30 00:41:04 +00005228 ADDOP(c, STORE_SUBSCR);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005229 }
5230 break;
5231 case Attribute_kind:
Pablo Galindoc5fc1562020-04-22 23:29:27 +01005232 if (forbidden_name(c, targ->v.Attribute.attr, Store))
5233 return 0;
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07005234 if (!s->v.AnnAssign.value &&
5235 !check_ann_expr(c, targ->v.Attribute.value)) {
5236 return 0;
5237 }
5238 break;
5239 case Subscript_kind:
5240 if (!s->v.AnnAssign.value &&
5241 (!check_ann_expr(c, targ->v.Subscript.value) ||
5242 !check_ann_subscr(c, targ->v.Subscript.slice))) {
5243 return 0;
5244 }
5245 break;
5246 default:
5247 PyErr_Format(PyExc_SystemError,
5248 "invalid node type (%d) for annotated assignment",
5249 targ->kind);
5250 return 0;
5251 }
5252 /* Annotation is evaluated last. */
5253 if (!s->v.AnnAssign.simple && !check_annotation(c, s)) {
5254 return 0;
5255 }
5256 return 1;
5257}
5258
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005259/* Raises a SyntaxError and returns 0.
5260 If something goes wrong, a different exception may be raised.
5261*/
5262
5263static int
5264compiler_error(struct compiler *c, const char *errstr)
5265{
Benjamin Peterson43b06862011-05-27 09:08:01 -05005266 PyObject *loc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005267 PyObject *u = NULL, *v = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005268
Victor Stinner14e461d2013-08-26 22:28:21 +02005269 loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005270 if (!loc) {
5271 Py_INCREF(Py_None);
5272 loc = Py_None;
5273 }
Victor Stinner14e461d2013-08-26 22:28:21 +02005274 u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno,
Ammar Askar025eb982018-09-24 17:12:49 -04005275 c->u->u_col_offset + 1, loc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005276 if (!u)
5277 goto exit;
5278 v = Py_BuildValue("(zO)", errstr, u);
5279 if (!v)
5280 goto exit;
5281 PyErr_SetObject(PyExc_SyntaxError, v);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005282 exit:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005283 Py_DECREF(loc);
5284 Py_XDECREF(u);
5285 Py_XDECREF(v);
5286 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005287}
5288
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005289/* Emits a SyntaxWarning and returns 1 on success.
5290 If a SyntaxWarning raised as error, replaces it with a SyntaxError
5291 and returns 0.
5292*/
5293static int
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005294compiler_warn(struct compiler *c, const char *format, ...)
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005295{
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005296 va_list vargs;
5297#ifdef HAVE_STDARG_PROTOTYPES
5298 va_start(vargs, format);
5299#else
5300 va_start(vargs);
5301#endif
5302 PyObject *msg = PyUnicode_FromFormatV(format, vargs);
5303 va_end(vargs);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005304 if (msg == NULL) {
5305 return 0;
5306 }
5307 if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename,
5308 c->u->u_lineno, NULL, NULL) < 0)
5309 {
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005310 if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005311 /* Replace the SyntaxWarning exception with a SyntaxError
5312 to get a more accurate error report */
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005313 PyErr_Clear();
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005314 assert(PyUnicode_AsUTF8(msg) != NULL);
5315 compiler_error(c, PyUnicode_AsUTF8(msg));
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005316 }
Serhiy Storchaka62e44812019-02-16 08:12:19 +02005317 Py_DECREF(msg);
Serhiy Storchakad31e7732018-10-21 10:09:39 +03005318 return 0;
5319 }
5320 Py_DECREF(msg);
5321 return 1;
5322}
5323
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005324static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005325compiler_subscript(struct compiler *c, expr_ty e)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005326{
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005327 expr_context_ty ctx = e->v.Subscript.ctx;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005328 int op = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005329
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005330 if (ctx == Load) {
5331 if (!check_subscripter(c, e->v.Subscript.value)) {
5332 return 0;
5333 }
5334 if (!check_index(c, e->v.Subscript.value, e->v.Subscript.slice)) {
5335 return 0;
5336 }
5337 }
5338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005339 switch (ctx) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005340 case Load: op = BINARY_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005341 case Store: op = STORE_SUBSCR; break;
5342 case Del: op = DELETE_SUBSCR; break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005343 }
Serhiy Storchaka6b975982020-03-17 23:41:08 +02005344 assert(op);
5345 VISIT(c, expr, e->v.Subscript.value);
5346 VISIT(c, expr, e->v.Subscript.slice);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005347 ADDOP(c, op);
5348 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005349}
5350
5351static int
Serhiy Storchaka13d52c22020-03-10 18:52:34 +02005352compiler_slice(struct compiler *c, expr_ty s)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005354 int n = 2;
5355 assert(s->kind == Slice_kind);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005357 /* only handles the cases where BUILD_SLICE is emitted */
5358 if (s->v.Slice.lower) {
5359 VISIT(c, expr, s->v.Slice.lower);
5360 }
5361 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005362 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005363 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005365 if (s->v.Slice.upper) {
5366 VISIT(c, expr, s->v.Slice.upper);
5367 }
5368 else {
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005369 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005370 }
5371
5372 if (s->v.Slice.step) {
5373 n++;
5374 VISIT(c, expr, s->v.Slice.step);
5375 }
5376 ADDOP_I(c, BUILD_SLICE, n);
5377 return 1;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005378}
5379
Thomas Wouters89f507f2006-12-13 04:49:30 +00005380/* End of the compiler section, beginning of the assembler section */
5381
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005382/* do depth-first search of basic block graph, starting with block.
T. Wouters99b54d62019-09-12 07:05:33 -07005383 post records the block indices in post-order.
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005384
5385 XXX must handle implicit jumps from one block to next
5386*/
5387
Thomas Wouters89f507f2006-12-13 04:49:30 +00005388struct assembler {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005389 PyObject *a_bytecode; /* string containing bytecode */
5390 int a_offset; /* offset into bytecode */
5391 int a_nblocks; /* number of reachable blocks */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005392 PyObject *a_lnotab; /* string containing lnotab */
5393 int a_lnotab_off; /* offset into lnotab */
Mark Shannon877df852020-11-12 09:43:29 +00005394 int a_prevlineno; /* lineno of last emitted line in line table */
5395 int a_lineno; /* lineno of last emitted instruction */
5396 int a_lineno_start; /* bytecode start offset of current lineno */
Mark Shannoncc75ab72020-11-12 19:49:33 +00005397 basicblock *a_entry;
Thomas Wouters89f507f2006-12-13 04:49:30 +00005398};
5399
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005400Py_LOCAL_INLINE(void)
5401stackdepth_push(basicblock ***sp, basicblock *b, int depth)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005402{
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02005403 assert(b->b_startdepth < 0 || b->b_startdepth == depth);
Mark Shannonfee55262019-11-21 09:11:43 +00005404 if (b->b_startdepth < depth && b->b_startdepth < 100) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005405 assert(b->b_startdepth < 0);
5406 b->b_startdepth = depth;
5407 *(*sp)++ = b;
Serhiy Storchakad4864c62018-01-09 21:54:52 +02005408 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005409}
5410
5411/* Find the flow path that needs the largest stack. We assume that
5412 * cycles in the flow graph have no net effect on the stack depth.
5413 */
5414static int
5415stackdepth(struct compiler *c)
5416{
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005417 basicblock *b, *entryblock = NULL;
5418 basicblock **stack, **sp;
5419 int nblocks = 0, maxdepth = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005420 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005421 b->b_startdepth = INT_MIN;
5422 entryblock = b;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005423 nblocks++;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005424 }
5425 if (!entryblock)
5426 return 0;
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005427 stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * nblocks);
5428 if (!stack) {
5429 PyErr_NoMemory();
5430 return -1;
5431 }
5432
5433 sp = stack;
5434 stackdepth_push(&sp, entryblock, 0);
5435 while (sp != stack) {
5436 b = *--sp;
5437 int depth = b->b_startdepth;
5438 assert(depth >= 0);
5439 basicblock *next = b->b_next;
5440 for (int i = 0; i < b->b_iused; i++) {
5441 struct instr *instr = &b->b_instr[i];
5442 int effect = stack_effect(instr->i_opcode, instr->i_oparg, 0);
5443 if (effect == PY_INVALID_STACK_EFFECT) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01005444 _Py_FatalErrorFormat(__func__,
5445 "opcode = %d", instr->i_opcode);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005446 }
5447 int new_depth = depth + effect;
5448 if (new_depth > maxdepth) {
5449 maxdepth = new_depth;
5450 }
5451 assert(depth >= 0); /* invalid code or bug in stackdepth() */
Mark Shannon582aaf12020-08-04 17:30:11 +01005452 if (is_jump(instr)) {
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005453 effect = stack_effect(instr->i_opcode, instr->i_oparg, 1);
5454 assert(effect != PY_INVALID_STACK_EFFECT);
5455 int target_depth = depth + effect;
5456 if (target_depth > maxdepth) {
5457 maxdepth = target_depth;
5458 }
5459 assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005460 stackdepth_push(&sp, instr->i_target, target_depth);
5461 }
5462 depth = new_depth;
5463 if (instr->i_opcode == JUMP_ABSOLUTE ||
5464 instr->i_opcode == JUMP_FORWARD ||
5465 instr->i_opcode == RETURN_VALUE ||
Mark Shannonfee55262019-11-21 09:11:43 +00005466 instr->i_opcode == RAISE_VARARGS ||
5467 instr->i_opcode == RERAISE)
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005468 {
5469 /* remaining code is dead */
5470 next = NULL;
5471 break;
5472 }
5473 }
5474 if (next != NULL) {
Mark Shannon266b4622020-11-17 19:30:14 +00005475 assert(b->b_nofallthrough == 0);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005476 stackdepth_push(&sp, next, depth);
5477 }
5478 }
5479 PyObject_Free(stack);
5480 return maxdepth;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005481}
5482
5483static int
5484assemble_init(struct assembler *a, int nblocks, int firstlineno)
5485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005486 memset(a, 0, sizeof(struct assembler));
Mark Shannon877df852020-11-12 09:43:29 +00005487 a->a_prevlineno = a->a_lineno = firstlineno;
Mark Shannonfd009e62020-11-13 12:53:53 +00005488 a->a_lnotab = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005489 a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005490 if (a->a_bytecode == NULL) {
5491 goto error;
5492 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005493 a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
Mark Shannonfd009e62020-11-13 12:53:53 +00005494 if (a->a_lnotab == NULL) {
5495 goto error;
5496 }
Benjamin Peterson2f8bfef2016-09-07 09:26:18 -07005497 if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005498 PyErr_NoMemory();
Mark Shannonfd009e62020-11-13 12:53:53 +00005499 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005500 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005501 return 1;
Mark Shannonfd009e62020-11-13 12:53:53 +00005502error:
5503 Py_XDECREF(a->a_bytecode);
5504 Py_XDECREF(a->a_lnotab);
5505 return 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005506}
5507
5508static void
5509assemble_free(struct assembler *a)
5510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005511 Py_XDECREF(a->a_bytecode);
5512 Py_XDECREF(a->a_lnotab);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005513}
5514
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005515static int
5516blocksize(basicblock *b)
5517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005518 int i;
5519 int size = 0;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005521 for (i = 0; i < b->b_iused; i++)
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005522 size += instrsize(b->b_instr[i].i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005523 return size;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005524}
5525
Guido van Rossumf68d8e52001-04-14 17:55:09 +00005526static int
Mark Shannon877df852020-11-12 09:43:29 +00005527assemble_emit_linetable_pair(struct assembler *a, int bdelta, int ldelta)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005528{
Mark Shannon877df852020-11-12 09:43:29 +00005529 Py_ssize_t len = PyBytes_GET_SIZE(a->a_lnotab);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005530 if (a->a_lnotab_off + 2 >= len) {
5531 if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0)
5532 return 0;
5533 }
Mark Shannon877df852020-11-12 09:43:29 +00005534 unsigned char *lnotab = (unsigned char *)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005535 PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
Tim Peters51e26512001-09-07 08:45:55 +00005536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005537 a->a_lnotab_off += 2;
Mark Shannon877df852020-11-12 09:43:29 +00005538 *lnotab++ = bdelta;
5539 *lnotab++ = ldelta;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005540 return 1;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005541}
5542
Mark Shannon877df852020-11-12 09:43:29 +00005543/* Appends a range to the end of the line number table. See
5544 * Objects/lnotab_notes.txt for the description of the line number table. */
5545
5546static int
5547assemble_line_range(struct assembler *a)
5548{
5549 int ldelta, bdelta;
5550 bdelta = (a->a_offset - a->a_lineno_start) * 2;
5551 if (bdelta == 0) {
5552 return 1;
5553 }
5554 if (a->a_lineno < 0) {
5555 ldelta = -128;
5556 }
5557 else {
5558 ldelta = a->a_lineno - a->a_prevlineno;
5559 a->a_prevlineno = a->a_lineno;
5560 while (ldelta > 127) {
5561 if (!assemble_emit_linetable_pair(a, 0, 127)) {
5562 return 0;
5563 }
5564 ldelta -= 127;
5565 }
5566 while (ldelta < -127) {
5567 if (!assemble_emit_linetable_pair(a, 0, -127)) {
5568 return 0;
5569 }
5570 ldelta += 127;
5571 }
5572 }
5573 assert(-128 <= ldelta && ldelta < 128);
5574 while (bdelta > 254) {
5575 if (!assemble_emit_linetable_pair(a, 254, ldelta)) {
5576 return 0;
5577 }
5578 ldelta = a->a_lineno < 0 ? -128 : 0;
5579 bdelta -= 254;
5580 }
5581 if (!assemble_emit_linetable_pair(a, bdelta, ldelta)) {
5582 return 0;
5583 }
5584 a->a_lineno_start = a->a_offset;
5585 return 1;
5586}
5587
5588static int
5589assemble_lnotab(struct assembler *a, struct instr *i)
5590{
5591 if (i->i_lineno == a->a_lineno) {
5592 return 1;
5593 }
5594 if (!assemble_line_range(a)) {
5595 return 0;
5596 }
5597 a->a_lineno = i->i_lineno;
5598 return 1;
5599}
5600
5601
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005602/* assemble_emit()
5603 Extend the bytecode with a new instruction.
5604 Update lnotab if necessary.
Jeremy Hylton376e63d2003-08-28 14:42:14 +00005605*/
5606
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005607static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005608assemble_emit(struct assembler *a, struct instr *i)
Guido van Rossum4ca6c9d1994-08-29 12:16:12 +00005609{
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005610 int size, arg = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005611 Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode);
Serhiy Storchakaab874002016-09-11 13:48:15 +03005612 _Py_CODEUNIT *code;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005613
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005614 arg = i->i_oparg;
5615 size = instrsize(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005616 if (i->i_lineno && !assemble_lnotab(a, i))
5617 return 0;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005618 if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005619 if (len > PY_SSIZE_T_MAX / 2)
5620 return 0;
5621 if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0)
5622 return 0;
5623 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005624 code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005625 a->a_offset += size;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005626 write_op_arg(code, i->i_opcode, arg, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005627 return 1;
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005628}
5629
Neal Norwitz7d37f2f2005-10-23 22:40:47 +00005630static void
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005631assemble_jump_offsets(struct assembler *a, struct compiler *c)
Anthony Baxterc2a5a632004-08-02 06:10:11 +00005632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005633 basicblock *b;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005634 int bsize, totsize, extended_arg_recompile;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005635 int i;
Guido van Rossumc5e96291991-12-10 13:53:51 +00005636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005637 /* Compute the size of each block and fixup jump args.
5638 Replace block pointer with position in bytecode. */
5639 do {
5640 totsize = 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005641 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005642 bsize = blocksize(b);
5643 b->b_offset = totsize;
5644 totsize += bsize;
5645 }
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005646 extended_arg_recompile = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005647 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5648 bsize = b->b_offset;
5649 for (i = 0; i < b->b_iused; i++) {
5650 struct instr *instr = &b->b_instr[i];
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005651 int isize = instrsize(instr->i_oparg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005652 /* Relative jumps are computed relative to
5653 the instruction pointer after fetching
5654 the jump instruction.
5655 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005656 bsize += isize;
Mark Shannon582aaf12020-08-04 17:30:11 +01005657 if (is_jump(instr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005658 instr->i_oparg = instr->i_target->b_offset;
Mark Shannon582aaf12020-08-04 17:30:11 +01005659 if (is_relative_jump(instr)) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005660 instr->i_oparg -= bsize;
5661 }
Serhiy Storchakaab874002016-09-11 13:48:15 +03005662 instr->i_oparg *= sizeof(_Py_CODEUNIT);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005663 if (instrsize(instr->i_oparg) != isize) {
5664 extended_arg_recompile = 1;
5665 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005666 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005667 }
5668 }
Neal Norwitzf1d50682005-10-23 23:00:41 +00005669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005670 /* XXX: This is an awful hack that could hurt performance, but
5671 on the bright side it should work until we come up
5672 with a better solution.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005674 The issue is that in the first loop blocksize() is called
5675 which calls instrsize() which requires i_oparg be set
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005676 appropriately. There is a bootstrap problem because
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005677 i_oparg is calculated in the second loop above.
Neal Norwitzf1d50682005-10-23 23:00:41 +00005678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005679 So we loop until we stop seeing new EXTENDED_ARGs.
5680 The only EXTENDED_ARGs that could be popping up are
5681 ones in jump instructions. So this should converge
5682 fairly quickly.
5683 */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005684 } while (extended_arg_recompile);
Guido van Rossum10dc2e81990-11-18 17:27:39 +00005685}
5686
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005687static PyObject *
Victor Stinnerad9a0662013-11-19 22:23:20 +01005688dict_keys_inorder(PyObject *dict, Py_ssize_t offset)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005690 PyObject *tuple, *k, *v;
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005691 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005693 tuple = PyTuple_New(size);
5694 if (tuple == NULL)
5695 return NULL;
5696 while (PyDict_Next(dict, &pos, &k, &v)) {
5697 i = PyLong_AS_LONG(v);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005698 Py_INCREF(k);
5699 assert((i - offset) < size);
5700 assert((i - offset) >= 0);
5701 PyTuple_SET_ITEM(tuple, i - offset, k);
5702 }
5703 return tuple;
5704}
5705
5706static PyObject *
5707consts_dict_keys_inorder(PyObject *dict)
5708{
5709 PyObject *consts, *k, *v;
5710 Py_ssize_t i, pos = 0, size = PyDict_GET_SIZE(dict);
5711
5712 consts = PyList_New(size); /* PyCode_Optimize() requires a list */
5713 if (consts == NULL)
5714 return NULL;
5715 while (PyDict_Next(dict, &pos, &k, &v)) {
5716 i = PyLong_AS_LONG(v);
Serhiy Storchakab7e1eff2018-04-19 08:28:04 +03005717 /* The keys of the dictionary can be tuples wrapping a contant.
5718 * (see compiler_add_o and _PyCode_ConstantKey). In that case
5719 * the object we want is always second. */
5720 if (PyTuple_CheckExact(k)) {
5721 k = PyTuple_GET_ITEM(k, 1);
5722 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005723 Py_INCREF(k);
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005724 assert(i < size);
5725 assert(i >= 0);
5726 PyList_SET_ITEM(consts, i, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005727 }
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005728 return consts;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005729}
5730
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005731static int
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005732compute_code_flags(struct compiler *c)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005734 PySTEntryObject *ste = c->u->u_ste;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005735 int flags = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005736 if (ste->ste_type == FunctionBlock) {
Benjamin Peterson1dfd2472015-04-27 21:44:22 -04005737 flags |= CO_NEWLOCALS | CO_OPTIMIZED;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005738 if (ste->ste_nested)
5739 flags |= CO_NESTED;
Yury Selivanoveb636452016-09-08 22:01:51 -07005740 if (ste->ste_generator && !ste->ste_coroutine)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005741 flags |= CO_GENERATOR;
Yury Selivanoveb636452016-09-08 22:01:51 -07005742 if (!ste->ste_generator && ste->ste_coroutine)
5743 flags |= CO_COROUTINE;
5744 if (ste->ste_generator && ste->ste_coroutine)
5745 flags |= CO_ASYNC_GENERATOR;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005746 if (ste->ste_varargs)
5747 flags |= CO_VARARGS;
5748 if (ste->ste_varkeywords)
5749 flags |= CO_VARKEYWORDS;
5750 }
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005752 /* (Only) inherit compilerflags in PyCF_MASK */
5753 flags |= (c->c_flags->cf_flags & PyCF_MASK);
Thomas Wouters5e9f1fa2006-02-28 20:02:27 +00005754
Pablo Galindo90235812020-03-15 04:29:22 +00005755 if ((IS_TOP_LEVEL_AWAIT(c)) &&
Matthias Bussonnier565b4f12019-05-21 13:12:03 -07005756 ste->ste_coroutine &&
5757 !ste->ste_generator) {
5758 flags |= CO_COROUTINE;
5759 }
5760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005761 return flags;
Jeremy Hylton29906ee2001-02-27 04:23:34 +00005762}
5763
INADA Naokic2e16072018-11-26 21:23:22 +09005764// Merge *tuple* with constant cache.
5765// Unlike merge_consts_recursive(), this function doesn't work recursively.
5766static int
5767merge_const_tuple(struct compiler *c, PyObject **tuple)
5768{
5769 assert(PyTuple_CheckExact(*tuple));
5770
5771 PyObject *key = _PyCode_ConstantKey(*tuple);
5772 if (key == NULL) {
5773 return 0;
5774 }
5775
5776 // t is borrowed reference
5777 PyObject *t = PyDict_SetDefault(c->c_const_cache, key, key);
5778 Py_DECREF(key);
5779 if (t == NULL) {
5780 return 0;
5781 }
5782 if (t == key) { // tuple is new constant.
5783 return 1;
5784 }
5785
5786 PyObject *u = PyTuple_GET_ITEM(t, 1);
5787 Py_INCREF(u);
5788 Py_DECREF(*tuple);
5789 *tuple = u;
5790 return 1;
5791}
5792
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005793static PyCodeObject *
Mark Shannon6e8128f2020-07-30 10:03:00 +01005794makecode(struct compiler *c, struct assembler *a, PyObject *consts)
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005796 PyCodeObject *co = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005797 PyObject *names = NULL;
5798 PyObject *varnames = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005799 PyObject *name = NULL;
5800 PyObject *freevars = NULL;
5801 PyObject *cellvars = NULL;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005802 Py_ssize_t nlocals;
5803 int nlocals_int;
5804 int flags;
Pablo Galindocd74e662019-06-01 18:08:04 +01005805 int posorkeywordargcount, posonlyargcount, kwonlyargcount, maxdepth;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005807 names = dict_keys_inorder(c->u->u_names, 0);
5808 varnames = dict_keys_inorder(c->u->u_varnames, 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005809 if (!names || !varnames) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005810 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005811 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005812 cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
5813 if (!cellvars)
5814 goto error;
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005815 freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_GET_SIZE(cellvars));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005816 if (!freevars)
5817 goto error;
Victor Stinnerad9a0662013-11-19 22:23:20 +01005818
INADA Naokic2e16072018-11-26 21:23:22 +09005819 if (!merge_const_tuple(c, &names) ||
5820 !merge_const_tuple(c, &varnames) ||
5821 !merge_const_tuple(c, &cellvars) ||
5822 !merge_const_tuple(c, &freevars))
5823 {
5824 goto error;
5825 }
5826
Serhiy Storchaka5ab81d72016-12-16 16:18:57 +02005827 nlocals = PyDict_GET_SIZE(c->u->u_varnames);
Victor Stinnerad9a0662013-11-19 22:23:20 +01005828 assert(nlocals < INT_MAX);
5829 nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int);
5830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005831 flags = compute_code_flags(c);
5832 if (flags < 0)
5833 goto error;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005834
Mark Shannon6e8128f2020-07-30 10:03:00 +01005835 consts = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
5836 if (consts == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005837 goto error;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005838 }
INADA Naokic2e16072018-11-26 21:23:22 +09005839 if (!merge_const_tuple(c, &consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005840 Py_DECREF(consts);
INADA Naokic2e16072018-11-26 21:23:22 +09005841 goto error;
5842 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005843
Pablo Galindo8c77b8c2019-04-29 13:36:57 +01005844 posonlyargcount = Py_SAFE_DOWNCAST(c->u->u_posonlyargcount, Py_ssize_t, int);
Pablo Galindocd74e662019-06-01 18:08:04 +01005845 posorkeywordargcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int);
Victor Stinnerf8e32212013-11-19 23:56:34 +01005846 kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005847 maxdepth = stackdepth(c);
5848 if (maxdepth < 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01005849 Py_DECREF(consts);
Serhiy Storchaka782d6fe2018-01-11 20:20:13 +02005850 goto error;
5851 }
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005852 co = PyCode_NewWithPosOnlyArgs(posonlyargcount+posorkeywordargcount,
Mark Shannon13bc1392020-01-23 09:25:17 +00005853 posonlyargcount, kwonlyargcount, nlocals_int,
Mark Shannon6e8128f2020-07-30 10:03:00 +01005854 maxdepth, flags, a->a_bytecode, consts, names,
Pablo Galindo4a2edc32019-07-01 11:35:05 +01005855 varnames, freevars, cellvars, c->c_filename,
5856 c->u->u_name, c->u->u_firstlineno, a->a_lnotab);
Mark Shannon6e8128f2020-07-30 10:03:00 +01005857 Py_DECREF(consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005858 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005859 Py_XDECREF(names);
5860 Py_XDECREF(varnames);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005861 Py_XDECREF(name);
5862 Py_XDECREF(freevars);
5863 Py_XDECREF(cellvars);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005864 return co;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005865}
5866
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005867
5868/* For debugging purposes only */
5869#if 0
5870static void
5871dump_instr(const struct instr *i)
5872{
Mark Shannon582aaf12020-08-04 17:30:11 +01005873 const char *jrel = (is_relative_jump(instr)) ? "jrel " : "";
5874 const char *jabs = (is_jump(instr) && !is_relative_jump(instr))? "jabs " : "";
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005875 char arg[128];
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005877 *arg = '\0';
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005878 if (HAS_ARG(i->i_opcode)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005879 sprintf(arg, "arg: %d ", i->i_oparg);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03005880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005881 fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
5882 i->i_lineno, i->i_opcode, arg, jabs, jrel);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005883}
5884
5885static void
5886dump_basicblock(const basicblock *b)
5887{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005888 const char *b_return = b->b_return ? "return " : "";
Pablo Galindo60eb9f12020-06-28 01:55:47 +01005889 fprintf(stderr, "used: %d, depth: %d, offset: %d %s\n",
5890 b->b_iused, b->b_startdepth, b->b_offset, b_return);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005891 if (b->b_instr) {
5892 int i;
5893 for (i = 0; i < b->b_iused; i++) {
5894 fprintf(stderr, " [%02d] ", i);
5895 dump_instr(b->b_instr + i);
5896 }
5897 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00005898}
5899#endif
5900
Mark Shannon5977a792020-12-02 13:31:40 +00005901
5902static int
5903normalize_basic_block(basicblock *bb);
5904
Mark Shannon6e8128f2020-07-30 10:03:00 +01005905static int
5906optimize_cfg(struct assembler *a, PyObject *consts);
5907
Mark Shannon5977a792020-12-02 13:31:40 +00005908static int
5909ensure_exits_have_lineno(struct compiler *c);
5910
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005911static PyCodeObject *
5912assemble(struct compiler *c, int addNone)
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005914 basicblock *b, *entryblock;
5915 struct assembler a;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005916 int j, nblocks;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005917 PyCodeObject *co = NULL;
Mark Shannon6e8128f2020-07-30 10:03:00 +01005918 PyObject *consts = NULL;
Jeremy Hylton64949cb2001-01-25 20:06:59 +00005919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005920 /* Make sure every block that falls off the end returns None.
5921 XXX NEXT_BLOCK() isn't quite right, because if the last
5922 block ends with a jump or return b_next shouldn't set.
5923 */
5924 if (!c->u->u_curblock->b_return) {
Mark Shannon877df852020-11-12 09:43:29 +00005925 c->u->u_lineno = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005926 if (addNone)
Serhiy Storchakad70c2a62018-04-20 16:01:25 +03005927 ADDOP_LOAD_CONST(c, Py_None);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005928 ADDOP(c, RETURN_VALUE);
5929 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005930
Mark Shannon5977a792020-12-02 13:31:40 +00005931 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
5932 if (normalize_basic_block(b)) {
5933 goto error;
5934 }
5935 }
5936
5937 if (ensure_exits_have_lineno(c)) {
5938 goto error;
5939 }
5940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005941 nblocks = 0;
5942 entryblock = NULL;
5943 for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
5944 nblocks++;
5945 entryblock = b;
5946 }
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005948 /* Set firstlineno if it wasn't explicitly set. */
5949 if (!c->u->u_firstlineno) {
Ned Deilydc35cda2016-08-17 17:18:33 -04005950 if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005951 c->u->u_firstlineno = entryblock->b_instr->i_lineno;
Mark Shannon877df852020-11-12 09:43:29 +00005952 else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005953 c->u->u_firstlineno = 1;
5954 }
Mark Shannon5977a792020-12-02 13:31:40 +00005955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005956 if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
5957 goto error;
Mark Shannoncc75ab72020-11-12 19:49:33 +00005958 a.a_entry = entryblock;
5959 a.a_nblocks = nblocks;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005960
Mark Shannon6e8128f2020-07-30 10:03:00 +01005961 consts = consts_dict_keys_inorder(c->u->u_consts);
5962 if (consts == NULL) {
5963 goto error;
5964 }
5965 if (optimize_cfg(&a, consts)) {
5966 goto error;
5967 }
5968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005969 /* Can't modify the bytecode after computing jump offsets. */
5970 assemble_jump_offsets(&a, c);
Tim Petersb6c3cea2001-06-26 03:36:28 +00005971
Mark Shannoncc75ab72020-11-12 19:49:33 +00005972 /* Emit code. */
5973 for(b = entryblock; b != NULL; b = b->b_next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005974 for (j = 0; j < b->b_iused; j++)
5975 if (!assemble_emit(&a, &b->b_instr[j]))
5976 goto error;
5977 }
Mark Shannon877df852020-11-12 09:43:29 +00005978 if (!assemble_line_range(&a)) {
5979 return 0;
5980 }
5981 /* Emit sentinel at end of line number table */
5982 if (!assemble_emit_linetable_pair(&a, 255, -128)) {
5983 goto error;
5984 }
Tim Petersb6c3cea2001-06-26 03:36:28 +00005985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005986 if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
5987 goto error;
Serhiy Storchakaab874002016-09-11 13:48:15 +03005988 if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005989 goto error;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005990
Mark Shannon6e8128f2020-07-30 10:03:00 +01005991 co = makecode(c, &a, consts);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00005992 error:
Mark Shannon6e8128f2020-07-30 10:03:00 +01005993 Py_XDECREF(consts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00005994 assemble_free(&a);
5995 return co;
Jeremy Hyltone36f7782001-01-19 03:21:30 +00005996}
Georg Brandl8334fd92010-12-04 10:26:46 +00005997
5998#undef PyAST_Compile
Benjamin Petersone5024512018-09-12 12:06:42 -07005999PyCodeObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00006000PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
6001 PyArena *arena)
6002{
6003 return PyAST_CompileEx(mod, filename, flags, -1, arena);
6004}
Mark Shannon6e8128f2020-07-30 10:03:00 +01006005
6006
6007/* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
6008 with LOAD_CONST (c1, c2, ... cn).
6009 The consts table must still be in list form so that the
6010 new constant (c1, c2, ... cn) can be appended.
6011 Called with codestr pointing to the first LOAD_CONST.
6012*/
6013static int
6014fold_tuple_on_constants(struct instr *inst,
6015 int n, PyObject *consts)
6016{
6017 /* Pre-conditions */
6018 assert(PyList_CheckExact(consts));
6019 assert(inst[n].i_opcode == BUILD_TUPLE);
6020 assert(inst[n].i_oparg == n);
6021
6022 for (int i = 0; i < n; i++) {
6023 if (inst[i].i_opcode != LOAD_CONST) {
6024 return 0;
6025 }
6026 }
6027
6028 /* Buildup new tuple of constants */
6029 PyObject *newconst = PyTuple_New(n);
6030 if (newconst == NULL) {
6031 return -1;
6032 }
6033 for (int i = 0; i < n; i++) {
6034 int arg = inst[i].i_oparg;
6035 PyObject *constant = PyList_GET_ITEM(consts, arg);
6036 Py_INCREF(constant);
6037 PyTuple_SET_ITEM(newconst, i, constant);
6038 }
6039 Py_ssize_t index = PyList_GET_SIZE(consts);
Victor Stinner71f2ff42020-09-23 14:06:55 +02006040 if ((size_t)index >= (size_t)INT_MAX - 1) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006041 Py_DECREF(newconst);
6042 PyErr_SetString(PyExc_OverflowError, "too many constants");
6043 return -1;
6044 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006045 if (PyList_Append(consts, newconst)) {
6046 Py_DECREF(newconst);
6047 return -1;
6048 }
6049 Py_DECREF(newconst);
6050 for (int i = 0; i < n; i++) {
6051 inst[i].i_opcode = NOP;
6052 }
6053 inst[n].i_opcode = LOAD_CONST;
Victor Stinner71f2ff42020-09-23 14:06:55 +02006054 inst[n].i_oparg = (int)index;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006055 return 0;
6056}
6057
Mark Shannon28b75c82020-12-23 11:43:10 +00006058
6059static int
6060eliminate_jump_to_jump(basicblock *bb, int opcode) {
6061 assert (bb->b_iused > 0);
6062 struct instr *inst = &bb->b_instr[bb->b_iused-1];
6063 assert (is_jump(inst));
6064 assert (inst->i_target->b_iused > 0);
6065 struct instr *target = &inst->i_target->b_instr[0];
6066 if (inst->i_target == target->i_target) {
6067 /* Nothing to do */
6068 return 0;
6069 }
6070 int lineno = target->i_lineno;
6071 if (add_jump_to_block(bb, opcode, lineno, target->i_target) == 0) {
6072 return -1;
6073 }
6074 assert (bb->b_iused >= 2);
6075 bb->b_instr[bb->b_iused-2].i_opcode = NOP;
6076 return 0;
6077}
6078
Mark Shannoncc75ab72020-11-12 19:49:33 +00006079/* Maximum size of basic block that should be copied in optimizer */
6080#define MAX_COPY_SIZE 4
Mark Shannon6e8128f2020-07-30 10:03:00 +01006081
6082/* Optimization */
6083static int
6084optimize_basic_block(basicblock *bb, PyObject *consts)
6085{
6086 assert(PyList_CheckExact(consts));
6087 struct instr nop;
6088 nop.i_opcode = NOP;
6089 struct instr *target;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006090 for (int i = 0; i < bb->b_iused; i++) {
6091 struct instr *inst = &bb->b_instr[i];
6092 int oparg = inst->i_oparg;
6093 int nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
Mark Shannon582aaf12020-08-04 17:30:11 +01006094 if (is_jump(inst)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006095 /* Skip over empty basic blocks. */
6096 while (inst->i_target->b_iused == 0) {
6097 inst->i_target = inst->i_target->b_next;
6098 }
6099 target = &inst->i_target->b_instr[0];
6100 }
6101 else {
6102 target = &nop;
6103 }
6104 switch (inst->i_opcode) {
Mark Shannon266b4622020-11-17 19:30:14 +00006105 /* Remove LOAD_CONST const; conditional jump */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006106 case LOAD_CONST:
Mark Shannon266b4622020-11-17 19:30:14 +00006107 {
6108 PyObject* cnt;
6109 int is_true;
6110 int jump_if_true;
6111 switch(nextop) {
6112 case POP_JUMP_IF_FALSE:
6113 case POP_JUMP_IF_TRUE:
6114 cnt = PyList_GET_ITEM(consts, oparg);
6115 is_true = PyObject_IsTrue(cnt);
6116 if (is_true == -1) {
6117 goto error;
6118 }
6119 inst->i_opcode = NOP;
6120 jump_if_true = nextop == POP_JUMP_IF_TRUE;
6121 if (is_true == jump_if_true) {
6122 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6123 bb->b_nofallthrough = 1;
6124 }
6125 else {
6126 bb->b_instr[i+1].i_opcode = NOP;
6127 }
6128 break;
6129 case JUMP_IF_FALSE_OR_POP:
6130 case JUMP_IF_TRUE_OR_POP:
6131 cnt = PyList_GET_ITEM(consts, oparg);
6132 is_true = PyObject_IsTrue(cnt);
6133 if (is_true == -1) {
6134 goto error;
6135 }
6136 jump_if_true = nextop == JUMP_IF_TRUE_OR_POP;
6137 if (is_true == jump_if_true) {
6138 bb->b_instr[i+1].i_opcode = JUMP_ABSOLUTE;
6139 bb->b_nofallthrough = 1;
6140 }
6141 else {
6142 inst->i_opcode = NOP;
6143 bb->b_instr[i+1].i_opcode = NOP;
6144 }
6145 break;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006146 }
6147 break;
Mark Shannon266b4622020-11-17 19:30:14 +00006148 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006149
6150 /* Try to fold tuples of constants.
6151 Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
6152 Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
6153 Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
6154 case BUILD_TUPLE:
6155 if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
6156 switch(oparg) {
6157 case 1:
6158 inst->i_opcode = NOP;
6159 bb->b_instr[i+1].i_opcode = NOP;
6160 break;
6161 case 2:
6162 inst->i_opcode = ROT_TWO;
6163 bb->b_instr[i+1].i_opcode = NOP;
6164 break;
6165 case 3:
6166 inst->i_opcode = ROT_THREE;
6167 bb->b_instr[i+1].i_opcode = ROT_TWO;
6168 }
6169 break;
6170 }
6171 if (i >= oparg) {
6172 if (fold_tuple_on_constants(inst-oparg, oparg, consts)) {
6173 goto error;
6174 }
6175 }
6176 break;
6177
6178 /* Simplify conditional jump to conditional jump where the
6179 result of the first test implies the success of a similar
6180 test or the failure of the opposite test.
6181 Arises in code like:
6182 "a and b or c"
6183 "(a and b) and c"
6184 "(a or b) or c"
6185 "(a or b) and c"
6186 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
6187 --> x:JUMP_IF_FALSE_OR_POP z
6188 x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
6189 --> x:POP_JUMP_IF_FALSE y+1
6190 where y+1 is the instruction following the second test.
6191 */
6192 case JUMP_IF_FALSE_OR_POP:
6193 switch(target->i_opcode) {
6194 case POP_JUMP_IF_FALSE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006195 if (inst->i_lineno == target->i_lineno) {
6196 *inst = *target;
6197 i--;
6198 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006199 break;
6200 case JUMP_ABSOLUTE:
6201 case JUMP_FORWARD:
6202 case JUMP_IF_FALSE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006203 if (inst->i_lineno == target->i_lineno &&
6204 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006205 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006206 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006207 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006208 break;
6209 case JUMP_IF_TRUE_OR_POP:
6210 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006211 if (inst->i_lineno == target->i_lineno) {
6212 inst->i_opcode = POP_JUMP_IF_FALSE;
6213 inst->i_target = inst->i_target->b_next;
6214 --i;
6215 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006216 break;
6217 }
6218 break;
6219
6220 case JUMP_IF_TRUE_OR_POP:
6221 switch(target->i_opcode) {
6222 case POP_JUMP_IF_TRUE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006223 if (inst->i_lineno == target->i_lineno) {
6224 *inst = *target;
6225 i--;
6226 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006227 break;
6228 case JUMP_ABSOLUTE:
6229 case JUMP_FORWARD:
6230 case JUMP_IF_TRUE_OR_POP:
Mark Shannon28b75c82020-12-23 11:43:10 +00006231 if (inst->i_lineno == target->i_lineno &&
6232 inst->i_target != target->i_target) {
Mark Shannon266b4622020-11-17 19:30:14 +00006233 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006234 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006235 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006236 break;
6237 case JUMP_IF_FALSE_OR_POP:
6238 assert (inst->i_target->b_iused == 1);
Mark Shannon28b75c82020-12-23 11:43:10 +00006239 if (inst->i_lineno == target->i_lineno) {
6240 inst->i_opcode = POP_JUMP_IF_TRUE;
6241 inst->i_target = inst->i_target->b_next;
6242 --i;
6243 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006244 break;
6245 }
6246 break;
6247
6248 case POP_JUMP_IF_FALSE:
6249 switch(target->i_opcode) {
6250 case JUMP_ABSOLUTE:
6251 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006252 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006253 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006254 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006255 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006256 break;
6257 }
6258 break;
6259
6260 case POP_JUMP_IF_TRUE:
6261 switch(target->i_opcode) {
6262 case JUMP_ABSOLUTE:
6263 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006264 if (inst->i_lineno == target->i_lineno) {
Mark Shannon266b4622020-11-17 19:30:14 +00006265 inst->i_target = target->i_target;
Mark Shannon28b75c82020-12-23 11:43:10 +00006266 i--;
Mark Shannon266b4622020-11-17 19:30:14 +00006267 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006268 break;
6269 }
6270 break;
6271
6272 case JUMP_ABSOLUTE:
6273 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006274 assert (i == bb->b_iused-1);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006275 switch(target->i_opcode) {
6276 case JUMP_FORWARD:
Mark Shannon28b75c82020-12-23 11:43:10 +00006277 if (eliminate_jump_to_jump(bb, inst->i_opcode)) {
6278 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006279 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006280 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006281
Mark Shannon6e8128f2020-07-30 10:03:00 +01006282 case JUMP_ABSOLUTE:
Mark Shannon28b75c82020-12-23 11:43:10 +00006283 if (eliminate_jump_to_jump(bb, JUMP_ABSOLUTE)) {
6284 goto error;
Mark Shannon266b4622020-11-17 19:30:14 +00006285 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006286 break;
Mark Shannon28b75c82020-12-23 11:43:10 +00006287 default:
6288 if (inst->i_target->b_exit && inst->i_target->b_iused <= MAX_COPY_SIZE) {
6289 basicblock *to_copy = inst->i_target;
6290 inst->i_opcode = NOP;
6291 for (i = 0; i < to_copy->b_iused; i++) {
6292 int index = compiler_next_instr(bb);
6293 if (index < 0) {
6294 return -1;
6295 }
6296 bb->b_instr[index] = to_copy->b_instr[i];
6297 }
6298 bb->b_exit = 1;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006299 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006300 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006301 }
6302 }
6303 return 0;
6304error:
6305 return -1;
6306}
6307
6308
6309static void
6310clean_basic_block(basicblock *bb) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006311 /* Remove NOPs. */
Mark Shannon6e8128f2020-07-30 10:03:00 +01006312 int dest = 0;
Mark Shannon877df852020-11-12 09:43:29 +00006313 int prev_lineno = -1;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006314 for (int src = 0; src < bb->b_iused; src++) {
Mark Shannon877df852020-11-12 09:43:29 +00006315 int lineno = bb->b_instr[src].i_lineno;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006316 if (bb->b_instr[src].i_opcode == NOP) {
Mark Shannon266b4622020-11-17 19:30:14 +00006317 /* Eliminate no-op if it doesn't have a line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006318 if (lineno < 0) {
6319 continue;
6320 }
Mark Shannon266b4622020-11-17 19:30:14 +00006321 /* or, if the previous instruction had the same line number. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006322 if (prev_lineno == lineno) {
6323 continue;
6324 }
Mark Shannon266b4622020-11-17 19:30:14 +00006325 /* or, if the next instruction has same line number or no line number */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006326 if (src < bb->b_iused - 1) {
6327 int next_lineno = bb->b_instr[src+1].i_lineno;
6328 if (next_lineno < 0 || next_lineno == lineno) {
6329 bb->b_instr[src+1].i_lineno = lineno;
6330 continue;
Mark Shannon877df852020-11-12 09:43:29 +00006331 }
6332 }
Mark Shannon266b4622020-11-17 19:30:14 +00006333 else {
6334 basicblock* next = bb->b_next;
6335 while (next && next->b_iused == 0) {
6336 next = next->b_next;
6337 }
6338 /* or if last instruction in BB and next BB has same line number */
6339 if (next) {
6340 if (lineno == next->b_instr[0].i_lineno) {
6341 continue;
6342 }
6343 }
6344 }
6345
Mark Shannon6e8128f2020-07-30 10:03:00 +01006346 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006347 if (dest != src) {
6348 bb->b_instr[dest] = bb->b_instr[src];
6349 }
6350 dest++;
6351 prev_lineno = lineno;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006352 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006353 assert(dest <= bb->b_iused);
6354 bb->b_iused = dest;
6355}
6356
Mark Shannon266b4622020-11-17 19:30:14 +00006357static int
6358normalize_basic_block(basicblock *bb) {
6359 /* Mark blocks as exit and/or nofallthrough.
6360 Raise SystemError if CFG is malformed. */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006361 for (int i = 0; i < bb->b_iused; i++) {
6362 switch(bb->b_instr[i].i_opcode) {
6363 case RETURN_VALUE:
6364 case RAISE_VARARGS:
6365 case RERAISE:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006366 bb->b_exit = 1;
Mark Shannon5977a792020-12-02 13:31:40 +00006367 bb->b_nofallthrough = 1;
6368 break;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006369 case JUMP_ABSOLUTE:
6370 case JUMP_FORWARD:
Mark Shannoncc75ab72020-11-12 19:49:33 +00006371 bb->b_nofallthrough = 1;
Mark Shannon266b4622020-11-17 19:30:14 +00006372 /* fall through */
6373 case POP_JUMP_IF_FALSE:
6374 case POP_JUMP_IF_TRUE:
6375 case JUMP_IF_FALSE_OR_POP:
6376 case JUMP_IF_TRUE_OR_POP:
Mark Shannon5977a792020-12-02 13:31:40 +00006377 case FOR_ITER:
Mark Shannon266b4622020-11-17 19:30:14 +00006378 if (i != bb->b_iused-1) {
6379 PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
6380 return -1;
6381 }
Mark Shannon5977a792020-12-02 13:31:40 +00006382 /* Skip over empty basic blocks. */
6383 while (bb->b_instr[i].i_target->b_iused == 0) {
6384 bb->b_instr[i].i_target = bb->b_instr[i].i_target->b_next;
6385 }
6386
Mark Shannoncc75ab72020-11-12 19:49:33 +00006387 }
6388 }
Mark Shannon266b4622020-11-17 19:30:14 +00006389 return 0;
Mark Shannoncc75ab72020-11-12 19:49:33 +00006390}
6391
Mark Shannon6e8128f2020-07-30 10:03:00 +01006392static int
6393mark_reachable(struct assembler *a) {
6394 basicblock **stack, **sp;
6395 sp = stack = (basicblock **)PyObject_Malloc(sizeof(basicblock *) * a->a_nblocks);
6396 if (stack == NULL) {
6397 return -1;
6398 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006399 a->a_entry->b_reachable = 1;
6400 *sp++ = a->a_entry;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006401 while (sp > stack) {
6402 basicblock *b = *(--sp);
Mark Shannoncc75ab72020-11-12 19:49:33 +00006403 if (b->b_next && !b->b_nofallthrough && b->b_next->b_reachable == 0) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006404 b->b_next->b_reachable = 1;
6405 *sp++ = b->b_next;
6406 }
6407 for (int i = 0; i < b->b_iused; i++) {
6408 basicblock *target;
Mark Shannon582aaf12020-08-04 17:30:11 +01006409 if (is_jump(&b->b_instr[i])) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006410 target = b->b_instr[i].i_target;
6411 if (target->b_reachable == 0) {
6412 target->b_reachable = 1;
6413 *sp++ = target;
6414 }
6415 }
6416 }
6417 }
6418 PyObject_Free(stack);
6419 return 0;
6420}
6421
Mark Shannon5977a792020-12-02 13:31:40 +00006422/* If an instruction has no line number, but it's predecessor in the BB does,
6423 * then copy the line number. This reduces the size of the line number table,
6424 * but has no impact on the generated line number events.
6425 */
6426static void
6427minimize_lineno_table(struct assembler *a) {
6428 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6429 int prev_lineno = -1;
6430 for (int i = 0; i < b->b_iused; i++) {
6431 if (b->b_instr[i].i_lineno < 0) {
6432 b->b_instr[i].i_lineno = prev_lineno;
6433 }
6434 else {
6435 prev_lineno = b->b_instr[i].i_lineno;
6436 }
6437 }
Mark Shannon6e8128f2020-07-30 10:03:00 +01006438
Mark Shannon5977a792020-12-02 13:31:40 +00006439 }
6440}
6441
6442/* Perform optimizations on a control flow graph.
Mark Shannon6e8128f2020-07-30 10:03:00 +01006443 The consts object should still be in list form to allow new constants
6444 to be appended.
6445
6446 All transformations keep the code size the same or smaller.
6447 For those that reduce size, the gaps are initially filled with
6448 NOPs. Later those NOPs are removed.
6449*/
6450
6451static int
6452optimize_cfg(struct assembler *a, PyObject *consts)
6453{
Mark Shannoncc75ab72020-11-12 19:49:33 +00006454 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
Mark Shannoncc75ab72020-11-12 19:49:33 +00006455 if (optimize_basic_block(b, consts)) {
Mark Shannon6e8128f2020-07-30 10:03:00 +01006456 return -1;
6457 }
Mark Shannoncc75ab72020-11-12 19:49:33 +00006458 clean_basic_block(b);
6459 assert(b->b_reachable == 0);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006460 }
6461 if (mark_reachable(a)) {
6462 return -1;
6463 }
6464 /* Delete unreachable instructions */
Mark Shannoncc75ab72020-11-12 19:49:33 +00006465 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6466 if (b->b_reachable == 0) {
6467 b->b_iused = 0;
Om Gc71581c2020-12-16 17:48:05 +05306468 b->b_nofallthrough = 0;
Mark Shannon6e8128f2020-07-30 10:03:00 +01006469 }
6470 }
Om Gc71581c2020-12-16 17:48:05 +05306471 /* Delete jump instructions made redundant by previous step. If a non-empty
6472 block ends with a jump instruction, check if the next non-empty block
6473 reached through normal flow control is the target of that jump. If it
6474 is, then the jump instruction is redundant and can be deleted.
6475 */
6476 for (basicblock *b = a->a_entry; b != NULL; b = b->b_next) {
6477 if (b->b_iused > 0) {
6478 struct instr *b_last_instr = &b->b_instr[b->b_iused - 1];
6479 if (b_last_instr->i_opcode == POP_JUMP_IF_FALSE ||
6480 b_last_instr->i_opcode == POP_JUMP_IF_TRUE ||
6481 b_last_instr->i_opcode == JUMP_ABSOLUTE ||
6482 b_last_instr->i_opcode == JUMP_FORWARD) {
6483 basicblock *b_next_act = b->b_next;
6484 while (b_next_act != NULL && b_next_act->b_iused == 0) {
6485 b_next_act = b_next_act->b_next;
6486 }
6487 if (b_last_instr->i_target == b_next_act) {
6488 b->b_nofallthrough = 0;
6489 switch(b_last_instr->i_opcode) {
6490 case POP_JUMP_IF_FALSE:
6491 case POP_JUMP_IF_TRUE:
6492 b_last_instr->i_opcode = POP_TOP;
6493 b_last_instr->i_target = NULL;
6494 b_last_instr->i_oparg = 0;
6495 break;
6496 case JUMP_ABSOLUTE:
6497 case JUMP_FORWARD:
6498 b_last_instr->i_opcode = NOP;
6499 clean_basic_block(b);
6500 break;
6501 }
6502 /* The blocks after this one are now reachable through it */
6503 b_next_act = b->b_next;
6504 while (b_next_act != NULL && b_next_act->b_iused == 0) {
6505 b_next_act->b_reachable = 1;
6506 b_next_act = b_next_act->b_next;
6507 }
6508 }
6509 }
6510 }
6511 }
Mark Shannon5977a792020-12-02 13:31:40 +00006512 minimize_lineno_table(a);
Mark Shannon6e8128f2020-07-30 10:03:00 +01006513 return 0;
6514}
6515
Mark Shannon5977a792020-12-02 13:31:40 +00006516static inline int
6517is_exit_without_lineno(basicblock *b) {
6518 return b->b_exit && b->b_instr[0].i_lineno < 0;
6519}
6520
6521/* PEP 626 mandates that the f_lineno of a frame is correct
6522 * after a frame terminates. It would be prohibitively expensive
6523 * to continuously update the f_lineno field at runtime,
6524 * so we make sure that all exiting instruction (raises and returns)
6525 * have a valid line number, allowing us to compute f_lineno lazily.
6526 * We can do this by duplicating the exit blocks without line number
6527 * so that none have more than one predecessor. We can then safely
6528 * copy the line number from the sole predecessor block.
6529 */
6530static int
6531ensure_exits_have_lineno(struct compiler *c)
6532{
Mark Shannoneaccc122020-12-04 15:22:12 +00006533 basicblock *entry = NULL;
Mark Shannon5977a792020-12-02 13:31:40 +00006534 /* Copy all exit blocks without line number that are targets of a jump.
6535 */
6536 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6537 if (b->b_iused > 0 && is_jump(&b->b_instr[b->b_iused-1])) {
6538 switch (b->b_instr[b->b_iused-1].i_opcode) {
6539 /* Note: Only actual jumps, not exception handlers */
6540 case SETUP_ASYNC_WITH:
6541 case SETUP_WITH:
6542 case SETUP_FINALLY:
6543 continue;
6544 }
6545 basicblock *target = b->b_instr[b->b_iused-1].i_target;
6546 if (is_exit_without_lineno(target)) {
6547 basicblock *new_target = compiler_copy_block(c, target);
6548 if (new_target == NULL) {
6549 return -1;
6550 }
6551 new_target->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6552 b->b_instr[b->b_iused-1].i_target = new_target;
6553 }
6554 }
Mark Shannoneaccc122020-12-04 15:22:12 +00006555 entry = b;
6556 }
6557 assert(entry != NULL);
6558 if (is_exit_without_lineno(entry)) {
6559 entry->b_instr[0].i_lineno = c->u->u_firstlineno;
Mark Shannon5977a792020-12-02 13:31:40 +00006560 }
Mark Shannonee9f98d2021-01-05 12:04:10 +00006561 /* Eliminate empty blocks */
6562 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6563 while (b->b_next && b->b_next->b_iused == 0) {
6564 b->b_next = b->b_next->b_next;
6565 }
6566 }
Mark Shannon5977a792020-12-02 13:31:40 +00006567 /* Any remaining reachable exit blocks without line number can only be reached by
6568 * fall through, and thus can only have a single predecessor */
6569 for (basicblock *b = c->u->u_blocks; b != NULL; b = b->b_list) {
6570 if (!b->b_nofallthrough && b->b_next && b->b_iused > 0) {
6571 if (is_exit_without_lineno(b->b_next)) {
6572 assert(b->b_next->b_iused > 0);
6573 b->b_next->b_instr[0].i_lineno = b->b_instr[b->b_iused-1].i_lineno;
6574 }
6575 }
6576 }
6577 return 0;
6578}
6579
6580
Mark Shannon6e8128f2020-07-30 10:03:00 +01006581/* Retained for API compatibility.
6582 * Optimization is now done in optimize_cfg */
6583
6584PyObject *
6585PyCode_Optimize(PyObject *code, PyObject* Py_UNUSED(consts),
6586 PyObject *Py_UNUSED(names), PyObject *Py_UNUSED(lnotab_obj))
6587{
6588 Py_INCREF(code);
6589 return code;
6590}
6591